'use client';

import { useQuery } from '@tanstack/react-query';

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

interface TenureRow {
  tenureType: string;
  activeCount: number;
}

interface TenureResponse {
  data: TenureRow[];
}

const TENURE_LABELS: Record<string, string> = {
  permanent: 'Permanent',
  fee_simple: 'Fee simple',
  strata_lot: 'Strata lot',
  fixed_term: 'Fixed term',
  seasonal: 'Seasonal',
};

const TENURE_COLORS: Record<string, string> = {
  permanent: 'bg-emerald-500',
  fee_simple: 'bg-blue-500',
  strata_lot: 'bg-indigo-500',
  fixed_term: 'bg-amber-500',
  seasonal: 'bg-sky-500',
};

/**
 * Distribution of active tenancies by tenure type. Lightweight bar
 * variant of the design's donut spec; ECharts donut lands alongside the
 * recharts→ECharts pass.
 */
export function TenancyByTenureTypeWidget() {
  const { data, isLoading } = useQuery<TenureResponse>({
    queryKey: ['dashboard', 'tenancy_tenure'],
    queryFn: () => apiFetch<TenureResponse>('/api/v1/dashboard/tenancy-tenure'),
    staleTime: 60_000,
  });

  const rows = data?.data ?? [];
  const total = rows.reduce((acc, r) => acc + r.activeCount, 0);

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-base">Tenancies by tenure type</CardTitle>
        <CardDescription>
          {total === 0
            ? 'No active tenancies yet.'
            : `${total} active tenanc${total === 1 ? 'y' : 'ies'} across the port.`}
        </CardDescription>
      </CardHeader>
      <CardContent>
        {isLoading ? (
          <Skeleton className="h-[180px] w-full" aria-hidden />
        ) : rows.length === 0 ? (
          <p className="py-8 text-center text-sm text-muted-foreground">
            Tenancy data appears here once active rows exist.
          </p>
        ) : (
          <ul className="space-y-2">
            {rows
              .slice()
              .sort((a, b) => b.activeCount - a.activeCount)
              .map((r) => {
                const pct = total > 0 ? Math.round((r.activeCount / total) * 100) : 0;
                return (
                  <li key={r.tenureType} className="space-y-1">
                    <div className="flex items-center justify-between text-xs">
                      <span className="font-medium">
                        {TENURE_LABELS[r.tenureType] ?? r.tenureType}
                      </span>
                      <span className="text-muted-foreground">
                        {r.activeCount} · {pct}%
                      </span>
                    </div>
                    <div className="h-2 overflow-hidden rounded-full bg-muted">
                      <div
                        className={`h-full ${TENURE_COLORS[r.tenureType] ?? 'bg-slate-400'}`}
                        style={{ width: `${pct}%` }}
                        aria-hidden
                      />
                    </div>
                  </li>
                );
              })}
          </ul>
        )}
      </CardContent>
    </Card>
  );
}
