"use client";

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

export function InterestCalculator() {
  const [principal, setPrincipal] = useState(1000);
  const [monthly, setMonthly] = useState(400);
  const [rate, setRate] = useState(4.5);
  const [years, setYears] = useState(5);

  const result = useMemo(
    () =>
      compoundInterest({
        principalMinor: Math.round(principal * 100),
        monthlyContributionMinor: Math.round(monthly * 100),
        annualRate: rate / 100,
        months: Math.round(years * 12),
      }),
    [principal, monthly, rate, years],
  );

  const months20k = useMemo(
    () =>
      monthsToReachGoal({
        principalMinor: Math.round(principal * 100),
        monthlyContributionMinor: Math.round(monthly * 100),
        annualRate: rate / 100,
        goalMinor: 20000_00,
      }),
    [principal, monthly, rate],
  );

  const data = result.series.map((s) => ({
    month: s.month,
    Balance: s.balanceMinor / 100,
    Contributed: s.contributedMinor / 100,
    Interest: s.interestMinor / 100,
  }));

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 gap-3">
        <div className="space-y-1.5">
          <Label>Starting balance</Label>
          <Input type="number" step="0.01" value={principal} onChange={(e) => setPrincipal(Number(e.target.value))} />
        </div>
        <div className="space-y-1.5">
          <Label>Monthly contribution</Label>
          <Input type="number" step="0.01" value={monthly} onChange={(e) => setMonthly(Number(e.target.value))} />
        </div>
        <div className="space-y-1.5">
          <Label>Annual rate (%)</Label>
          <Input type="number" step="0.01" value={rate} onChange={(e) => setRate(Number(e.target.value))} />
        </div>
        <div className="space-y-1.5">
          <Label>Years</Label>
          <Input type="number" step="0.5" value={years} onChange={(e) => setYears(Number(e.target.value))} />
        </div>
      </div>

      <div className="rounded-md border bg-card/40 p-3 text-sm space-y-1">
        <div className="flex justify-between">
          <span className="text-muted-foreground">Final balance</span>
          <span className="font-mono tabular text-lg font-semibold">{formatMoney(result.finalMinor)}</span>
        </div>
        <div className="flex justify-between">
          <span className="text-muted-foreground">Total contributed</span>
          <span className="font-mono tabular">{formatMoney(result.series.at(-1)?.contributedMinor ?? 0)}</span>
        </div>
        <div className="flex justify-between">
          <span className="text-muted-foreground">Interest earned</span>
          <span className="font-mono tabular text-success">{formatMoney(result.series.at(-1)?.interestMinor ?? 0)}</span>
        </div>
        {months20k && (
          <div className="flex justify-between">
            <span className="text-muted-foreground">Months to £20,000</span>
            <span className="font-mono tabular">{months20k}m</span>
          </div>
        )}
      </div>

      <div className="h-56">
        <ResponsiveContainer width="100%" height="100%">
          <AreaChart data={data} margin={{ top: 8, right: 12, bottom: 0, left: 0 }}>
            <defs>
              <linearGradient id="balGrad" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="oklch(0.72 0.13 195)" stopOpacity={0.5} />
                <stop offset="100%" stopColor="oklch(0.72 0.13 195)" 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={60} />
            <Tooltip
              contentStyle={{ background: "oklch(0.19 0.014 235)", border: "1px solid oklch(0.28 0.014 235)", borderRadius: 8, fontSize: 12 }}
              labelFormatter={(m) => `Month ${m}`}
              formatter={(v: number) => formatMoney(Math.round(v * 100))}
            />
            <Area type="monotone" dataKey="Balance" stroke="oklch(0.72 0.13 195)" fill="url(#balGrad)" strokeWidth={2} />
            <Line type="monotone" dataKey="Contributed" stroke="oklch(0.7 0.018 220)" strokeWidth={1.5} dot={false} />
          </AreaChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}
