"use client";

import { useState, useMemo } from "react";
import { Plus, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { formatCents } from "@/lib/utils/format";

interface DebtEntry {
  id: string;
  name: string;
  balanceCents: number;
  annualRateBps: number;
  minPaymentCents: number;
}

interface PayoffResult {
  name: string;
  months: number;
  totalInterestCents: number;
  payoffOrder: number;
}

function simulatePayoff(
  debts: DebtEntry[],
  extraCents: number,
  strategy: "snowball" | "avalanche"
): { results: PayoffResult[]; totalMonths: number; totalInterest: number } {
  if (debts.length === 0) return { results: [], totalMonths: 0, totalInterest: 0 };

  type Working = {
    id: string;
    name: string;
    balance: number;
    rate: number;
    minPayment: number;
    paidOff: boolean;
    month: number;
    interest: number;
    order: number;
  };

  const working: Working[] = debts.map((d) => ({
    id: d.id,
    name: d.name,
    balance: d.balanceCents,
    rate: d.annualRateBps / 10000 / 12,
    minPayment: d.minPaymentCents,
    paidOff: false,
    month: 0,
    interest: 0,
    order: 0,
  }));

  let month = 0;
  let orderCounter = 1;
  const MAX_MONTHS = 600;

  while (working.some((d) => !d.paidOff) && month < MAX_MONTHS) {
    month++;

    // Apply interest
    for (const d of working) {
      if (!d.paidOff) {
        const interestThisMonth = Math.round(d.balance * d.rate);
        d.balance += interestThisMonth;
        d.interest += interestThisMonth;
      }
    }

    // Determine focus debt (snowball = lowest balance, avalanche = highest rate)
    const active = working.filter((d) => !d.paidOff);
    const sorted = [...active].sort((a, b) =>
      strategy === "snowball" ? a.balance - b.balance : b.rate - a.rate
    );
    const focusId = sorted[0]?.id;

    // Apply payments
    let extra = extraCents;
    for (const d of working) {
      if (d.paidOff) continue;

      let payment = d.minPayment;
      if (d.id === focusId) {
        payment += extra;
        extra = 0;
      }

      payment = Math.min(payment, d.balance);
      d.balance -= payment;

      if (d.balance <= 0) {
        d.balance = 0;
        d.paidOff = true;
        d.month = month;
        d.order = orderCounter++;
      }
    }

    // Freed min payments roll to next focus
    const justPaidOff = working.filter((d) => d.paidOff && d.month === month);
    extra += justPaidOff.reduce((s, d) => s + d.minPayment, 0);
  }

  const results: PayoffResult[] = working.map((d) => ({
    name: d.name,
    months: d.month || month,
    totalInterestCents: d.interest,
    payoffOrder: d.order,
  }));

  const totalInterest = working.reduce((s, d) => s + d.interest, 0);

  return { results, totalMonths: month, totalInterest };
}

function MonthsToYears(months: number): string {
  if (months <= 0) return "—";
  const y = Math.floor(months / 12);
  const m = months % 12;
  if (y === 0) return `${m}mo`;
  if (m === 0) return `${y}yr`;
  return `${y}yr ${m}mo`;
}

export default function DebtSimulatorPage() {
  const [debts, setDebts] = useState<DebtEntry[]>([]);
  const [extra, setExtra] = useState("");
  const [strategy, setStrategy] = useState<"snowball" | "avalanche">("avalanche");

  const addDebt = () => {
    setDebts((d) => [
      ...d,
      {
        id: Math.random().toString(36).slice(2),
        name: `Debt ${d.length + 1}`,
        balanceCents: 0,
        annualRateBps: 2400,
        minPaymentCents: 0,
      },
    ]);
  };

  const removeDebt = (id: string) => setDebts((d) => d.filter((x) => x.id !== id));

  const updateDebt = (id: string, field: keyof DebtEntry, raw: string) => {
    setDebts((d) =>
      d.map((x) => {
        if (x.id !== id) return x;
        if (field === "name") return { ...x, name: raw };
        const num = parseFloat(raw);
        if (isNaN(num)) return x;
        if (field === "balanceCents" || field === "minPaymentCents") {
          return { ...x, [field]: Math.round(num * 100) };
        }
        if (field === "annualRateBps") {
          return { ...x, annualRateBps: Math.round(num * 100) };
        }
        return x;
      })
    );
  };

  const extraCents = useMemo(() => {
    const n = parseFloat(extra);
    return isNaN(n) ? 0 : Math.round(n * 100);
  }, [extra]);

  const simulation = useMemo(
    () => simulatePayoff(debts.filter((d) => d.balanceCents > 0), extraCents, strategy),
    [debts, extraCents, strategy]
  );

  const snowball = useMemo(
    () => simulatePayoff(debts.filter((d) => d.balanceCents > 0), extraCents, "snowball"),
    [debts, extraCents]
  );

  const avalanche = useMemo(
    () => simulatePayoff(debts.filter((d) => d.balanceCents > 0), extraCents, "avalanche"),
    [debts, extraCents]
  );

  const interestSavings = snowball.totalInterest - avalanche.totalInterest;
  const monthsSavings = snowball.totalMonths - avalanche.totalMonths;

  return (
    <div className="space-y-6 max-w-4xl">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Debt Simulator</h1>
          <p className="text-slate-400 text-sm mt-1">
            Compare Snowball vs Avalanche payoff strategies
          </p>
        </div>
      </div>

      {/* Debts Input */}
      <Card className="bg-slate-800/50 border-slate-700/50">
        <CardHeader>
          <CardTitle className="text-white text-base">Your Debts</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {debts.length === 0 && (
            <p className="text-slate-500 text-sm text-center py-4">
              Add debts below to run the simulation
            </p>
          )}

          {debts.map((d) => (
            <div key={d.id} className="space-y-2 sm:space-y-0 sm:grid sm:grid-cols-[1fr_auto_auto_auto_auto] sm:gap-2 sm:items-end p-3 sm:p-0 rounded-lg sm:rounded-none bg-slate-900/40 sm:bg-transparent border border-slate-700/40 sm:border-0">
              <div className="space-y-1">
                <Label className="text-slate-400 text-xs">Name</Label>
                <Input
                  value={d.name}
                  onChange={(e) => updateDebt(d.id, "name", e.target.value)}
                  className="bg-slate-800 border-slate-600 text-white h-8 text-sm"
                />
              </div>
              <div className="grid grid-cols-3 gap-2 sm:contents">
              <div className="space-y-1 sm:w-28">
                <Label className="text-slate-400 text-xs">Balance ($)</Label>
                <Input
                  type="number"
                  step="0.01"
                  defaultValue={(d.balanceCents / 100).toFixed(2)}
                  onBlur={(e) => updateDebt(d.id, "balanceCents", e.target.value)}
                  className="bg-slate-800 border-slate-600 text-white h-8 text-sm"
                />
              </div>
              <div className="space-y-1 sm:w-24">
                <Label className="text-slate-400 text-xs">Rate (%)</Label>
                <Input
                  type="number"
                  step="0.01"
                  defaultValue={(d.annualRateBps / 100).toFixed(2)}
                  onBlur={(e) => updateDebt(d.id, "annualRateBps", e.target.value)}
                  className="bg-slate-800 border-slate-600 text-white h-8 text-sm"
                />
              </div>
              <div className="space-y-1 sm:w-28">
                <Label className="text-slate-400 text-xs">Min Pay ($)</Label>
                <Input
                  type="number"
                  step="0.01"
                  defaultValue={(d.minPaymentCents / 100).toFixed(2)}
                  onBlur={(e) => updateDebt(d.id, "minPaymentCents", e.target.value)}
                  className="bg-slate-800 border-slate-600 text-white h-8 text-sm"
                />
              </div>
              </div>{/* end grid cols wrapper */}
              <div className="flex justify-end sm:block">
              <button
                onClick={() => removeDebt(d.id)}
                className="text-slate-600 hover:text-red-400 transition-colors sm:mb-0.5"
              >
                <Trash2 className="h-4 w-4" />
              </button>
              </div>
            </div>
          ))}

          <div className="flex items-end gap-4 pt-2 border-t border-slate-700/50">
            <Button
              onClick={addDebt}
              variant="outline"
              className="border-slate-600 text-slate-300 hover:bg-slate-800"
            >
              <Plus className="h-4 w-4 mr-2" />
              Add Debt
            </Button>
            <div className="space-y-1 w-40">
              <Label className="text-slate-400 text-xs">Extra Monthly Payment ($)</Label>
              <Input
                type="number"
                step="0.01"
                value={extra}
                onChange={(e) => setExtra(e.target.value)}
                placeholder="0.00"
                className="bg-slate-800 border-slate-600 text-white h-8 text-sm"
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {debts.filter((d) => d.balanceCents > 0).length > 0 && (
        <>
          {/* Strategy comparison */}
          {snowball.totalMonths > 0 && (
            <div className="grid grid-cols-2 gap-4">
              <Card className={`border-2 ${strategy === "avalanche" ? "border-emerald-500 bg-emerald-500/5" : "border-slate-700/50 bg-slate-800/50"}`}>
                <CardContent className="p-4 text-center">
                  <div className="text-xs text-slate-400 mb-1">Avalanche (Highest Rate First)</div>
                  <div className="text-lg font-bold text-white">{MonthsToYears(avalanche.totalMonths)}</div>
                  <div className="text-sm text-red-400">{formatCents(avalanche.totalInterest)} interest</div>
                  {interestSavings > 0 && (
                    <div className="text-xs text-emerald-400 mt-1">
                      saves {formatCents(interestSavings)} vs Snowball
                    </div>
                  )}
                </CardContent>
              </Card>
              <Card className={`border-2 ${strategy === "snowball" ? "border-emerald-500 bg-emerald-500/5" : "border-slate-700/50 bg-slate-800/50"}`}>
                <CardContent className="p-4 text-center">
                  <div className="text-xs text-slate-400 mb-1">Snowball (Lowest Balance First)</div>
                  <div className="text-lg font-bold text-white">{MonthsToYears(snowball.totalMonths)}</div>
                  <div className="text-sm text-red-400">{formatCents(snowball.totalInterest)} interest</div>
                  {monthsSavings < 0 && (
                    <div className="text-xs text-emerald-400 mt-1">
                      {Math.abs(monthsSavings)} months faster
                    </div>
                  )}
                </CardContent>
              </Card>
            </div>
          )}

          {/* Detailed results */}
          <Card className="bg-slate-800/50 border-slate-700/50">
            <CardHeader className="pb-2">
              <div className="flex items-center justify-between">
                <CardTitle className="text-white text-base">Payoff Schedule</CardTitle>
                <Tabs value={strategy} onValueChange={(v) => setStrategy(v as "snowball" | "avalanche")}>
                  <TabsList className="bg-slate-700 border border-slate-600 h-7">
                    <TabsTrigger value="avalanche" className="text-xs h-6 data-[state=active]:bg-slate-600 data-[state=active]:text-white text-slate-400">
                      Avalanche
                    </TabsTrigger>
                    <TabsTrigger value="snowball" className="text-xs h-6 data-[state=active]:bg-slate-600 data-[state=active]:text-white text-slate-400">
                      Snowball
                    </TabsTrigger>
                  </TabsList>
                </Tabs>
              </div>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {[...simulation.results]
                  .sort((a, b) => a.payoffOrder - b.payoffOrder)
                  .map((r, i) => (
                    <div key={i} className="flex items-center gap-3">
                      <div className="w-5 h-5 rounded-full bg-emerald-500/20 text-emerald-400 text-xs flex items-center justify-center font-bold shrink-0">
                        {r.payoffOrder}
                      </div>
                      <div className="flex-1">
                        <div className="flex justify-between items-center">
                          <span className="text-sm text-white">{r.name}</span>
                          <span className="text-sm text-slate-400">{MonthsToYears(r.months)}</span>
                        </div>
                        <div className="flex justify-between items-center mt-0.5">
                          <span className="text-xs text-slate-500">
                            {formatCents(r.totalInterestCents)} total interest
                          </span>
                        </div>
                      </div>
                    </div>
                  ))}
              </div>

              <div className="mt-4 pt-4 border-t border-slate-700/50 flex justify-between text-sm">
                <span className="text-slate-400">Total payoff time</span>
                <span className="text-white font-semibold">{MonthsToYears(simulation.totalMonths)}</span>
              </div>
              <div className="flex justify-between text-sm mt-1">
                <span className="text-slate-400">Total interest paid</span>
                <span className="text-red-400 font-semibold">{formatCents(simulation.totalInterest)}</span>
              </div>
            </CardContent>
          </Card>
        </>
      )}
    </div>
  );
}
