import type { ExperimentAnalyticsValueDto } from "@montelo/browser-client";
import { FC } from "react";
import { Cell, Pie, PieChart as RechartsPieChart } from "recharts";

const COLORS = ["#0088FE", "#00C49F", "#FFBB28", "#FF8042"];

export const PieChart: FC<{
  values: Array<ExperimentAnalyticsValueDto>;
}> = ({ values }) => {
  const RADIAN = Math.PI / 180;

  const renderCustomizedLabel = ({ cx, cy, midAngle, innerRadius, outerRadius, percent, name }: any) => {
    const radius = innerRadius + (outerRadius - innerRadius) * 0.5;
    const x = cx + radius * Math.cos(-midAngle * RADIAN);
    const y = cy + radius * Math.sin(-midAngle * RADIAN);

    return (
      <text x={x} y={y} fill="white" textAnchor={x > cx ? "start" : "end"} dominantBaseline="central">
        {`${name} ${(percent * 100).toFixed(0)}%`}
      </text>
    );
  };

  return (
    <RechartsPieChart width={470} height={320}>
      <Pie
        data={values}
        cx="50%"
        cy="50%"
        labelLine={false}
        outerRadius={100}
        fill="var(--background)"
        dataKey="value"
        label={renderCustomizedLabel}
        isAnimationActive={false}
      >
        {values.map((_entry, index) => (
          <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
        ))}
      </Pie>
    </RechartsPieChart>
  );
};
