"use client";

import {
  PieChart,
  Pie,
  Cell,
  Tooltip,
  ResponsiveContainer,
} from "recharts";
import { CHART_COLORS, chartTheme } from "@/config/chart-theme";
import type { TrafficSourcePoint } from "@/types/analytics";

interface TrafficSourceChartProps {
  data: TrafficSourcePoint[];
  emptyLabel?: string;
  colors?: string[];
}

export function TrafficSourceChart({
  data,
  emptyLabel = "No traffic data yet.",
  colors,
}: TrafficSourceChartProps) {
  if (data.length === 0) {
    return (
      <p className="py-12 text-center text-sm text-muted">{emptyLabel}</p>
    );
  }

  const total = data.reduce((s, d) => s + d.value, 0) || 1;
  const palette = colors ?? CHART_COLORS.pie;

  return (
    <div className="flex flex-col sm:flex-row sm:items-center">
      <div className="h-[200px] w-full sm:h-[230px] sm:w-[55%]">
        <ResponsiveContainer width="100%" height="100%" debounce={50} minWidth={0}>
          <PieChart>
            <Pie
              data={data}
              dataKey="value"
              nameKey="name"
              cx="50%"
              cy="50%"
              innerRadius={52}
              outerRadius={80}
              paddingAngle={3}
            >
              {data.map((entry, i) => (
                <Cell
                  key={entry.name}
                  fill={palette[i % palette.length]}
                />
              ))}
            </Pie>
            <Tooltip
              {...chartTheme.tooltip}
              formatter={(value, name) => [
                `${value} (${Math.round((Number(value) / total) * 100)}%)`,
                String(name),
              ]}
            />
          </PieChart>
        </ResponsiveContainer>
      </div>
      <ul className="space-y-2 px-2 pb-2 sm:w-[45%]">
        {data.map((d, i) => (
          <li key={d.name} className="flex items-center gap-2 text-[13px]">
            <span
              className="h-2.5 w-2.5 shrink-0 rounded-full"
              style={{
                backgroundColor: palette[i % palette.length],
              }}
            />
            <span className="min-w-0 flex-1 truncate font-medium text-navy">
              {d.name}
            </span>
            <span className="shrink-0 font-mono text-xs font-bold text-muted">
              {Math.round((d.value / total) * 100)}%
            </span>
          </li>
        ))}
      </ul>
    </div>
  );
}
