'use client';

/**
 * Berth-demand widget - ranks berths by active interest count, with a
 * horizontal bar per row encoding magnitude relative to the leader.
 * Matches the standard CardHeader / CardContent layout of its dashboard
 * siblings; the bars (not chrome) do the visual work.
 */
import { useQuery } from '@tanstack/react-query';
import { ArrowRight, TrendingUp } from 'lucide-react';
import { useParams } from 'next/navigation';
import Link from 'next/link';

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

interface HeatRow {
  berthId: string;
  mooringNumber: string;
  area: string | null;
  status: string;
  activeInterestCount: number;
}

interface HeatResponse {
  data: { rows: HeatRow[] };
}

function formatStatus(s: string): string {
  return s.replace(/_/g, ' ');
}

const BAR_COLOR_BY_STATUS: Record<string, string> = {
  available: 'bg-success/70',
  under_offer: 'bg-warning/80',
  sold: 'bg-error/60',
};

export function BerthHeatWidget() {
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';
  const { data, isLoading } = useQuery<HeatResponse>({
    queryKey: ['dashboard', 'berth-heat'],
    queryFn: () => apiFetch<HeatResponse>('/api/v1/dashboard/berth-heat?limit=15'),
    staleTime: 60_000,
  });

  const ranked = (data?.data?.rows ?? []).filter((r) => r.activeInterestCount > 0);
  const visible = ranked.slice(0, 6);
  const max = visible[0]?.activeInterestCount ?? 1;
  const totalActive = ranked.reduce((sum, r) => sum + r.activeInterestCount, 0);

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-1.5 text-base">
          <TrendingUp className="size-4 text-brand-600" aria-hidden />
          Berth demand
        </CardTitle>
        <CardDescription>
          {ranked.length > 0
            ? `${totalActive} active interest${totalActive === 1 ? '' : 's'} across ${ranked.length} ${ranked.length === 1 ? 'berth' : 'berths'}.`
            : 'Berths ranked by active interest count.'}
        </CardDescription>
      </CardHeader>
      <CardContent>
        {isLoading ? (
          <div className="space-y-2">
            {Array.from({ length: 5 }).map((_, i) => (
              <Skeleton key={i} className="h-10 w-full" aria-hidden />
            ))}
          </div>
        ) : visible.length === 0 ? (
          <p className="py-4 text-center text-sm text-muted-foreground">
            No active demand yet. Berths will appear here as interests land.
          </p>
        ) : (
          <>
            <ul className="space-y-1">
              {visible.map((r) => {
                const widthPct = Math.max(6, Math.round((r.activeInterestCount / max) * 100));
                return (
                  <li key={r.berthId}>
                    <Link
                      // eslint-disable-next-line @typescript-eslint/no-explicit-any
                      href={`/${portSlug}/berths/${r.berthId}` as any}
                      className="-mx-2 grid grid-cols-[3.25rem_1fr_2rem] items-center gap-3 rounded-md px-2 py-2 hover:bg-accent/60"
                    >
                      <span className="truncate font-mono text-sm font-medium text-foreground">
                        {r.mooringNumber}
                      </span>
                      <div className="min-w-0">
                        <div className="flex h-1.5 w-full overflow-hidden rounded-full bg-muted">
                          <span
                            aria-hidden
                            className={cn(
                              'h-full rounded-full',
                              BAR_COLOR_BY_STATUS[r.status] ?? 'bg-brand-400',
                            )}
                            style={{ width: `${widthPct}%` }}
                          />
                        </div>
                        <p className="mt-1 truncate text-xs text-muted-foreground">
                          {r.area ?? 'Unassigned'} ·{' '}
                          <span className="capitalize">{formatStatus(r.status)}</span>
                        </p>
                      </div>
                      <span className="text-right text-sm font-semibold text-foreground tabular-nums">
                        {r.activeInterestCount}
                      </span>
                    </Link>
                  </li>
                );
              })}
            </ul>
            {ranked.length > visible.length ? (
              <div className="mt-3 border-t pt-2 text-right">
                <Link
                  // eslint-disable-next-line @typescript-eslint/no-explicit-any
                  href={`/${portSlug}/berths?sort=activeInterestCount&order=desc` as any}
                  className="inline-flex items-center gap-1 text-xs font-medium text-muted-foreground hover:text-foreground"
                >
                  View all by demand
                  <ArrowRight className="size-3" aria-hidden />
                </Link>
              </div>
            ) : null}
          </>
        )}
      </CardContent>
    </Card>
  );
}
