'use client';

import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip, Legend } from 'recharts';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import type { ExpenseChartItem } from '../hooks/transformers';
import { formatNumber } from '@/lib/utils/amount';

function formatTooltipValue(value: number): string {
  if (value >= 100000000) return `${(value / 100000000).toFixed(1)}억원`;
  if (value >= 10000) return `${formatNumber(Math.round(value / 10000))}만원`;
  return `${formatNumber(value)}원`;
}

export function ExpenseDonutChart({ data }: { data: ExpenseChartItem[] }) {
  if (data.length === 0) return null;

  // recharts expects plain objects with index signature
  const chartData = data.map((d) => ({ name: d.name, value: d.value, color: d.color }));

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-base font-semibold">지출 항목별 비율</CardTitle>
      </CardHeader>
      <CardContent>
        <ResponsiveContainer width="100%" height={200}>
          <PieChart>
            <Pie
              data={chartData}
              cx="50%"
              cy="50%"
              innerRadius={50}
              outerRadius={80}
              paddingAngle={2}
              dataKey="value"
              nameKey="name"

            >
              {data.map((entry, index) => (
                <Cell key={`cell-${index}`} fill={entry.color} />
              ))}
            </Pie>
            <Tooltip
              formatter={(value) => formatTooltipValue(Number(value ?? 0))}
              contentStyle={{ fontSize: '12px', borderRadius: '8px' }}
            />
            <Legend
              wrapperStyle={{ fontSize: '12px' }}
            />
          </PieChart>
        </ResponsiveContainer>
      </CardContent>
    </Card>
  );
}
