import { createFileRoute } from "@tanstack/react-router";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useMemo, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { GlassCard } from "@/components/GlassCard";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet";
import { formatCurrency } from "@/lib/format";
import { observedMonthlySurplus, goalProbability, monthsToGoal } from "@/lib/finance";
import { toast } from "sonner";
import { Plus, Trash2, CalendarClock, Target } from "lucide-react";

export const Route = createFileRoute("/_authenticated/goals")({
  head: () => ({
    meta: [
      { title: "Goals — PRUDENTIA" },
      { name: "description", content: "Build wealth toward what matters." },
      { property: "og:title", content: "Goals — PRUDENTIA" },
      { property: "og:description", content: "PRUDENTIA financial goals." },
    ],
  }),
  component: GoalsPage,
});

function GoalsPage() {
  const { user } = Route.useRouteContext();
  const qc = useQueryClient();
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState({ name: "", target_amount: "", current_amount: "0", target_date: "", monthly_contribution: "" });

  const profileQ = useQuery({ queryKey: ["profile", user.id], queryFn: async () => (await supabase.from("profiles").select("currency").eq("id", user.id).single()).data });
  const currency = profileQ.data?.currency ?? "USD";
  const goalsQ = useQuery({ queryKey: ["goals", user.id], queryFn: async () => (await supabase.from("goals").select("*").eq("user_id", user.id).order("created_at", { ascending: false })).data ?? [] });
  const txQ = useQuery({ queryKey: ["tx", user.id], queryFn: async () => (await supabase.from("transactions").select("amount,type,occurred_at").eq("user_id", user.id)).data ?? [] });

  /** Observed monthly surplus over the last 90 days — powers ETA and probability. */
  const monthlySurplus = useMemo(
    () => observedMonthlySurplus((txQ.data ?? []) as any[]),
    [txQ.data],
  );

  const goals = (goalsQ.data ?? []) as any[];
  const totalCommitted = goals.reduce((s, g) => s + Number(g.monthly_contribution ?? 0), 0);

  async function save() {
    if (!form.name.trim() || !Number(form.target_amount)) return toast.error("Name and target required");
    const { error } = await supabase.from("goals").insert({
      user_id: user.id,
      name: form.name,
      target_amount: Number(form.target_amount),
      current_amount: Number(form.current_amount) || 0,
      target_date: form.target_date || null,
      monthly_contribution: Number(form.monthly_contribution) || 0,
    });
    if (error) return toast.error(error.message);
    toast.success("Goal created");
    setForm({ name: "", target_amount: "", current_amount: "0", target_date: "", monthly_contribution: "" });
    setOpen(false);
    qc.invalidateQueries({ queryKey: ["goals", user.id] });
  }

  async function addContribution(id: string, current: number, amount: number) {
    const { error } = await supabase.from("goals").update({ current_amount: current + amount }).eq("id", id);
    if (error) return toast.error(error.message);
    qc.invalidateQueries({ queryKey: ["goals", user.id] });
  }

  async function del(id: string) {
    await supabase.from("goals").delete().eq("id", id);
    qc.invalidateQueries({ queryKey: ["goals", user.id] });
  }

  return (
    <div className="px-4 pt-8 space-y-5">
      <header className="flex items-end justify-between px-1">
        <div>
          <p className="text-[11px] text-muted-foreground uppercase tracking-widest">Trajectory</p>
          <h1 className="text-2xl font-semibold">Goals</h1>
        </div>
        <Sheet open={open} onOpenChange={setOpen}>
          <SheetTrigger asChild>
            <Button size="sm" className="rounded-full bg-gradient-to-r from-electric to-purple text-primary-foreground"><Plus className="size-4 mr-1" /> New</Button>
          </SheetTrigger>
          <SheetContent side="bottom" className="rounded-t-3xl bg-background border-white/10 max-h-[92vh] overflow-y-auto">
            <SheetHeader><SheetTitle>New goal</SheetTitle></SheetHeader>
            <div className="space-y-3 mt-4">
              <div><Label>Name</Label><Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Emergency fund" className="mt-1" /></div>
              <div><Label>Target amount</Label><Input type="number" inputMode="decimal" value={form.target_amount} onChange={(e) => setForm({ ...form, target_amount: e.target.value })} className="mt-1" /></div>
              <div><Label>Saved so far</Label><Input type="number" inputMode="decimal" value={form.current_amount} onChange={(e) => setForm({ ...form, current_amount: e.target.value })} className="mt-1" /></div>
              <div><Label>Monthly contribution</Label><Input type="number" inputMode="decimal" value={form.monthly_contribution} onChange={(e) => setForm({ ...form, monthly_contribution: e.target.value })} placeholder="Optional" className="mt-1" /></div>
              <div><Label>Target date</Label><Input type="date" value={form.target_date} onChange={(e) => setForm({ ...form, target_date: e.target.value })} className="mt-1" /></div>
              <Button onClick={save} className="w-full h-11 rounded-full bg-gradient-to-r from-electric to-purple text-primary-foreground glow-electric">Save</Button>
            </div>
          </SheetContent>
        </Sheet>
      </header>

      {goals.length > 0 && (
        <GlassCard className="flex items-center justify-between py-4">
          <div>
            <p className="text-[10px] uppercase tracking-widest text-muted-foreground">Observed surplus</p>
            <p className="text-lg font-semibold tabular-nums mt-0.5">{formatCurrency(monthlySurplus, currency)}<span className="text-xs text-muted-foreground font-normal">/mo</span></p>
          </div>
          <div className="text-right">
            <p className="text-[10px] uppercase tracking-widest text-muted-foreground">Committed</p>
            <p className={`text-lg font-semibold tabular-nums mt-0.5 ${totalCommitted > monthlySurplus ? "text-warning" : "text-success"}`}>{formatCurrency(totalCommitted, currency)}<span className="text-xs text-muted-foreground font-normal">/mo</span></p>
          </div>
        </GlassCard>
      )}

      <div className="space-y-3">
        {goals.length === 0 && (
          <GlassCard className="text-center text-sm text-muted-foreground py-10">Every big number starts with a goal.</GlassCard>
        )}
        {goals.map((g: any) => {
          const cur = Number(g.current_amount);
          const tgt = Number(g.target_amount);
          const pct = Math.min(100, (cur / tgt) * 100);
          const remaining = Math.max(0, tgt - cur);
          const share = totalCommitted > 0 ? Number(g.monthly_contribution ?? 0) / totalCommitted : 1 / Math.max(1, goals.length);
          const perMonth = Number(g.monthly_contribution) > 0 ? Number(g.monthly_contribution) : monthlySurplus * share;
          const monthsNeeded = monthsToGoal(remaining, perMonth);
          const eta = Number.isFinite(monthsNeeded) ? new Date(Date.now() + monthsNeeded * 30.44 * 86_400_000) : null;
          const probability = goalProbability(remaining, perMonth, g.target_date);
          return (
            <GlassCard key={g.id} className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-base font-medium">{g.name}</p>
                  <p className="text-[11px] text-muted-foreground mt-0.5">{formatCurrency(cur, currency)} of {formatCurrency(tgt, currency)}{g.target_date ? ` · by ${new Date(g.target_date).toLocaleDateString()}` : ""}</p>
                </div>
                <button onClick={() => del(g.id)} className="text-muted-foreground hover:text-destructive" aria-label="Delete goal"><Trash2 className="size-4" /></button>
              </div>
              <div className="mt-3 h-2 rounded-full bg-white/10 overflow-hidden">
                <div className="h-full bg-gradient-to-r from-electric to-purple" style={{ width: `${pct}%` }} />
              </div>

              <div className="mt-3 grid grid-cols-2 gap-2">
                <div className="rounded-2xl bg-white/5 px-3 py-2">
                  <p className="text-[10px] uppercase tracking-widest text-muted-foreground flex items-center gap-1"><CalendarClock className="size-3" /> ETA</p>
                  <p className="text-sm font-medium mt-0.5">
                    {eta ? `${eta.toLocaleDateString(undefined, { month: "short", year: "numeric" })} · ${monthsNeeded} mo` : "Add a contribution"}
                  </p>
                </div>
                <div className="rounded-2xl bg-white/5 px-3 py-2">
                  <p className="text-[10px] uppercase tracking-widest text-muted-foreground flex items-center gap-1"><Target className="size-3" /> On-time odds</p>
                  <p className={`text-sm font-medium mt-0.5 ${probability === null ? "" : probability >= 70 ? "text-success" : probability >= 40 ? "text-warning" : "text-destructive"}`}>
                    {probability === null ? "No deadline" : `${probability}%`}
                  </p>
                </div>
              </div>

              <div className="flex gap-2 mt-3">
                {[50, 100, 500].map((amt) => (
                  <button key={amt} onClick={() => addContribution(g.id, cur, amt)} className="rounded-full text-xs px-3 py-1.5 bg-white/5 hover:bg-white/10">+{formatCurrency(amt, currency)}</button>
                ))}
              </div>
            </GlassCard>
          );
        })}
      </div>
    </div>
  );
}
