'use client';

import { BarChart, Bar, XAxis, YAxis, CartesianGrid, ResponsiveContainer, Tooltip, Cell } from 'recharts';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import type { OverviewChartItem } 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 OverviewSummaryChart({ data }: { data: OverviewChartItem[] }) {
  if (data.length === 0) return null;

  const chartData = data.map((d) => ({ name: d.name, 금액: d.금액, color: d.color }));

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-base font-semibold">주요 재무 지표</CardTitle>
      </CardHeader>
      <CardContent>
        <ResponsiveContainer width="100%" height={200}>
          <BarChart data={chartData} layout="vertical">
            <CartesianGrid strokeDasharray="3 3" horizontal={false} />
            <XAxis type="number" tick={{ fontSize: 11 }} tickFormatter={(v: number) => formatTooltipValue(v)} />
            <YAxis dataKey="name" type="category" tick={{ fontSize: 12 }} width={80} />
            <Tooltip
              formatter={(value) => formatTooltipValue(Number(value ?? 0))}
              contentStyle={{ fontSize: '12px', borderRadius: '8px' }}
            />
            <Bar dataKey="금액" radius={[0, 4, 4, 0]} maxBarSize={24}>
              {chartData.map((entry, index) => (
                <Cell key={`cell-${index}`} fill={entry.color} />
              ))}
            </Bar>
          </BarChart>
        </ResponsiveContainer>
      </CardContent>
    </Card>
  );
}
