import { useEffect, useState } from "react";

export default function SumUpDemoPage() {
    const [checkoutId, setCheckoutId] = useState<string | null>(null);

    useEffect(() => {
        const localReservation = JSON.parse(localStorage.getItem("RESERVATION") || "{}");

        // Fetch checkout ID from the backend SumUp endpoint
        const csrfToken = document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.content ?? "";

        fetch("/sumup/pay", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                Accept: "application/json",
                "X-CSRF-TOKEN": csrfToken,
            },
            body: JSON.stringify(localReservation),
        })
            .then((res) => res.json())
            .then((data) => {
                if (data.checkout_id) setCheckoutId(data.checkout_id);
            });
    }, []);

    useEffect(() => {
        if (!checkoutId) return;

        // Load SumUp SDK script dynamically
        const script = document.createElement("script");
        script.src = "https://gateway.sumup.com/gateway/ecom/card/v2/sdk.js";
        script.async = true;
        script.onload = () => {
            // @ts-ignore
            window.SumUpCard.mount({
                id: "sumup-card",
                checkoutId: checkoutId,
                onResponse: (type: string, body: any) => {
                    console.log("Response type:", type);
                    console.log("Response body:", body);

                    if (type === "success") {
                        window.location.href = `/payment/verify?ref=${body?.checkout_reference ?? ""}`;
                    }
                },
            });
        };
        document.body.appendChild(script);

        return () => {
            document.body.removeChild(script);
        };
    }, [checkoutId]);

    return (
        <div className="min-h-screen bg-[#f3f4f8] text-[#1e2532] flex flex-col justify-between font-sans">
            {/* SumUp Branded Header */}
            <header className="bg-white border-b border-gray-200 py-4 px-6 shadow-sm">
                <div className="max-w-4xl mx-auto flex items-center justify-between">
                    <div className="flex items-center gap-3">
                        <div className="bg-[#0f1f3d] text-white font-black px-3 py-1 rounded text-lg tracking-tight">
                            sumup
                        </div>
                        <span className="text-xs text-gray-500 font-medium hidden sm:inline">
                            Portail de paiement sécurisé 256-bit SSL
                        </span>
                    </div>
                    <div className="flex items-center gap-2">
                        <span className="text-xs text-emerald-700 bg-emerald-50 px-2.5 py-1 rounded-full border border-emerald-200 font-semibold flex items-center gap-1.5">
                            <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span>
                            Mode Sandbox / Sécurisé
                        </span>
                    </div>
                </div>
            </header>

            {/* Main Checkout Container */}
            <main className="flex-1 flex items-center justify-center p-4 sm:p-6">
                <div id="sumup-card"></div>
            </main>

            {/* Footer */}
            <footer className="py-4 text-center text-xs text-gray-400 border-t border-gray-200">
                Paiement géré par SumUp Payments Ltd. & AEROCAB. Tous droits réservés.
            </footer>
        </div>
    );
}

