import { createFileRoute, Link } from "@tanstack/react-router";
import { useServerFn } from "@tanstack/react-start";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { CreditCard, LockKeyhole, ArrowLeft } from "lucide-react";
import { useCart } from "@/lib/cart";
import { getProduct, formatPrice } from "@/lib/products";
import { createCheckout, getRetailPaymentOptions } from "@/lib/checkout.functions";
import { Button } from "@/components/ui/button";

export const Route = createFileRoute("/checkout")({
  head: () => ({ meta: [
    { title: "Shop Checkout — Right On Gloss" },
    { name: "description", content: "Review your individual gloss order and pay securely through Stripe in Nigerian Naira." },
    { property: "og:title", content: "Shop Checkout — Right On Gloss" },
    { property: "og:description", content: "Secure Stripe checkout for individual Right On Gloss purchases." },
    { property: "og:type", content: "website" },
    { name: "twitter:card", content: "summary" },
  ] }),
  component: Checkout,
});

function Checkout() {
  const { items } = useCart();
  const checkout = useServerFn(createCheckout);
  const optionsFn = useServerFn(getRetailPaymentOptions);
  const { data: options, isPending } = useQuery({ queryKey: ["retail-payment-options"], queryFn: () => optionsFn() });
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const lines = items.flatMap((item) => {
    const product = getProduct(item.slug);
    return product ? [{ ...item, product }] : [];
  });
  const total = lines.reduce((sum, line) => sum + line.product.price * line.qty, 0);
  async function pay(test: boolean) {
    setBusy(true); setError("");
    try {
      const result = await checkout({ data: { items: lines.map(({ slug, qty }) => ({ slug, qty })), test } });
      if ("url" in result && result.url) { window.location.assign(result.url); return; }
      setError(("error" in result && result.error) || "Unable to start checkout. Please try again.");
    } catch { setError("Unable to start checkout. Please try again."); }
    setBusy(false);
  }
  return <main className="mx-auto max-w-5xl px-5 py-12">
    <Link to="/cart" className="inline-flex items-center gap-2 text-sm text-primary"><ArrowLeft className="size-4" />Your bag</Link>
    <h1 className="mt-6 text-4xl font-semibold">Checkout</h1>
    {!lines.length ? <div className="mt-8"><p>Your bag is empty.</p><Button asChild className="mt-4"><Link to="/shop">Shop glosses</Link></Button></div> :
    <div className="mt-8 grid gap-10 md:grid-cols-[1.4fr_1fr]">
      <section><h2 className="text-xl font-semibold">Your order</h2>
        {lines.map(({ slug, qty, product }) => <div key={slug} className="flex items-center gap-4 border-b py-5">
          <img src={product.image} alt={product.name} loading="lazy" width={80} height={80} className="size-20 rounded-lg object-cover" />
          <div className="min-w-0 flex-1"><p className="font-medium">{product.name}</p><p className="mt-1 text-sm text-muted-foreground">{qty} × {formatPrice(product.price)}</p></div>
          <strong className="shrink-0">{formatPrice(product.price * qty)}</strong>
        </div>)}
      </section>
      <section className="border-t pt-5 md:border-t-0 md:border-l md:pl-8">
        <h2 className="text-xl font-semibold">Payment</h2>
        <div className="mt-5 flex justify-between text-lg"><span>Total</span><strong className="text-primary">{formatPrice(total)}</strong></div>
        <p className="mt-5 text-sm text-muted-foreground">Contact and delivery details are collected securely by Stripe.</p>
        {isPending ? <p className="mt-5 text-sm">Checking payment availability…</p> : options?.liveAvailable ?
          <Button className="mt-6 w-full" size="lg" disabled={busy} onClick={() => pay(false)}><CreditCard />{busy ? "Opening Stripe…" : `Pay ${formatPrice(total)}`}</Button> :
          <p role="status" className="mt-6 text-sm text-destructive">Real payments are not available yet. Please contact Right On Gloss to order.</p>}
        {!options?.liveAvailable && options?.testAvailable && <div className="mt-6 border-t pt-5">
          <p className="text-sm text-muted-foreground">Test checkout only — no real money is collected and this does not count as a sale.</p>
          <Button variant="outline" className="mt-3 w-full" disabled={busy} onClick={() => pay(true)}>{busy ? "Opening Stripe…" : "Test checkout"}</Button>
        </div>}
        {error && <p role="alert" className="mt-4 text-sm text-destructive">{error}</p>}
        <p className="mt-5 flex items-center gap-2 text-xs text-muted-foreground"><LockKeyhole className="size-4" />Secure payment by Stripe · NGN</p>
      </section>
    </div>}
  </main>;
}