import { createFileRoute, Link, useRouter } from "@tanstack/react-router";
import { useEffect, useMemo, useState } from "react";
import { useServerFn } from "@tanstack/react-start";
import { supabase } from "@/integrations/supabase/client";
import { recordPlanIntent } from "@/lib/subscription.functions";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import { Check, Crown, Loader2, Sparkles, Zap } from "lucide-react";
import { PLANS, PLAN_BY_ID, PLAN_RANK, annualSavingPct, type BillingInterval, type PlanId } from "@/lib/plans";

export const Route = createFileRoute("/plans")({
  ssr: false,
  validateSearch: (s: Record<string, unknown>) => ({ from: typeof s.from === "string" ? s.from : undefined }),
  head: () => ({
    meta: [
      { title: "PRUDENTIA Premium — Plans" },
      { name: "description", content: "Compare PRUDENTIA Free, Pro and Elite: unlimited AI decisions, simulations, advanced analytics and forecasting." },
      { property: "og:title", content: "PRUDENTIA Premium — Plans" },
      { property: "og:description", content: "Unlimited AI decisions, simulations and advanced forecasting with PRUDENTIA Pro and Elite." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
  }),
  component: PlansPage,
});

function PlansPage() {
  const router = useRouter();
  const { from } = Route.useSearch();
  const [interval, setInterval] = useState<BillingInterval>("annual");
  const [selected, setSelected] = useState<PlanId>("pro");
  const [current, setCurrent] = useState<PlanId | null>(null);
  const [ready, setReady] = useState(false);
  const [next, setNext] = useState<"/home" | "/onboarding" | "/auth">("/auth");
  const [busy, setBusy] = useState(false);
  const saveIntent = useServerFn(recordPlanIntent);

  useEffect(() => {
    let mounted = true;
    (async () => {
      const { data } = await supabase.auth.getSession();
      const session = data.session;
      if (!session) {
        if (mounted) { setNext("/auth"); setReady(true); }
        return;
      }
      const [{ data: p }, { data: sub }] = await Promise.all([
        supabase.from("profiles").select("onboarding_completed").eq("id", session.user.id).maybeSingle(),
        supabase.from("subscriptions").select("plan,status,current_period_end").eq("user_id", session.user.id).maybeSingle(),
      ]);
      if (!mounted) return;
      const active = sub ? ["active", "trialing", "past_due"].includes(sub.status) : false;
      const notExpired = !sub?.current_period_end || new Date(sub.current_period_end).getTime() > Date.now();
      const plan = (active && notExpired ? (sub?.plan as PlanId) : "free") ?? "free";
      setCurrent(plan);
      setSelected(plan === "free" ? "pro" : plan);
      setNext(p?.onboarding_completed ? "/home" : "/onboarding");
      setReady(true);
    })();
    return () => { mounted = false; };
  }, []);

  const isPaid = current === "pro" || current === "elite";

  async function continueWith(plan: PlanId) {
    setBusy(true);
    try {
      const { data } = await supabase.auth.getUser();
      if (data.user) {
        try {
          await saveIntent({ data: { plan, interval } });
        } catch {
          /* choice recording is best-effort — never block the user */
        }
      }
      if (plan !== "free" && (current ?? "free") !== plan) {
        toast("Secure checkout is being wired up", {
          description: "Your interest in PRUDENTIA " + plan.toUpperCase() + " is saved — you'll be able to pay in-app shortly.",
        });
      }
      router.navigate({ to: next });
    } finally {
      setBusy(false);
    }
  }

  const cta = useMemo(() => {
    if (isPaid && selected === current) return "Continue";
    if (selected === "free") return "Continue with Free";
    return `Choose ${selected === "pro" ? "Pro" : "Elite"}`;
  }, [selected, current, isPaid]);

  if (!ready) {
    return (
      <div className="fixed inset-0 grid place-items-center bg-background">
        <Loader2 className="size-5 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background text-foreground relative overflow-x-hidden">
      <div className="absolute inset-0 pointer-events-none">
        <div className="absolute -top-24 left-1/2 -translate-x-1/2 size-[420px] rounded-full bg-electric/15 blur-[120px] animate-aura-pulse" />
        <div className="absolute top-1/2 -right-24 size-[320px] rounded-full bg-purple/15 blur-[110px] animate-aura-pulse" style={{ animationDelay: "1.4s" }} />
      </div>

      <div className="relative mx-auto max-w-md px-4 pt-12 pb-10">
        <header className="text-center animate-aura-fade">
          <div className="mx-auto size-14 rounded-2xl glass grid place-items-center glow-electric animate-aura-float">
            <Sparkles className="size-6 text-electric" />
          </div>
          <p className="mt-4 text-[11px] uppercase tracking-[0.3em] text-muted-foreground">PRUDENTIA Premium</p>
          <h1 className="mt-2 text-3xl font-semibold tracking-tight">
            {isPaid ? `You're on ${current?.toUpperCase()}` : from === "limit" ? "Go unlimited" : "Choose how you fly"}
          </h1>
          <p className="mt-2 text-[13px] text-muted-foreground leading-relaxed px-4">
            {isPaid
              ? "Everything is unlocked. Manage or change your plan any time from Profile."
              : "Every plan includes the full PRUDENTIA dashboard. Premium removes the limits on the AI."}
          </p>
        </header>

        {!isPaid && (
          <div className="mt-6 mx-auto w-fit rounded-full glass p-1 flex animate-aura-slide-up">
            {(["monthly", "annual"] as BillingInterval[]).map((i) => (
              <button
                key={i}
                onClick={() => setInterval(i)}
                aria-pressed={interval === i}
                className={`px-4 py-1.5 rounded-full text-xs font-medium transition-all ${
                  interval === i ? "bg-gradient-to-br from-electric to-purple text-primary-foreground" : "text-muted-foreground"
                }`}
              >
                {i === "monthly" ? "Monthly" : "Annual"}
                {i === "annual" && <span className="ml-1.5 opacity-80">−27%</span>}
              </button>
            ))}
          </div>
        )}

        <div className="mt-6 space-y-3">
          {PLANS.map((plan, idx) => {
            const active = selected === plan.id;
            const isCurrent = current === plan.id;
            const price = interval === "annual" ? plan.priceAnnual : plan.priceMonthly;
            const downgrade = current ? PLAN_RANK[plan.id] < PLAN_RANK[current] : false;
            return (
              <button
                key={plan.id}
                onClick={() => setSelected(plan.id)}
                aria-pressed={active}
                style={{ animationDelay: `${80 + idx * 90}ms` }}
                className={`w-full text-left rounded-3xl p-5 transition-all duration-300 animate-aura-slide-up ${
                  active
                    ? "glass border border-electric/40 glow-electric scale-[1.01]"
                    : "glass border border-white/5 opacity-80 hover:opacity-100"
                }`}
              >
                <div className="flex items-start justify-between gap-3">
                  <div className="min-w-0">
                    <div className="flex items-center gap-2">
                      <p className="text-lg font-semibold">{plan.name}</p>
                      {plan.highlight && !isCurrent && (
                        <span className="text-[9px] uppercase tracking-widest px-2 py-0.5 rounded-full bg-gradient-to-br from-electric to-purple text-primary-foreground">
                          Popular
                        </span>
                      )}
                      {isCurrent && (
                        <span className="text-[9px] uppercase tracking-widest px-2 py-0.5 rounded-full bg-white/10">Current</span>
                      )}
                      {plan.id === "elite" && <Crown className="size-3.5 text-warning" />}
                    </div>
                    <p className="text-[12px] text-muted-foreground mt-0.5">{plan.tagline}</p>
                  </div>
                  <div className="text-right shrink-0">
                    <p className="text-xl font-semibold tabular-nums">{price === 0 ? "Free" : `$${price}`}</p>
                    {price > 0 && (
                      <p className="text-[10px] text-muted-foreground">/{interval === "annual" ? "year" : "month"}</p>
                    )}
                    {price > 0 && interval === "annual" && (
                      <p className="text-[10px] text-electric">save {annualSavingPct(plan)}%</p>
                    )}
                  </div>
                </div>

                {plan.inherits && <p className="mt-3 text-[11px] text-muted-foreground">{plan.inherits}</p>}
                <ul className={`mt-2 grid gap-1.5 ${active ? "" : "max-h-[4.5rem] overflow-hidden"}`}>
                  {plan.features.map((f) => (
                    <li key={f} className="flex items-start gap-2 text-[12.5px]">
                      <Check className="size-3.5 mt-0.5 text-electric shrink-0" />
                      <span>{f}</span>
                    </li>
                  ))}
                </ul>
                {!active && <p className="mt-2 text-[11px] text-muted-foreground">Tap to see everything included</p>}
                {downgrade && active && (
                  <p className="mt-3 text-[11px] text-warning">Selecting this downgrades your plan at the end of the current period.</p>
                )}
              </button>
            );
          })}
        </div>

        <div className="mt-6 space-y-2 animate-aura-slide-up" style={{ animationDelay: "400ms" }}>
          <Button
            disabled={busy}
            onClick={() => continueWith(selected)}
            className="w-full h-12 rounded-full bg-gradient-to-br from-electric to-purple text-primary-foreground text-[15px] font-medium glow-electric"
          >
            {busy ? <Loader2 className="size-4 animate-spin" /> : <><Zap className="size-4 mr-2" />{cta}</>}
          </Button>
          {!isPaid && selected !== "free" && (
            <Button onClick={() => continueWith("free")} variant="ghost" disabled={busy} className="w-full rounded-full text-muted-foreground text-[13px]">
              Continue with Free
            </Button>
          )}
          <div className="glass rounded-3xl p-4 mt-3 space-y-1.5 text-[11px] text-muted-foreground leading-relaxed">
            <p className="text-foreground text-[11.5px] font-medium">Before you choose</p>
            <p>
              {selected === "free"
                ? "Free is $0 forever — no card, no trial that converts. It includes 5 AI decisions and 5 AI simulations per calendar month; the allowance resets on the 1st."
                : `${PLAN_BY_ID[selected].name} is billed $${interval === "annual" ? PLAN_BY_ID[selected].priceAnnual : PLAN_BY_ID[selected].priceMonthly} per ${interval === "annual" ? "year" : "month"}, in advance.`}
            </p>
            {selected !== "free" && (
              <>
                <p>Renews automatically each {interval === "annual" ? "year" : "month"} at the same price until you cancel. Prices are in USD; taxes may be added where required.</p>
                <p>Cancel any time from Profile → Subscription. Cancelling stops the next renewal and you keep paid features until the end of the period you already paid for.</p>
                <p>When a subscription ends, nothing is deleted — your account simply returns to Free and the monthly AI limits apply again.</p>
              </>
            )}
            <p>
              No hidden charges and no guaranteed financial outcomes.{" "}
              <Link to="/legal/terms" className="underline underline-offset-2">Terms</Link>
              {" · "}
              <Link to="/legal/privacy" className="underline underline-offset-2">Privacy</Link>
              {" · "}
              <Link to="/legal/disclaimer" className="underline underline-offset-2">Disclaimer</Link>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
