// src/BalanceChart.tsx
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { type BalancePoint } from '../api';

function formatAmount(n: number) {
  return new Intl.NumberFormat(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(n);
}

function formatDate(dateStr: string) {
  return new Date(dateStr).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}

export default function BalanceChart({ data }: { data: BalancePoint[] }) {
  if (data.length === 0) {
    return <div>No data to display</div>;
  }

  return (
    <ResponsiveContainer width="100%" height={300}>
      <LineChart
        data={data}
        // Increased 'left' margin to create more space for the Y-axis label and tick values
        margin={{ top: 5, right: 30, left: 50, bottom: 5 }} // <-- Change this line
      >
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis
          dataKey="date"
          tickFormatter={formatDate}
          label={{ value: 'Date', position: 'insideBottom', offset: -5 }}
        />
        <YAxis
          tickFormatter={(value) => formatAmount(value as number)}
          // Adjusted 'offset' for the Y-axis label.
          // A negative offset moves it further away from the axis.
          label={{ value: 'Balance', angle: -90, position: 'insideLeft', offset: -30 }} // <-- Change this line
        />
        <Tooltip
          labelFormatter={formatDate}
          formatter={(value) => [formatAmount(value as number), 'Balance']}
        />
        <Legend />
        <Line type="monotone" dataKey="balance" stroke="#3b82f6" strokeWidth={2} activeDot={{ r: 8 }} />
      </LineChart>
    </ResponsiveContainer>
  );
}