'use client';

import { useQuery } from '@tanstack/react-query';
import { Cell, Legend, Pie, PieChart, ResponsiveContainer, Tooltip } from 'recharts';

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

interface BerthStatusResponse {
  data: {
    total: number;
    available: number;
    underOffer: number;
    sold: number;
  };
}

// Brand-aligned palette. Order matches the legend reading order
// (positive → in-progress → closed). Mirrors BERTH_STATUSES in
// src/lib/constants.ts (canonical 3-status enum).
const SEGMENTS = [
  { key: 'available', label: 'Available', color: 'hsl(213 55% 56%)' },
  { key: 'underOffer', label: 'Under offer', color: 'hsl(38 92% 50%)' },
  { key: 'sold', label: 'Sold', color: 'hsl(142 70% 40%)' },
] as const;

/**
 * Donut visualisation of the port's berth status mix. Sized to fit a
 * single chart column (~360px wide) with a generous legend; degrades
 * cleanly when a status has zero berths (segment is omitted, legend
 * still hints at its absence).
 */
export function BerthStatusChart() {
  const { data, isLoading } = useQuery<BerthStatusResponse>({
    queryKey: ['dashboard', 'berth_status'],
    queryFn: () => apiFetch<BerthStatusResponse>('/api/v1/dashboard/berth-status'),
    staleTime: 60_000,
  });

  const stats = data?.data;
  const chartData = stats
    ? SEGMENTS.map((s) => ({ ...s, value: stats[s.key] })).filter((s) => s.value > 0)
    : [];

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-base">Berth status</CardTitle>
        <CardDescription>
          {stats
            ? `${stats.sold} sold · ${stats.underOffer} under offer · ${stats.available} available`
            : 'Distribution across the port'}
        </CardDescription>
      </CardHeader>
      <CardContent>
        {isLoading ? (
          <Skeleton className="h-[240px] w-full" aria-hidden />
        ) : chartData.length === 0 ? (
          <p className="py-8 text-center text-sm text-muted-foreground">No berths yet.</p>
        ) : (
          <ResponsiveContainer width="100%" height={240}>
            <PieChart>
              <Pie
                data={chartData}
                dataKey="value"
                nameKey="label"
                cx="50%"
                cy="50%"
                innerRadius={50}
                outerRadius={85}
                paddingAngle={2}
              >
                {chartData.map((d) => (
                  <Cell key={d.key} fill={d.color} />
                ))}
              </Pie>
              <Tooltip
                formatter={(value, _name, payload) => {
                  const numeric = typeof value === 'number' ? value : Number(value ?? 0);
                  const total = stats?.total ?? 0;
                  const pct = total > 0 ? Math.round((numeric / total) * 100) : 0;
                  const label = (payload as { payload?: { label?: string } } | undefined)?.payload
                    ?.label;
                  return [`${numeric} (${pct}%)`, label ?? ''];
                }}
              />
              <Legend
                verticalAlign="bottom"
                height={36}
                iconType="circle"
                wrapperStyle={{ fontSize: 12 }}
              />
            </PieChart>
          </ResponsiveContainer>
        )}
      </CardContent>
    </Card>
  );
}
