'use client';

import { Cell, Legend, Pie, PieChart, ResponsiveContainer, Tooltip } from 'recharts';

import { CardSkeleton } from '@/components/shared/loading-skeleton';
import { EmptyState } from '@/components/shared/empty-state';
import { ChartCard } from './chart-card';
import { useLeadSource } from './use-analytics';
import type { DateRange } from '@/lib/services/analytics.service';
import { rangeToSlug } from '@/lib/analytics/range';
import { SOURCE_LABELS as CANONICAL_SOURCE_LABELS } from '@/lib/constants';

interface Props {
  range: DateRange;
}

const COLORS = [
  'hsl(var(--chart-1))',
  'hsl(var(--chart-2))',
  'hsl(var(--chart-3))',
  'hsl(var(--chart-4))',
  'hsl(var(--chart-5))',
];

// Extend the canonical source labels with the analytics-specific buckets the
// API returns (`unspecified` for null sources, legacy `social`). Renames to the
// canonical set in /lib/constants stay in sync via the spread.
const SOURCE_LABELS: Record<string, string> = {
  ...CANONICAL_SOURCE_LABELS,
  social: 'Social',
  unspecified: 'Unspecified',
};

export function LeadSourceChart({ range }: Props) {
  const { data, isLoading } = useLeadSource(range);
  const slices = data?.slices ?? [];

  function toCsv(): string | null {
    if (!slices.length) return null;
    const header = 'source,count';
    const rows = slices.map((s) => `${s.source},${s.count}`);
    return [header, ...rows].join('\n');
  }

  const chartData = slices.map((s) => ({
    name: SOURCE_LABELS[s.source] ?? s.source,
    value: s.count,
  }));

  return (
    <ChartCard
      title="Lead Source Attribution"
      description="Where new interests came from"
      exportFilename={`lead-source-${rangeToSlug(range)}`}
      toCsv={toCsv}
    >
      {isLoading ? (
        <CardSkeleton />
      ) : !slices.length ? (
        <EmptyState
          title="No interests in range"
          description="Lights up once new interests are created - tracks where each came from (website, referral, broker)."
        />
      ) : (
        // Percentage radii + center-anchored chart so the pie scales with
        // the container instead of being clipped to a constant 90px ring at
        // narrow widths. Legend is reserved a fixed footer height.
        <ResponsiveContainer width="100%" height={280}>
          <PieChart>
            <Pie
              data={chartData}
              dataKey="value"
              nameKey="name"
              cx="50%"
              cy="45%"
              outerRadius="70%"
              innerRadius="40%"
              paddingAngle={2}
            >
              {chartData.map((_, i) => (
                <Cell key={i} fill={COLORS[i % COLORS.length]} />
              ))}
            </Pie>
            <Tooltip
              contentStyle={{
                background: 'hsl(var(--popover))',
                border: '1px solid hsl(var(--border))',
                borderRadius: '6px',
                fontSize: 12,
              }}
            />
            <Legend
              verticalAlign="bottom"
              height={40}
              wrapperStyle={{ fontSize: 12, paddingTop: 4 }}
            />
          </PieChart>
        </ResponsiveContainer>
      )}
    </ChartCard>
  );
}
