'use client';

import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { useQuery } from '@tanstack/react-query';

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { EmptyState } from '@/components/shared/empty-state';
import { apiFetch } from '@/lib/api/client';

export interface TenancyRow {
  id: string;
  berthId: string;
  portId: string;
  clientId: string;
  yachtId: string;
  status: 'pending' | 'active' | 'ended' | 'cancelled';
  startDate: string;
  endDate: string | null;
  tenureType: string;
  contractFileId: string | null;
  notes: string | null;
  createdAt: string;
}

export interface TenancyListProps {
  tenancies: TenancyRow[];
  showBerth?: boolean;
  portSlug?: string;
  emptyMessage?: string;
}

/**
 * Renders a client's name as a link by fetching the client record.
 * Uses TanStack Query cache for memoization of repeated clientId queries.
 */
export function ClientLink({ clientId, portSlug }: { clientId: string; portSlug: string }) {
  const { data } = useQuery<{ fullName: string }>({
    queryKey: ['clients', clientId, 'name-only'],
    queryFn: () =>
      apiFetch<{ data: { fullName: string } }>(`/api/v1/clients/${clientId}`).then((r) => r.data),
  });

  return (
    <Link
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      href={`/${portSlug}/clients/${clientId}` as any}
      className="text-primary hover:underline"
    >
      {data?.fullName ?? `Client ${clientId.slice(0, 8)}`}
    </Link>
  );
}

/**
 * Renders a yacht's name as a link by fetching the yacht record.
 */
export function YachtLink({ yachtId, portSlug }: { yachtId: string; portSlug: string }) {
  const { data } = useQuery<{ name: string }>({
    queryKey: ['yachts', yachtId, 'name-only'],
    queryFn: () =>
      apiFetch<{ data: { name: string } }>(`/api/v1/yachts/${yachtId}`).then((r) => r.data),
  });

  return (
    <Link
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      href={`/${portSlug}/yachts/${yachtId}` as any}
      className="text-primary hover:underline"
    >
      {data?.name ?? `Yacht ${yachtId.slice(0, 8)}`}
    </Link>
  );
}

/**
 * Renders a berth's mooring number as a link by fetching the berth record.
 */
export function BerthLink({ berthId, portSlug }: { berthId: string; portSlug: string }) {
  const { data } = useQuery<{ mooringNumber: string }>({
    queryKey: ['berths', berthId, 'name-only'],
    queryFn: () =>
      apiFetch<{ data: { mooringNumber: string } }>(`/api/v1/berths/${berthId}`).then(
        (r) => r.data,
      ),
  });

  return (
    <Link
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      href={`/${portSlug}/berths/${berthId}` as any}
      className="text-primary hover:underline"
    >
      {data?.mooringNumber ?? `Berth ${berthId.slice(0, 8)}`}
    </Link>
  );
}

/**
 * Renders a status badge with appropriate color coding.
 */
function StatusBadge({ status }: { status: TenancyRow['status'] }) {
  const colorMap: Record<TenancyRow['status'], string> = {
    pending: 'bg-gray-100 text-gray-800',
    active: 'bg-green-100 text-green-800',
    ended: 'bg-blue-100 text-blue-800',
    cancelled: 'bg-red-100 text-red-800',
  };

  const color = colorMap[status];
  const label = status.charAt(0).toUpperCase() + status.slice(1);

  return (
    <span className={`inline-block rounded-full px-2 py-0.5 text-xs font-medium ${color}`}>
      {label}
    </span>
  );
}

/**
 * Pretty-prints tenure type for display.
 */
function prettyTenure(tenureType: string): string {
  const tenureMap: Record<string, string> = {
    permanent: 'Permanent',
    fixed_term: 'Fixed term',
    seasonal: 'Seasonal',
  };
  return tenureMap[tenureType] ?? tenureType;
}

/**
 * Formats a date range as "{startDate} → {endDate or 'ongoing'}".
 */
function formatDateRange(startDate: string, endDate: string | null): string {
  const start = new Date(startDate).toLocaleDateString();
  const end = endDate ? new Date(endDate).toLocaleDateString() : 'ongoing';
  return `${start} → ${end}`;
}

export function TenancyList({
  tenancies,
  showBerth = false,
  portSlug: portSlugProp,
  emptyMessage,
}: TenancyListProps) {
  const routeParams = useParams<{ portSlug: string }>();
  const portSlug = portSlugProp ?? routeParams?.portSlug ?? '';
  const router = useRouter();

  if (tenancies.length === 0) {
    return <EmptyState title="No tenancies" description={emptyMessage ?? 'No tenancies yet.'} />;
  }

  // Row-level navigation: clicking anywhere on the row (except inside
  // an inner `<a>` or `<button>`) opens the tenancy detail page. Inner
  // links (BerthLink / ClientLink / YachtLink) and the "View contract"
  // button keep their own behaviour because the click handler bails
  // when the target is inside an interactive element.
  const openTenancy = (id: string) => router.push(`/${portSlug}/tenancies/${id}` as never);

  return (
    <div className="rounded-md border">
      <Table>
        <TableHeader>
          <TableRow>
            {showBerth && <TableHead>Berth</TableHead>}
            <TableHead>Client</TableHead>
            <TableHead>Yacht</TableHead>
            <TableHead>Dates</TableHead>
            <TableHead>Tenure</TableHead>
            <TableHead>Status</TableHead>
            <TableHead>Contract</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {tenancies.map((r) => (
            <TableRow
              key={r.id}
              role="link"
              tabIndex={0}
              className="cursor-pointer hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
              onClick={(e) => {
                if ((e.target as HTMLElement).closest('a, button')) return;
                openTenancy(r.id);
              }}
              onKeyDown={(e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                  if ((e.target as HTMLElement).closest('a, button')) return;
                  e.preventDefault();
                  openTenancy(r.id);
                }
              }}
            >
              {showBerth && (
                <TableCell>
                  <BerthLink berthId={r.berthId} portSlug={portSlug} />
                </TableCell>
              )}
              <TableCell>
                <ClientLink clientId={r.clientId} portSlug={portSlug} />
              </TableCell>
              <TableCell>
                <YachtLink yachtId={r.yachtId} portSlug={portSlug} />
              </TableCell>
              <TableCell>{formatDateRange(r.startDate, r.endDate)}</TableCell>
              <TableCell>{prettyTenure(r.tenureType)}</TableCell>
              <TableCell>
                <StatusBadge status={r.status} />
              </TableCell>
              <TableCell>
                {r.contractFileId ? (
                  <button
                    type="button"
                    className="text-primary hover:underline"
                    onClick={async () => {
                      const res = await apiFetch<{ data: { url: string } }>(
                        `/api/v1/files/${r.contractFileId}/download`,
                      );
                      window.open(res.data.url, '_blank', 'noopener,noreferrer');
                    }}
                  >
                    View contract
                  </button>
                ) : (
                  '-'
                )}
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  );
}
