'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useParams } from 'next/navigation';
import { Loader2, ArrowLeftRight } from 'lucide-react';

import { Button } from '@/components/ui/button';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { EmptyState } from '@/components/shared/empty-state';
import { OwnerLink } from '@/components/yachts/yacht-detail-header';
import { YachtTransferDialog } from '@/components/yachts/yacht-transfer-dialog';
import { PermissionGate } from '@/components/shared/permission-gate';
import { apiFetch } from '@/lib/api/client';

interface OwnershipHistoryRow {
  id: string;
  yachtId: string;
  ownerType: 'client' | 'company';
  ownerId: string;
  startDate: string;
  endDate: string | null;
  transferReason: string | null;
  transferNotes: string | null;
  createdBy: string;
  createdAt: string;
}

interface YachtOwnershipHistoryProps {
  yachtId: string;
}

const REASON_LABELS: Record<string, string> = {
  sale: 'Sale',
  inheritance: 'Inheritance',
  gift: 'Gift',
  company_restructure: 'Company restructure',
  other: 'Other',
};

function formatDate(value: string | null): string {
  if (!value) return '-';
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return date.toLocaleDateString();
}

export function YachtOwnershipHistory({ yachtId }: YachtOwnershipHistoryProps) {
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';
  const [transferOpen, setTransferOpen] = useState(false);

  const { data, isLoading } = useQuery<OwnershipHistoryRow[]>({
    queryKey: ['yachts', yachtId, 'ownership-history'],
    queryFn: () =>
      apiFetch<{ data: OwnershipHistoryRow[] }>(`/api/v1/yachts/${yachtId}/ownership-history`).then(
        (r) => r.data,
      ),
  });

  const currentOwnerRow = data?.find((r) => r.endDate === null);
  const currentOwner = currentOwnerRow
    ? { type: currentOwnerRow.ownerType, id: currentOwnerRow.ownerId }
    : undefined;

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" aria-hidden />
      </div>
    );
  }

  if (!data || data.length === 0) {
    return (
      <>
        <EmptyState
          title="No ownership history"
          description="This yacht's ownership transfers will appear here."
          action={{ label: 'Transfer ownership', onClick: () => setTransferOpen(true) }}
        />
        <YachtTransferDialog
          open={transferOpen}
          onOpenChange={setTransferOpen}
          yachtId={yachtId}
          currentOwner={currentOwner}
        />
      </>
    );
  }

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-end">
        <PermissionGate resource="yachts" action="edit">
          <Button size="sm" onClick={() => setTransferOpen(true)} className="gap-1.5">
            <ArrowLeftRight className="size-4" aria-hidden />
            Transfer ownership
          </Button>
        </PermissionGate>
      </div>
      <div className="rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Start Date</TableHead>
              <TableHead>End Date</TableHead>
              <TableHead>Owner</TableHead>
              <TableHead>Reason</TableHead>
              <TableHead>Notes</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {data.map((row) => (
              <TableRow key={row.id}>
                <TableCell>{formatDate(row.startDate)}</TableCell>
                <TableCell>
                  {row.endDate ? (
                    formatDate(row.endDate)
                  ) : (
                    <Badge variant="secondary" className="text-xs">
                      Current
                    </Badge>
                  )}
                </TableCell>
                <TableCell>
                  <OwnerLink portSlug={portSlug} type={row.ownerType} id={row.ownerId} />
                </TableCell>
                <TableCell className="text-sm text-muted-foreground">
                  {row.transferReason
                    ? (REASON_LABELS[row.transferReason] ?? row.transferReason)
                    : '-'}
                </TableCell>
                <TableCell className="text-sm text-muted-foreground max-w-[320px] truncate">
                  {row.transferNotes ?? '-'}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
      <YachtTransferDialog
        open={transferOpen}
        onOpenChange={setTransferOpen}
        yachtId={yachtId}
        currentOwner={currentOwner}
      />
    </div>
  );
}
