'use client';

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

  const chartData = data.map((d) => ({ name: d.name, 매출액: d.매출액, 미수금: d.미수금 }));

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-base font-semibold">매출 vs 미수금 비교</CardTitle>
      </CardHeader>
      <CardContent>
        <ResponsiveContainer width="100%" height={200}>
          <BarChart data={chartData}>
            <CartesianGrid strokeDasharray="3 3" vertical={false} />
            <XAxis dataKey="name" tick={{ fontSize: 12 }} />
            <YAxis tick={{ fontSize: 11 }} tickFormatter={(v: number) => formatTooltipValue(v)} width={70} />
            <Tooltip
              formatter={(value) => formatTooltipValue(Number(value ?? 0))}
              contentStyle={{ fontSize: '12px', borderRadius: '8px' }}
            />
            <Legend wrapperStyle={{ fontSize: '12px' }} />
            <Bar dataKey="매출액" fill="#3b82f6" radius={[4, 4, 0, 0]} maxBarSize={30} />
            <Bar dataKey="미수금" fill="#f97316" radius={[4, 4, 0, 0]} maxBarSize={30} />
          </BarChart>
        </ResponsiveContainer>
      </CardContent>
    </Card>
  );
}
