'use client';

import { useMemo } from 'react';
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 Cell {
  area: string;
  month: string;
  occupancyPct: number;
  berthCount: number;
  occupiedBerthMonths: number;
}

interface HeatmapResponse {
  data: Cell[];
}

function shade(pct: number): string {
  if (pct >= 90) return 'bg-emerald-700 text-white';
  if (pct >= 75) return 'bg-emerald-500 text-white';
  if (pct >= 50) return 'bg-emerald-300';
  if (pct >= 25) return 'bg-emerald-100';
  if (pct > 0) return 'bg-slate-100';
  return 'bg-slate-50 text-slate-400';
}

function formatMonth(iso: string): string {
  const [year, month] = iso.split('-');
  if (!year || !month) return iso;
  const d = new Date(Number(year), Number(month) - 1, 1);
  return d.toLocaleString(undefined, { month: 'short' });
}

/**
 * Per-(berth-area × month) occupancy heatmap. Cell shade encodes the
 * fraction of berths in that area covered by an active or ended tenancy
 * whose date range overlaps the month.
 */
export function TenancyOccupancyHeatmapWidget() {
  const { data, isLoading } = useQuery<HeatmapResponse>({
    queryKey: ['dashboard', 'tenancy_occupancy'],
    queryFn: () => apiFetch<HeatmapResponse>('/api/v1/dashboard/tenancy-occupancy'),
    staleTime: 60_000,
  });

  const { areas, months, byKey } = useMemo(() => {
    const cells = data?.data ?? [];
    const areaSet = new Set<string>();
    const monthSet = new Set<string>();
    const map = new Map<string, Cell>();
    for (const c of cells) {
      areaSet.add(c.area);
      monthSet.add(c.month);
      map.set(`${c.area}|${c.month}`, c);
    }
    return {
      areas: [...areaSet].sort(),
      months: [...monthSet].sort(),
      byKey: map,
    };
  }, [data]);

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-base">Occupancy heatmap</CardTitle>
        <CardDescription>
          {areas.length === 0
            ? 'No berths configured yet.'
            : 'Monthly occupancy across berth areas.'}
        </CardDescription>
      </CardHeader>
      <CardContent>
        {isLoading ? (
          <Skeleton className="h-[200px] w-full" aria-hidden />
        ) : areas.length === 0 ? (
          <p className="py-8 text-center text-sm text-muted-foreground">No data.</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full border-collapse text-xs">
              <thead>
                <tr>
                  <th className="px-2 py-1 text-left font-semibold text-muted-foreground">Area</th>
                  {months.map((m) => (
                    <th key={m} className="px-1 py-1 text-center font-normal text-muted-foreground">
                      {formatMonth(m)}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {areas.map((area) => (
                  <tr key={area}>
                    <td className="px-2 py-1 font-medium">{area}</td>
                    {months.map((m) => {
                      const cell = byKey.get(`${area}|${m}`);
                      const pct = cell?.occupancyPct ?? 0;
                      return (
                        <td
                          key={m}
                          className={`px-1 py-1 text-center ${shade(pct)}`}
                          title={`${area} · ${m}: ${pct}% (${cell?.occupiedBerthMonths ?? 0}/${cell?.berthCount ?? 0})`}
                        >
                          {pct}
                        </td>
                      );
                    })}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
