"use client";

import { LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid, Legend, ReferenceLine } from "recharts";
import { formatVND, formatVNDCompact, type ForecastPoint } from "@/lib/finance";

export function ForecastChart({
  forecast,
  safetyBalance,
}: {
  forecast: Record<"good" | "base" | "bad", ForecastPoint[]>;
  safetyBalance?: number;
}) {
  const merged = forecast.base.map((p, i) => ({
    date: p.date.slice(5),
    tot: forecast.good[i]?.balance,
    co_so: p.balance,
    xau: forecast.bad[i]?.balance,
  }));
  return (
    <ResponsiveContainer width="100%" height={280}>
      <LineChart data={merged} margin={{ top: 10, right: 10, left: -10, bottom: 0 }}>
        <CartesianGrid strokeDasharray="3 3" stroke="#eef2f6" />
        <XAxis dataKey="date" tick={{ fontSize: 11, fill: "#64748b" }} interval={4} />
        <YAxis tick={{ fontSize: 12, fill: "#64748b" }} tickFormatter={(v) => formatVNDCompact(v)} />
        <Tooltip formatter={(v: number) => formatVND(v)} />
        <Legend />
        {safetyBalance !== undefined && (
          <ReferenceLine y={safetyBalance} stroke="#ef4444" strokeDasharray="4 4" label={{ value: "Ngưỡng an toàn", position: "insideTopLeft", fontSize: 11, fill: "#ef4444" }} />
        )}
        <Line dataKey="tot" name="Kịch bản tốt" stroke="#16a34a" strokeWidth={1.5} dot={false} />
        <Line dataKey="co_so" name="Kịch bản cơ sở" stroke="#2563eb" strokeWidth={2} dot={false} />
        <Line dataKey="xau" name="Kịch bản xấu" stroke="#dc2626" strokeWidth={1.5} dot={false} />
      </LineChart>
    </ResponsiveContainer>
  );
}
