"use client";

import { useMemo, useState } from "react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { formatMoney } from "@/lib/utils";
import { ResponsiveContainer, AreaChart, Area, CartesianGrid, XAxis, YAxis, Tooltip, ReferenceLine } from "recharts";

export function ForecastChart({
  months,
  startBalance,
}: {
  months: { label: string; date: string; balance: number; deltaMonth: number }[];
  startBalance: number;
}) {
  const [extraIncome, setExtraIncome] = useState(0);
  const [extraSpend, setExtraSpend] = useState(0);

  const data = useMemo(() => {
    let bal = startBalance;
    const baseline: { month: string; Baseline: number; Adjusted: number }[] = [];
    let adj = startBalance;
    for (let i = 0; i < months.length; i++) {
      bal += months[i].deltaMonth;
      adj += months[i].deltaMonth + Math.round(extraIncome * 100) - Math.round(extraSpend * 100);
      baseline.push({
        month: months[i].label,
        Baseline: Math.round(bal / 100),
        Adjusted: Math.round(adj / 100),
      });
    }
    return baseline;
  }, [months, extraIncome, extraSpend, startBalance]);

  const finalBaseline = data.at(-1)?.Baseline ?? 0;
  const finalAdjusted = data.at(-1)?.Adjusted ?? 0;

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div className="space-y-1.5">
          <Label>+ Extra monthly income</Label>
          <Input type="number" step="50" value={extraIncome} onChange={(e) => setExtraIncome(Number(e.target.value))} />
        </div>
        <div className="space-y-1.5">
          <Label>− Extra monthly spend</Label>
          <Input type="number" step="50" value={extraSpend} onChange={(e) => setExtraSpend(Number(e.target.value))} />
        </div>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 text-sm">
        <div className="rounded-md border bg-card/40 p-3">
          <div className="text-xs text-muted-foreground">In 12 months (baseline)</div>
          <div className="font-mono tabular text-xl mt-1">{formatMoney(finalBaseline * 100)}</div>
        </div>
        <div className="rounded-md border bg-card/40 p-3">
          <div className="text-xs text-muted-foreground">In 12 months (adjusted)</div>
          <div className={`font-mono tabular text-xl mt-1 ${finalAdjusted >= finalBaseline ? "text-success" : "text-destructive"}`}>
            {formatMoney(finalAdjusted * 100)}
          </div>
        </div>
        <div className="rounded-md border bg-card/40 p-3">
          <div className="text-xs text-muted-foreground">Difference</div>
          <div className={`font-mono tabular text-xl mt-1 ${finalAdjusted - finalBaseline >= 0 ? "text-success" : "text-destructive"}`}>
            {formatMoney((finalAdjusted - finalBaseline) * 100)}
          </div>
        </div>
      </div>

      <div className="h-80">
        <ResponsiveContainer width="100%" height="100%">
          <AreaChart data={data} margin={{ top: 8, right: 12, bottom: 0, left: 0 }}>
            <defs>
              <linearGradient id="baseGrad" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="oklch(0.72 0.13 195)" stopOpacity={0.45} />
                <stop offset="100%" stopColor="oklch(0.72 0.13 195)" stopOpacity={0} />
              </linearGradient>
              <linearGradient id="adjGrad" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="oklch(0.72 0.17 150)" stopOpacity={0.35} />
                <stop offset="100%" stopColor="oklch(0.72 0.17 150)" stopOpacity={0} />
              </linearGradient>
            </defs>
            <CartesianGrid stroke="oklch(0.28 0.014 235 / 0.4)" strokeDasharray="3 3" />
            <XAxis dataKey="month" tickLine={false} axisLine={false} tick={{ fill: "oklch(0.7 0.018 220)", fontSize: 11 }} />
            <YAxis tickLine={false} axisLine={false} tick={{ fill: "oklch(0.7 0.018 220)", fontSize: 11 }} width={70} />
            <Tooltip
              contentStyle={{ background: "oklch(0.19 0.014 235)", border: "1px solid oklch(0.28 0.014 235)", borderRadius: 8, fontSize: 12 }}
              formatter={(v: number) => formatMoney(Math.round(v * 100))}
            />
            <ReferenceLine y={0} stroke="oklch(0.65 0.22 25 / 0.6)" strokeDasharray="2 2" />
            <Area type="monotone" dataKey="Baseline" stroke="oklch(0.72 0.13 195)" fill="url(#baseGrad)" strokeWidth={2} />
            <Area type="monotone" dataKey="Adjusted" stroke="oklch(0.72 0.17 150)" fill="url(#adjGrad)" strokeWidth={2} />
          </AreaChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}
