import { useMemo } from 'react';
import {
  Area,
  AreaChart,
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  Line,
  LineChart,
  Pie,
  PieChart,
  PolarAngleAxis,
  PolarGrid,
  Radar,
  RadarChart,
  RadialBar,
  RadialBarChart,
  XAxis,
} from 'recharts';
import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  type ChartConfig,
} from '@/components/ui/chart';
import type { ChartBlockData } from '../../../../../shared/api-types';

export function ChatChartBlock({ data: blockData }: { data: ChartBlockData }) {
  const { chartType, title, data } = blockData;
  // config is optional — the AI sometimes omits it and embeds color in data items instead
  const config = blockData.config ?? {};

  const chartConfig = useMemo(() => {
    const cfg: ChartConfig = {};
    const entries = Object.entries(config);
    for (let i = 0; i < entries.length; i++) {
      const [key, val] = entries[i];
      // Normalize: guard against missing colors and the legacy hsl(var(--chart-N)) pattern
      // (chart vars are oklch values, so the hsl wrapper produces invalid CSS → black fills).
      const raw = val.color ?? '';
      const color =
        raw && !/^hsl\(var\(/.test(raw) ? raw : `var(--chart-${(i % 5) + 1})`;
      cfg[key] = { label: val.label, color };
    }
    return cfg;
  }, [config]);

  const dataKeys = useMemo(() => {
    const keys = Object.keys(config);
    if (keys.length > 0) return keys;
    // Infer series keys from first data row when config is absent
    const first = data[0];
    if (!first) return ['value'];
    return Object.entries(first)
      .filter(([k, v]) => k !== 'name' && k !== 'color' && typeof v === 'number')
      .map(([k]) => k);
  }, [config, data]);

  return (
    <div className="rounded-lg border border-border bg-card p-4">
      {title && (
        <p className="mb-3 text-sm font-medium">{title}</p>
      )}
      <ChartContainer config={chartConfig} className="max-h-[240px] w-full">
        {renderChart(chartType, data, dataKeys)}
      </ChartContainer>
    </div>
  );
}

function renderChart(
  chartType: ChartBlockData['chartType'],
  data: Record<string, unknown>[],
  dataKeys: string[],
) {
  switch (chartType) {
    case 'area':
      return (
        <AreaChart accessibilityLayer data={data}>
          <CartesianGrid vertical={false} />
          <XAxis
            dataKey="name"
            tickLine={false}
            tickMargin={10}
            axisLine={false}
          />
          <ChartTooltip content={<ChartTooltipContent />} />
          {dataKeys.map((key) => (
            <Area
              key={key}
              type="monotone"
              dataKey={key}
              fill={`var(--color-${key})`}
              stroke={`var(--color-${key})`}
              fillOpacity={0.3}
            />
          ))}
        </AreaChart>
      );
    case 'bar':
      return (
        <BarChart accessibilityLayer data={data}>
          <CartesianGrid vertical={false} />
          <XAxis
            dataKey="name"
            tickLine={false}
            tickMargin={10}
            axisLine={false}
          />
          <ChartTooltip content={<ChartTooltipContent />} />
          {dataKeys.map((key) => (
            <Bar key={key} dataKey={key} fill={`var(--color-${key})`} radius={4} />
          ))}
        </BarChart>
      );
    case 'line':
      return (
        <LineChart accessibilityLayer data={data}>
          <CartesianGrid vertical={false} />
          <XAxis
            dataKey="name"
            tickLine={false}
            tickMargin={10}
            axisLine={false}
          />
          <ChartTooltip content={<ChartTooltipContent />} />
          {dataKeys.map((key) => (
            <Line
              key={key}
              type="monotone"
              dataKey={key}
              stroke={`var(--color-${key})`}
              strokeWidth={2}
              dot={false}
            />
          ))}
        </LineChart>
      );
    case 'pie':
      return (
        <PieChart>
          <ChartTooltip content={<ChartTooltipContent />} />
          <Pie
            data={data}
            dataKey={dataKeys[0] ?? 'value'}
            nameKey="name"
            innerRadius="40%"
            outerRadius="70%"
          >
            {data.map((_, i) => (
              <Cell key={i} fill={`var(--chart-${(i % 5) + 1})`} />
            ))}
          </Pie>
        </PieChart>
      );
    case 'radar':
      return (
        <RadarChart data={data}>
          <PolarGrid />
          <PolarAngleAxis dataKey="name" />
          <ChartTooltip content={<ChartTooltipContent />} />
          {dataKeys.map((key) => (
            <Radar
              key={key}
              dataKey={key}
              fill={`var(--color-${key})`}
              fillOpacity={0.3}
              stroke={`var(--color-${key})`}
            />
          ))}
        </RadarChart>
      );
    case 'radial':
      return (
        <RadialBarChart data={data} innerRadius="30%" outerRadius="90%">
          <ChartTooltip content={<ChartTooltipContent />} />
          {dataKeys.map((key) => (
            <RadialBar key={key} dataKey={key} fill={`var(--color-${key})`} />
          ))}
        </RadialBarChart>
      );
  }
}
