'use client';

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

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

interface SourceRow {
  source: string;
  total: number;
  won: number;
  lost: number;
  conversionRate: number;
}

interface SourceConversionResponse {
  data: SourceRow[];
}

/**
 * Horizontal bar list of lead-source conversion rates. Complements the
 * existing Lead Source Attribution donut: that one shows where leads
 * COME from, this shows which sources actually CONVERT. Lets marketing
 * spend follow the buyers, not the tire-kickers.
 *
 * Renders only sources with at least one lead; uses a compact bar-in-
 * row layout so 5-8 sources fit comfortably without scrolling.
 */
export function SourceConversionChart() {
  const { data, isLoading } = useQuery<SourceConversionResponse>({
    queryKey: ['dashboard', 'source_conversion'],
    queryFn: () => apiFetch<SourceConversionResponse>('/api/v1/dashboard/source-conversion'),
    staleTime: 60_000,
  });

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

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-base">Source conversion</CardTitle>
        <CardDescription>Won deals as a percentage of leads per source.</CardDescription>
      </CardHeader>
      <CardContent>
        {isLoading ? (
          <div className="space-y-3">
            <Skeleton className="h-8 w-full" aria-hidden />
            <Skeleton className="h-8 w-full" aria-hidden />
            <Skeleton className="h-8 w-full" aria-hidden />
          </div>
        ) : rows.length === 0 ? (
          <p className="py-4 text-center text-sm text-muted-foreground">
            Once interests have a source assigned, conversion rates will appear here.
          </p>
        ) : (
          <ul className="space-y-3">
            {rows.map((r) => {
              const pct = Math.round(r.conversionRate * 100);
              const label = formatEnum(r.source);
              return (
                <li key={r.source} className="space-y-1">
                  <div className="flex items-center justify-between text-xs">
                    <span className="font-medium text-foreground">{label}</span>
                    <span className="tabular-nums text-muted-foreground">
                      <span className="font-semibold text-foreground">{pct}%</span>
                      <span className="ml-1.5">
                        ({r.won} won · {r.total} total)
                      </span>
                    </span>
                  </div>
                  {/* Inline bar - keeps the widget compact and lets eight
                      rows share the same vertical space a Recharts plot
                      would use for two. */}
                  <div className="h-2 w-full overflow-hidden rounded-full bg-muted">
                    <div
                      className="h-full rounded-full bg-primary transition-all"
                      style={{ width: `${Math.max(pct, 2)}%` }}
                    />
                  </div>
                </li>
              );
            })}
          </ul>
        )}
      </CardContent>
    </Card>
  );
}
