import { Path, Svg } from '@react-pdf/renderer';

import { SvgLabel } from '../svg-primitives';
import { PDF_TOKENS } from '../tokens';

export interface FunnelDatum {
  label: string;
  value: number;
  color?: string;
}

export interface FunnelChartProps {
  data: FunnelDatum[];
  width?: number;
  height?: number;
}

const FUNNEL_PALETTE = [
  '#1d4ed8',
  '#2563eb',
  '#3b82f6',
  '#60a5fa',
  '#93c5fd',
  '#bfdbfe',
  '#dbeafe',
];

export function FunnelChart({ data, width = 480, height = 240 }: FunnelChartProps) {
  if (data.length === 0) {
    return (
      <Svg width={width} height={height}>
        <SvgLabel
          x={width / 2}
          y={height / 2}
          textAnchor="middle"
          fontSize={9}
          fill={PDF_TOKENS.colors.textMuted}
        >
          No data
        </SvgLabel>
      </Svg>
    );
  }
  const max = Math.max(...data.map((d) => d.value), 1);
  const sliceH = (height - 16) / data.length;
  const centerX = width / 2;
  return (
    <Svg width={width} height={height}>
      {data.map((d, i) => {
        const topWidth = (data[i]!.value / max) * (width * 0.7);
        const next = data[i + 1];
        const bottomWidth = next ? (next.value / max) * (width * 0.7) : topWidth * 0.85;
        const y0 = 8 + i * sliceH;
        const y1 = y0 + sliceH;
        const x0Top = centerX - topWidth / 2;
        const x1Top = centerX + topWidth / 2;
        const x0Bot = centerX - bottomWidth / 2;
        const x1Bot = centerX + bottomWidth / 2;
        const color =
          d.color ?? FUNNEL_PALETTE[i % FUNNEL_PALETTE.length] ?? PDF_TOKENS.colors.accentBlue;
        return (
          <Svg key={i}>
            <Path
              d={`M ${x0Top} ${y0} L ${x1Top} ${y0} L ${x1Bot} ${y1} L ${x0Bot} ${y1} Z`}
              fill={color}
            />
            <SvgLabel
              x={centerX}
              y={y0 + sliceH / 2 + 2}
              textAnchor="middle"
              fontSize={8}
              fill="#ffffff"
              fontWeight="bold"
            >
              {d.label}
            </SvgLabel>
            <SvgLabel
              x={centerX}
              y={y0 + sliceH / 2 + 12}
              textAnchor="middle"
              fontSize={7}
              fill="#ffffff"
            >
              {d.value.toLocaleString()}
            </SvgLabel>
          </Svg>
        );
      })}
    </Svg>
  );
}
