"use client";

import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer, Legend } from "recharts";

import type { HeirShare } from "@/types/inheritance";
import { formatCurrency } from "@/utils/formatting";

const CHART_COLORS = [
  "#047857",
  "#0F766E",
  "#B45309",
  "#065F46",
  "#7C2D12",
  "#115E59",
  "#92400E",
  "#14532D",
];

interface ResultsPieChartProps {
  shares: HeirShare[];
  currency: string;
}

export function ResultsPieChart({ shares, currency }: ResultsPieChartProps) {
  const data = shares.map((share) => ({
    name: share.label,
    value: share.amount,
    fraction: share.fraction,
    percentage: share.percentage,
  }));

  return (
    <div className="h-[320px] w-full">
      <ResponsiveContainer width="100%" height="100%">
        <PieChart>
          <Pie
            data={data}
            dataKey="value"
            nameKey="name"
            cx="50%"
            cy="50%"
            outerRadius={104}
            innerRadius={52}
            label={({ name, percent }) =>
              `${name} ${((percent ?? 0) * 100).toFixed(1)}%`
            }
          >
            {data.map((entry, index) => (
              <Cell key={entry.name} fill={CHART_COLORS[index % CHART_COLORS.length]} />
            ))}
          </Pie>
          <Tooltip
            formatter={(value) => {
              const numericValue =
                typeof value === "number"
                  ? value
                  : typeof value === "string"
                    ? Number(value)
                    : 0;
              return formatCurrency(numericValue, currency);
            }}
            contentStyle={{
              borderRadius: "10px",
              border: "1px solid #d1d5db",
            }}
          />
          <Legend />
        </PieChart>
      </ResponsiveContainer>
    </div>
  );
}
