'use client';

import { Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';

import { CardSkeleton } from '@/components/shared/loading-skeleton';
import { EmptyState } from '@/components/shared/empty-state';
import { useIsMobile } from '@/hooks/use-is-mobile';
import { STAGE_SHORT_LABELS, safeStage, stageLabel } from '@/lib/constants';
import { ChartCard } from './chart-card';
import { useFunnel } from './use-analytics';
import type { DateRange } from '@/lib/services/analytics.service';
import { rangeToSlug } from '@/lib/analytics/range';

interface Props {
  range: DateRange;
}

export function PipelineFunnelChart({ range }: Props) {
  const { data, isLoading } = useFunnel(range);
  const isMobile = useIsMobile();

  const stages = data?.stages ?? [];
  // Use short labels on mobile so the rotated axis isn't a wall of overlap.
  const chartData = stages.map((s) => ({
    stage: isMobile ? STAGE_SHORT_LABELS[safeStage(s.stage)] : stageLabel(s.stage),
    count: s.count,
    conversionPct: s.conversionPct,
  }));
  const allZero = stages.every((s) => s.count === 0);

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

  return (
    <ChartCard
      title="Pipeline Funnel"
      description="Interests by stage with conversion rate vs. open"
      exportFilename={`pipeline-funnel-${rangeToSlug(range)}`}
      toCsv={toCsv}
    >
      {isLoading ? (
        <CardSkeleton />
      ) : allZero ? (
        <EmptyState
          title="No interests in range"
          description="Conversion through Open → EOI → Deposit → Contract appears here. Try a longer date range, or add an interest to see it."
        />
      ) : (
        <ResponsiveContainer width="100%" height={260}>
          <BarChart data={chartData} margin={{ top: 4, right: 8, left: -16, bottom: 60 }}>
            <CartesianGrid strokeDasharray="3 3" className="stroke-border" />
            <XAxis
              dataKey="stage"
              tick={{ fontSize: 11, fill: 'hsl(var(--muted-foreground))' }}
              angle={-40}
              textAnchor="end"
              interval={0}
            />
            <YAxis
              tick={{ fontSize: 11, fill: 'hsl(var(--muted-foreground))' }}
              allowDecimals={false}
            />
            <Tooltip
              contentStyle={{
                background: 'hsl(var(--popover))',
                border: '1px solid hsl(var(--border))',
                borderRadius: '6px',
                fontSize: 12,
              }}
              formatter={(value, _name, item) => {
                const pct = (item?.payload as { conversionPct?: number } | undefined)
                  ?.conversionPct;
                return [`${value} (${pct ?? 0}%)`, 'Count'];
              }}
            />
            <Bar dataKey="count" fill="hsl(var(--chart-1))" radius={[4, 4, 0, 0]} />
          </BarChart>
        </ResponsiveContainer>
      )}
    </ChartCard>
  );
}
