'use client';

/**
 * PieChartWidget — Donut chart component with clean dark-theme styling.
 *
 * Features:
 * - Donut style by default (innerRadius 60) for modern look
 * - Vibrant color palette visible on dark backgrounds
 * - Custom themed tooltip with percentage display
 * - Legend with readable light text
 * - Smooth animation on initial render
 *
 * Requirements: 16.1, 16.2, 16.3, 16.4, 16.5
 */

import {
  PieChart,
  Pie,
  Cell,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts';
import CustomTooltip from './CustomTooltip';
import { chartColorArray } from '@/lib/constants/theme';
import { useChartTheme } from '@/lib/hooks/useChartTheme';

interface PieDataItem {
  name: string;
  value: number;
  color?: string;
}

interface PieChartWidgetProps {
  data: PieDataItem[];
  height?: number;
  innerRadius?: number;
  showLabels?: boolean;
}

export default function PieChartWidget({
  data,
  height = 300,
  innerRadius = 60,
  showLabels = false,
}: PieChartWidgetProps) {
  const total = data.reduce((sum, item) => sum + item.value, 0);
  const chartTheme = useChartTheme();

  return (
    <ResponsiveContainer width="100%" height={height}>
      <PieChart>
        <Pie
          data={data}
          cx="50%"
          cy="50%"
          innerRadius={innerRadius}
          outerRadius="75%"
          dataKey="value"
          nameKey="name"
          paddingAngle={2}
          cornerRadius={4}
          stroke="none"
          label={
            showLabels
              ? ({ name, percent }: { name?: string; percent?: number }) =>
                  `${name ?? ''} (${((percent ?? 0) * 100).toFixed(0)}%)`
              : false
          }
          labelLine={showLabels}
          animationDuration={800}
          animationEasing="ease-in-out"
        >
          {data.map((entry, index) => (
            <Cell
              key={`cell-${index}`}
              fill={entry.color ?? chartColorArray[index % chartColorArray.length]}
            />
          ))}
        </Pie>
        <Tooltip
          content={<CustomTooltip showPercentage total={total} />}
        />
        <Legend
          wrapperStyle={{ fontSize: 12 }}
          formatter={(value: string) => (
            <span style={{ color: chartTheme.legendColor }}>{value}</span>
          )}
        />
      </PieChart>
    </ResponsiveContainer>
  );
}
