import { useForceLightTheme } from '@/lib/theme';
import { Head, router } from '@inertiajs/react';
import { Loader2 } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';

type Props = {
    subscription_id: string;
    key_id: string;
    plan: { key: string | null; name: string | null; period: string | null };
    prefill: { name: string; email: string; contact: string };
    success_url: string;
    cancel_url: string;
};

declare global {
    interface Window {
        Razorpay?: new (options: Record<string, unknown>) => {
            open: () => void;
            on: (event: string, handler: (...args: unknown[]) => void) => void;
        };
    }
}

const CHECKOUT_SCRIPT = 'https://checkout.razorpay.com/v1/checkout.js';

export default function RazorpayCheckout({
    subscription_id,
    key_id,
    plan,
    prefill,
    cancel_url,
}: Props) {
    useForceLightTheme();
    const [error, setError] = useState<string | null>(null);
    const opened = useRef(false);

    useEffect(() => {
        // Idempotent open — React StrictMode would otherwise pop the modal twice.
        if (opened.current) return;
        opened.current = true;

        const ensureScript = (): Promise<void> => {
            if (window.Razorpay) return Promise.resolve();
            const existing = document.querySelector<HTMLScriptElement>(
                `script[src="${CHECKOUT_SCRIPT}"]`,
            );
            if (existing) {
                return new Promise((resolve, reject) => {
                    existing.addEventListener('load', () => resolve(), { once: true });
                    existing.addEventListener('error', () => reject(new Error('checkout.js failed to load')), { once: true });
                });
            }
            return new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = CHECKOUT_SCRIPT;
                script.async = true;
                script.onload = () => resolve();
                script.onerror = () => reject(new Error('checkout.js failed to load'));
                document.body.appendChild(script);
            });
        };

        const csrf =
            document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')
                ?.content ?? '';

        const verify = async (response: {
            razorpay_payment_id: string;
            razorpay_subscription_id: string;
            razorpay_signature: string;
        }) => {
            try {
                const res = await fetch('/checkout/razorpay/verify', {
                    method: 'POST',
                    credentials: 'same-origin',
                    headers: {
                        Accept: 'application/json',
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': csrf,
                    },
                    body: JSON.stringify(response),
                });
                if (!res.ok) {
                    const body = await res.json().catch(() => null);
                    setError(
                        (body && typeof body.error === 'string' && body.error) ||
                            `Verification failed (${res.status}).`,
                    );
                    return;
                }
                const data = (await res.json()) as { redirect: string };
                window.location.href = data.redirect;
            } catch {
                setError('Network error verifying payment. Please contact support.');
            }
        };

        ensureScript()
            .then(() => {
                if (!window.Razorpay) {
                    setError('Razorpay checkout failed to load.');
                    return;
                }
                const rzp = new window.Razorpay({
                    key: key_id,
                    subscription_id,
                    name: 'AppShot AI',
                    description: `${plan.name ?? 'Plan'} · ${plan.period ?? ''}`,
                    prefill,
                    theme: { color: '#0052FF' },
                    handler: (response: unknown) => {
                        void verify(response as Parameters<typeof verify>[0]);
                    },
                    modal: {
                        ondismiss: () => {
                            window.location.href = cancel_url;
                        },
                    },
                });
                rzp.on('payment.failed', (...args: unknown[]) => {
                    const arg = args[0] as
                        | { error?: { description?: string } }
                        | undefined;
                    setError(
                        arg?.error?.description ?? 'Payment failed. Please try again.',
                    );
                });
                rzp.open();
            })
            .catch((e: Error) => setError(e.message));
    }, [
        cancel_url,
        key_id,
        plan.name,
        plan.period,
        prefill,
        subscription_id,
    ]);

    return (
        <>
            <Head title="Checkout" />
            <main className="flex min-h-screen items-center justify-center bg-background px-4">
                <div className="flex w-full max-w-sm flex-col items-center gap-4 rounded-xl border border-border bg-card p-8 text-center shadow-sm">
                    {error ? (
                        <>
                            <p className="text-sm font-medium text-destructive">
                                {error}
                            </p>
                            <button
                                type="button"
                                onClick={() => router.visit(cancel_url)}
                                className="text-[12px] text-muted-foreground underline underline-offset-2 hover:text-foreground"
                            >
                                Back to pricing
                            </button>
                        </>
                    ) : (
                        <>
                            <Loader2
                                className="h-6 w-6 animate-spin text-accent"
                                strokeWidth={2}
                            />
                            <p className="text-[13px] text-muted-foreground">
                                Opening Razorpay checkout…
                            </p>
                            <p className="text-[11px] text-muted-foreground/70">
                                If the popup doesn't appear, check your popup blocker
                                or refresh the page.
                            </p>
                        </>
                    )}
                </div>
            </main>
        </>
    );
}
