'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { format } from 'date-fns';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Building2, Plus } from 'lucide-react';
import { toast } from 'sonner';

import {
  Table,
  TableHeader,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
} from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { EmptyState } from '@/components/shared/empty-state';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { CompanyPicker } from '@/components/companies/company-picker';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';

interface ClientCompaniesTabProps {
  clientId: string;
  companies: Array<{
    membershipId: string;
    role: string;
    isPrimary: boolean;
    startDate: string | Date;
    company: {
      id: string;
      name: string;
      legalName: string | null;
      status: string;
    };
  }>;
}

function formatSince(startDate: string | Date): string {
  const d = typeof startDate === 'string' ? new Date(startDate) : startDate;
  if (Number.isNaN(d.getTime())) return '-';
  return format(d, 'MMM d, yyyy');
}

export function ClientCompaniesTab({ clientId, companies }: ClientCompaniesTabProps) {
  const routeParams = useParams<{ portSlug: string }>();
  const portSlug = routeParams?.portSlug ?? '';
  const [linkOpen, setLinkOpen] = useState(false);

  if (companies.length === 0) {
    return (
      <>
        <EmptyState
          title="No company memberships"
          description="This client is not affiliated with any companies yet."
          icon={Building2}
          action={{ label: 'Link to a company', onClick: () => setLinkOpen(true) }}
        />
        <LinkCompanyDialog
          open={linkOpen}
          onOpenChange={setLinkOpen}
          clientId={clientId}
          portSlug={portSlug}
        />
      </>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-medium">Company affiliations</h3>
        <Button size="sm" variant="outline" onClick={() => setLinkOpen(true)}>
          <Plus className="mr-1.5 h-3.5 w-3.5" aria-hidden />
          Link to company
        </Button>
      </div>
      <LinkCompanyDialog
        open={linkOpen}
        onOpenChange={setLinkOpen}
        clientId={clientId}
        portSlug={portSlug}
      />
      <div className="rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Company</TableHead>
              <TableHead>Role</TableHead>
              <TableHead>Primary</TableHead>
              <TableHead>Since</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {companies.map((m) => (
              <TableRow key={m.membershipId}>
                <TableCell>
                  <Link
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    href={`/${portSlug}/companies/${m.company.id}` as any}
                    className="text-primary hover:underline"
                  >
                    {m.company.name}
                  </Link>
                  {m.company.legalName && (
                    <span className="ml-2 text-xs text-muted-foreground">
                      ({m.company.legalName})
                    </span>
                  )}
                </TableCell>
                <TableCell className="capitalize">{m.role.replace('_', ' ')}</TableCell>
                <TableCell>
                  {m.isPrimary ? (
                    <Badge variant="secondary" className="text-xs">
                      Primary
                    </Badge>
                  ) : (
                    <span className="text-muted-foreground">-</span>
                  )}
                </TableCell>
                <TableCell className="text-muted-foreground text-sm">
                  {formatSince(m.startDate)}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}

interface LinkCompanyDialogProps {
  open: boolean;
  onOpenChange: (next: boolean) => void;
  clientId: string;
  portSlug: string;
}

const MEMBERSHIP_ROLES = [
  { value: 'director', label: 'Director' },
  { value: 'shareholder', label: 'Shareholder' },
  { value: 'employee', label: 'Employee' },
  { value: 'agent', label: 'Agent' },
  { value: 'beneficial_owner', label: 'Beneficial owner' },
  { value: 'authorised_signatory', label: 'Authorised signatory' },
  { value: 'other', label: 'Other' },
];

function LinkCompanyDialog({ open, onOpenChange, clientId, portSlug }: LinkCompanyDialogProps) {
  const [companyId, setCompanyId] = useState<string | null>(null);
  const [role, setRole] = useState<string>('director');
  const [isPrimary, setIsPrimary] = useState(false);
  const qc = useQueryClient();

  const create = useMutation({
    mutationFn: async () => {
      if (!companyId) throw new Error('Pick a company');
      await apiFetch(`/api/v1/companies/${companyId}/members`, {
        method: 'POST',
        body: { clientId, role, isPrimary },
      });
    },
    onSuccess: () => {
      toast.success('Membership added');
      void qc.invalidateQueries({ queryKey: ['clients', clientId] });
      setCompanyId(null);
      setRole('director');
      setIsPrimary(false);
      onOpenChange(false);
    },
    onError: (err) => toastError(err),
  });

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Link client to a company</DialogTitle>
          <DialogDescription>
            Pick an existing company or{' '}
            <Link
              /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
              href={`/${portSlug}/companies?create=1` as any}
              className="text-primary hover:underline"
            >
              create a new one
            </Link>
            , then choose this client&apos;s role in it.
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-3 py-2">
          <div className="space-y-1">
            <Label>Company</Label>
            <CompanyPicker value={companyId} onChange={setCompanyId} />
          </div>
          <div className="space-y-1">
            <Label>Role</Label>
            <Select value={role} onValueChange={setRole}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {MEMBERSHIP_ROLES.map((r) => (
                  <SelectItem key={r.value} value={r.value}>
                    {r.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <label className="flex items-center gap-2 text-sm">
            <input
              type="checkbox"
              checked={isPrimary}
              onChange={(e) => setIsPrimary(e.target.checked)}
            />
            Set as primary affiliation
          </label>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button onClick={() => create.mutate()} disabled={create.isPending || !companyId}>
            Link
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
