'use client';

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

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
import { apiFetch } from '@/lib/api/client';

interface Renewal {
  tenancyId: string;
  berthId: string;
  mooringNumber: string;
  clientId: string;
  clientName: string;
  yachtName: string | null;
  endDate: string;
  daysUntilEnd: number;
  tenureType: string;
}

interface RenewalsResponse {
  data: Renewal[];
}

/**
 * Lists active tenancies expiring in the next 90 days with no successor
 * row in place. Surfaces the rep's renewal pipeline so a fixed-term
 * tenancy doesn't lapse silently. Mounted in the dashboard chart grid;
 * gated by the `tenancies_module` integration channel.
 */
export function TenancyRenewalsAtRiskWidget() {
  const routeParams = useParams<{ portSlug: string }>();
  const portSlug = routeParams?.portSlug ?? '';

  const { data, isLoading } = useQuery<RenewalsResponse>({
    queryKey: ['dashboard', 'tenancy_renewals'],
    queryFn: () => apiFetch<RenewalsResponse>('/api/v1/dashboard/tenancy-renewals?windowDays=90'),
    staleTime: 60_000,
  });

  const renewals = data?.data ?? [];

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-base">Renewals at risk</CardTitle>
        <CardDescription>
          {renewals.length === 0
            ? 'No fixed-term tenancies expiring in the next 90 days.'
            : `${renewals.length} tenanc${renewals.length === 1 ? 'y' : 'ies'} expiring without a successor.`}
        </CardDescription>
      </CardHeader>
      <CardContent>
        {isLoading ? (
          <Skeleton className="h-[200px] w-full" aria-hidden />
        ) : renewals.length === 0 ? (
          <p className="py-8 text-center text-sm text-muted-foreground">
            All active fixed-term tenancies have a successor or expire later.
          </p>
        ) : (
          <ul className="divide-y">
            {renewals.slice(0, 10).map((r) => (
              <li key={r.tenancyId} className="flex items-center justify-between py-2 text-sm">
                <div className="min-w-0 flex-1">
                  <Link
                    /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
                    href={`/${portSlug}/tenancies/${r.tenancyId}` as any}
                    className="font-medium text-primary hover:underline"
                  >
                    Berth {r.mooringNumber}
                  </Link>
                  <span className="ml-2 text-xs text-muted-foreground">
                    {r.clientName}
                    {r.yachtName ? ` · ${r.yachtName}` : ''}
                  </span>
                </div>
                <div className="ml-3 flex items-center gap-2 text-xs">
                  <Badge
                    variant={r.daysUntilEnd <= 30 ? 'destructive' : 'secondary'}
                    className="font-mono"
                  >
                    {r.daysUntilEnd}d
                  </Badge>
                  <span className="text-muted-foreground">
                    {new Date(r.endDate).toLocaleDateString()}
                  </span>
                </div>
              </li>
            ))}
          </ul>
        )}
      </CardContent>
    </Card>
  );
}
