import { createFileRoute, Link } from "@tanstack/react-router";
import { useServerFn } from "@tanstack/react-start";
import { useEffect, useState } from "react";
import { useCart } from "@/lib/cart";
import { confirmPayment } from "@/lib/orders.functions";
import { Button } from "@/components/ui/button";
import { RefreshCw } from "lucide-react";

export const Route = createFileRoute("/success")({
  validateSearch: (s: Record<string, unknown>) => ({
    session_id: typeof s['session_id'] === "string" ? s['session_id'] : undefined,
    bulk: s['bulk'] ? 1 : undefined,
  }),
  head: () => ({
    meta: [
      { title: "Order Confirmed — Right On Gloss" },
      { name: "description", content: "Thank you for your Right On Gloss order." },
      { property: "og:title", content: "Order Confirmed — Right On Gloss" },
      { property: "og:description", content: "Thank you for your order." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary" },
    ],
  }),
  component: Success,
});

function Success() {
  const { clear } = useCart();
  const { session_id, bulk } = Route.useSearch();
  const confirm = useServerFn(confirmPayment);
  const [result, setResult] = useState<{ ok: boolean; live: boolean } | null>(null);
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);
  async function verify() {
    if (!session_id) { setError("No payment reference was provided."); return; }
    setBusy(true); setError("");
    try {
      const next = await confirm({ data: { sessionId: session_id } });
      setResult(next);
      if (next.ok && !bulk) clear();
    } catch { setError("Unable to verify payment. Retry below or contact us with your payment reference."); }
    finally { setBusy(false); }
  }
  useEffect(() => {
    void verify();
    const timer = window.setInterval(() => { void verify(); }, 15000);
    return () => window.clearInterval(timer);
  }, [session_id]); // eslint-disable-line react-hooks/exhaustive-deps
  return (
    <div className="mx-auto max-w-xl px-5 py-24 text-center">
      <h1 className="text-4xl font-semibold">{result?.ok ? result.live ? "Payment verified" : "Test payment verified" : "Payment verification"}</h1>
      <p className="mt-4 text-lg text-muted-foreground">{error || (result?.ok ? result.live ? "Your payment has been received and your order recorded." : "No real money was collected. Test payments are excluded from sales." : result ? "Payment is not confirmed yet. Please retry shortly." : "Checking your payment with Stripe…")}</p>
      {session_id && !result?.ok && <Button className="mt-6" variant="outline" disabled={busy} onClick={() => void verify()}><RefreshCw className="size-4" />{busy ? "Checking payment…" : "Check payment again"}</Button>}
      {bulk ? <Link to="/distributor" className="btn-gloss mt-8">Back to bulk orders</Link> : <Link to="/shop" className="btn-gloss mt-8">Keep shopping</Link>}
    </div>
  );
}
