import { useEffect, useRef, useState } from "react";
import { CheckCircle2, Loader2, Lock } from "lucide-react";
import { toast } from "sonner";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { COMPANY } from "@/lib/company";
import { loadPayPalSdk } from "@/lib/paypal";
import { capturePaypalOrder, createPaypalOrder } from "@/lib/orders.functions";

export type CheckoutItem = {
  /** Server-trusted product ids; pricing is resolved on the server. */
  productIds: string[];
  name: string;
  description: string;
  /** Numeric amount in USD, display only. */
  amount: number;
};

type OrderState =
  | { status: "idle" }
  | { status: "processing" }
  | { status: "success"; orderId: string; payer: string };

const CURRENCY = "USD";

const money = (n: number) =>
  new Intl.NumberFormat("en-US", { style: "currency", currency: CURRENCY }).format(n);

export function CheckoutDialog({
  item,
  open,
  onOpenChange,
  onPaid,
}: {
  item: CheckoutItem | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onPaid?: () => void;
}) {
  const paypalRef = useRef<HTMLDivElement | null>(null);
  const cardRef = useRef<HTMLDivElement | null>(null);
  const [loading, setLoading] = useState(true);
  const [failed, setFailed] = useState(false);
  const [order, setOrder] = useState<OrderState>({ status: "idle" });
  const [reloadKey, setReloadKey] = useState(0);

  useEffect(() => {
    if (!open || !item) return;
    setOrder({ status: "idle" });
    setFailed(false);
    setLoading(true);

    let cancelled = false;
    const instances: any[] = [];

    loadPayPalSdk(CURRENCY)
      .then((paypal) => {
        if (cancelled || !paypal) return;

        const config = {
          // Order is created server-side so the amount can't be tampered with.
          createOrder: async () => {
            const res = await createPaypalOrder({ data: { productIds: item.productIds } });
            return res.id;
          },

          onApprove: async (data: any) => {
            setOrder({ status: "processing" });
            try {
              const res = await capturePaypalOrder({ data: { orderId: data.orderID } });
              setOrder({ status: "success", orderId: res.orderId, payer: res.payer });
              toast.success("Payment confirmed — your download link is on its way.");
              onPaid?.();
            } catch {
              setOrder({ status: "idle" });
              toast.error("We couldn't confirm your payment. Please contact support.");
            }
          },
          onCancel: () => {
            setOrder({ status: "idle" });
            toast("Checkout cancelled — nothing was charged.");
          },
          onError: () => {
            setOrder({ status: "idle" });
            toast.error("Payment error. Please try again or email " + COMPANY.email);
          },
        };

        const mount = (fundingSource: string, node: HTMLDivElement | null) => {
          if (!node) return;
          node.innerHTML = "";
          const buttons = paypal.Buttons({
            fundingSource,
            style: { layout: "vertical", shape: "rect", height: 46, label: "pay" },
            ...config,
          });
          if (!buttons.isEligible()) return;
          instances.push(buttons);
          buttons.render(node);
        };

        mount(paypal.FUNDING.PAYPAL, paypalRef.current);
        mount(paypal.FUNDING.CARD, cardRef.current);
        setLoading(false);
      })
      .catch(() => {
        if (cancelled) return;
        setFailed(true);
        setLoading(false);
        toast.error("PayPal is unavailable right now. Please try again shortly.");
      });

    return () => {
      cancelled = true;
      instances.forEach((b) => {
        try {
          b.close();
        } catch {
          /* noop */
        }
      });
    };
  }, [open, item, reloadKey]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-md">
        {order.status === "success" ? (
          <div className="space-y-5 py-2 text-center">
            <span className="mx-auto flex size-14 items-center justify-center rounded-full bg-secondary">
              <CheckCircle2 className="size-7 text-primary" />
            </span>
            <div className="space-y-2">
              <h2 className="text-xl font-semibold">Payment confirmed</h2>
              <p className="text-sm text-muted-foreground">
                Thank you, {order.payer}. Your secure download link is on its way to your PayPal
                email — it normally arrives in under 60 seconds.
              </p>
            </div>
            <div className="rounded-xl border border-border bg-background/60 p-4 text-left text-sm">
              <div className="flex justify-between gap-4">
                <span className="text-muted-foreground">Products</span>
                <span className="text-right font-medium">{item?.name}</span>
              </div>
              <div className="mt-2 flex justify-between gap-4">
                <span className="text-muted-foreground">Amount</span>
                <span className="font-medium">{item ? money(item.amount) : ""}</span>
              </div>
              <div className="mt-2 flex justify-between gap-4">
                <span className="text-muted-foreground">Order ID</span>
                <span className="font-mono text-xs">{order.orderId}</span>
              </div>
            </div>
            <Button variant="hero" className="w-full" onClick={() => onOpenChange(false)}>
              Done
            </Button>
          </div>
        ) : (
          <>
            <DialogHeader>
              <Badge variant="secondary" className="mb-1 w-fit">
                Secure checkout
              </Badge>
              <DialogTitle className="text-left leading-snug">{item?.name}</DialogTitle>
              <DialogDescription className="text-left">{item?.description}</DialogDescription>
            </DialogHeader>

            <div className="flex items-end justify-between border-y border-border/60 py-4">
              <span className="text-sm text-muted-foreground">Total due today</span>
              <span className="text-3xl font-bold tracking-tight">
                {item ? money(item.amount) : ""}
              </span>
            </div>

            {order.status === "processing" && (
              <div className="flex items-center gap-2 rounded-lg border border-border bg-background/60 p-3 text-sm text-muted-foreground">
                <Loader2 className="size-4 animate-spin text-primary" /> Capturing your payment…
              </div>
            )}

            {loading && (
              <div className="flex items-center gap-2 py-6 text-sm text-muted-foreground">
                <Loader2 className="size-4 animate-spin text-primary" /> Loading secure payment
                options…
              </div>
            )}

            {failed && (
              <div className="space-y-3 py-4">
                <p className="text-sm text-muted-foreground">
                  We couldn&apos;t load the PayPal checkout. This is almost always an ad blocker,
                  privacy extension, VPN or corporate network blocking{" "}
                  <span className="font-medium text-foreground">paypal.com</span>. Disable it for
                  this site (or try another browser) and retry.
                </p>
                <Button variant="hero" className="w-full" onClick={() => setReloadKey((k) => k + 1)}>
                  Retry secure checkout
                </Button>
                <p className="text-xs text-muted-foreground">
                  Still stuck? Email{" "}
                  <a href={`mailto:${COMPANY.email}`} className="text-primary hover:underline">
                    {COMPANY.email}
                  </a>{" "}
                  and we&apos;ll send you a direct payment link.
                </p>
              </div>
            )}


            <div className={order.status === "processing" ? "pointer-events-none opacity-50" : ""}>
              <div ref={paypalRef} className="min-h-0" />
              <div className="my-3 flex items-center gap-3 text-xs uppercase tracking-wide text-muted-foreground">
                <span className="h-px flex-1 bg-border" /> or pay by card{" "}
                <span className="h-px flex-1 bg-border" />
              </div>
              <div ref={cardRef} />
            </div>

            <p className="flex items-center justify-center gap-1.5 text-center text-xs text-muted-foreground">
              <Lock className="size-3.5" /> Encrypted checkout · Charges appear as{" "}
              {COMPANY.statementDescriptor}
            </p>
          </>
        )}
      </DialogContent>
    </Dialog>
  );
}
