import { useState } from "react";
import { useRouter } from "@tanstack/react-router";
import { useQueryClient } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { toast } from "sonner";
import { supabase } from "@/integrations/supabase/client";
import { deleteAccount } from "@/lib/account.functions";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { AlertTriangle } from "lucide-react";

const WILL_DELETE = [
  "Profile, income, savings and onboarding answers",
  "All transactions, budgets and goals",
  "All uploaded receipt images",
  "AI conversations, decisions, simulations and insights",
  "Your subscription record and plan status",
  "Your login itself — this cannot be undone",
];

export function DeleteAccountDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (v: boolean) => void }) {
  const [confirm, setConfirm] = useState("");
  const [busy, setBusy] = useState(false);
  const del = useServerFn(deleteAccount);
  const router = useRouter();
  const qc = useQueryClient();

  async function run() {
    setBusy(true);
    try {
      await del();
      await supabase.auth.signOut();
      qc.clear();
      toast.success("Your account and data have been deleted");
      router.navigate({ to: "/auth" });
    } catch (e: any) {
      toast.error(e?.message ?? "Could not delete the account");
    } finally {
      setBusy(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={(v) => { if (!busy) { setConfirm(""); onOpenChange(v); } }}>
      <DialogContent className="glass border-white/10 max-w-md">
        <DialogHeader>
          <div className="size-9 rounded-full bg-destructive/15 grid place-items-center mb-1">
            <AlertTriangle className="size-4 text-destructive" />
          </div>
          <DialogTitle>Delete your account</DialogTitle>
          <DialogDescription>This is permanent. Everything below is erased immediately and cannot be recovered.</DialogDescription>
        </DialogHeader>

        <ul className="space-y-1.5 text-[12px] text-muted-foreground">
          {WILL_DELETE.map((w) => (
            <li key={w} className="flex gap-2">
              <span className="text-destructive">·</span>
              {w}
            </li>
          ))}
        </ul>

        <p className="text-[11px] text-muted-foreground leading-relaxed">
          If you have an active paid plan, cancel it with your payment provider first so it does not renew. Deleting the account
          mid-period does not create a refund entitlement.
        </p>

        <div>
          <p className="text-[11px] text-muted-foreground mb-1.5">Type <span className="text-foreground font-medium">DELETE</span> to confirm</p>
          <Input value={confirm} onChange={(e) => setConfirm(e.target.value)} placeholder="DELETE" className="bg-white/5 border-white/10 rounded-2xl" />
        </div>

        <DialogFooter className="gap-2 sm:gap-2">
          <Button variant="outline" className="rounded-full bg-white/5 border-white/10" onClick={() => onOpenChange(false)} disabled={busy}>
            Keep my account
          </Button>
          <Button
            onClick={run}
            disabled={confirm.trim().toUpperCase() !== "DELETE" || busy}
            className="rounded-full bg-destructive text-destructive-foreground hover:bg-destructive/90"
          >
            {busy ? "Deleting…" : "Delete permanently"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
