import { useTranslation } from "react-i18next";
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip } from "recharts";
import type { CategoryZoomChild } from "../../shared/types";
import { ChartPatternDefs, getPatternFill } from "../../utils/chartPatterns";

export interface CategoryDonutChartProps {
  byChild: CategoryZoomChild[];
  centerLabel: string;
  centerValue: string;
}

export default function CategoryDonutChart({
  byChild,
  centerLabel,
  centerValue,
}: CategoryDonutChartProps) {
  const { t } = useTranslation();

  if (byChild.length === 0) {
    return (
      <div className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-6 text-center text-[var(--muted-foreground)] italic">
        {t("reports.empty.noData")}
      </div>
    );
  }

  return (
    <div className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-4 relative">
      <ResponsiveContainer width="100%" height={240}>
        <PieChart>
          <ChartPatternDefs
            prefix="cat-donut"
            categories={byChild.map((c, index) => ({ color: c.categoryColor, index }))}
          />
          <Pie
            data={byChild}
            dataKey="total"
            nameKey="categoryName"
            cx="50%"
            cy="50%"
            innerRadius={55}
            outerRadius={95}
            paddingAngle={2}
          >
            {byChild.map((entry, index) => (
              <Cell
                key={entry.categoryId}
                fill={getPatternFill("cat-donut", index, entry.categoryColor)}
              />
            ))}
          </Pie>
          <Tooltip
            formatter={(value) =>
              typeof value === "number"
                ? new Intl.NumberFormat("en-CA", { style: "currency", currency: "CAD" }).format(value)
                : String(value)
            }
            contentStyle={{
              backgroundColor: "var(--card)",
              border: "1px solid var(--border)",
              borderRadius: "0.5rem",
            }}
          />
        </PieChart>
      </ResponsiveContainer>
      <div className="absolute inset-0 flex flex-col items-center justify-center pointer-events-none">
        <span className="text-xs text-[var(--muted-foreground)]">{centerLabel}</span>
        <span className="text-lg font-bold">{centerValue}</span>
      </div>
    </div>
  );
}
