"use client";

import { AreaChart, Area, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid, ReferenceLine } from "recharts";
import { formatVND, formatVNDCompact } from "@/lib/finance";

export interface ForecastPoint {
  date: string;
  balance: number;
}

/** Biểu đồ dự báo số dư theo ngày (60 ngày, kịch bản cơ sở) — dùng lại nguyên forecast.base đã
 * tính ở /api/dashboard (forecastCashFlow), không tính lại. shortfallDate (nếu có) đánh dấu ngày
 * đầu tiên số dư dự kiến xuống dưới ngưỡng an toàn — lấy từ firstShortfallDate, không suy đoán. */
export function ForecastLineChart({ points, shortfallDate }: { points: ForecastPoint[]; shortfallDate: string | null }) {
  if (!points.length) {
    return <div className="flex h-64 items-center justify-center text-sm text-slate-400">Chưa đủ dữ liệu để dự báo.</div>;
  }
  const everyNth = Math.max(1, Math.floor(points.length / 7));
  return (
    <ResponsiveContainer width="100%" height={260}>
      <AreaChart data={points} margin={{ top: 10, right: 10, left: -10, bottom: 0 }}>
        <defs>
          <linearGradient id="forecastFill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="5%" stopColor="#14b8a6" stopOpacity={0.25} />
            <stop offset="95%" stopColor="#14b8a6" stopOpacity={0} />
          </linearGradient>
        </defs>
        <CartesianGrid strokeDasharray="3 3" stroke="#eef2f6" />
        <XAxis dataKey="date" tick={{ fontSize: 11, fill: "#64748b" }} interval={everyNth} />
        <YAxis tick={{ fontSize: 12, fill: "#64748b" }} tickFormatter={(v) => formatVNDCompact(v)} />
        <Tooltip formatter={(v: number) => formatVND(v)} labelFormatter={(l) => `Ngày ${l}`} />
        <ReferenceLine y={0} stroke="#cbd5e1" strokeDasharray="3 3" />
        {shortfallDate && <ReferenceLine x={shortfallDate} stroke="#f43f5e" strokeDasharray="4 2" label={{ value: "Mốc nguy cơ âm", position: "top", fontSize: 10, fill: "#f43f5e" }} />}
        <Area type="monotone" dataKey="balance" name="Số dư dự kiến" stroke="#0d9488" strokeWidth={2} fill="url(#forecastFill)" dot={false} />
      </AreaChart>
    </ResponsiveContainer>
  );
}
