import { Head } from '@inertiajs/react';
import { useEffect, useRef } from 'react';

type Props = {
    checkout: {
        action: string;
        fields: Record<string, string>;
    };
};

export default function PayHereRedirect({ checkout }: Props) {
    const formRef = useRef<HTMLFormElement>(null);

    useEffect(() => {
        formRef.current?.submit();
    }, []);

    return (
        <>
            <Head title="Continue to secure payment" />
            <main className="grid min-h-screen place-items-center bg-slate-950 px-5 text-white">
                <section className="w-full max-w-md rounded-3xl border border-white/10 bg-white/[.06] p-8 text-center shadow-2xl">
                    <p className="text-xs font-bold tracking-[.2em] text-amber-300 uppercase">
                        Secure checkout
                    </p>
                    <h1 className="mt-3 text-2xl font-black">
                        Connecting to PayHere
                    </h1>
                    <p className="mt-3 text-sm leading-6 text-white/65">
                        Your ticket reservation is held for up to 12 hours while
                        you complete payment.
                    </p>
                    <form
                        ref={formRef}
                        method="post"
                        action={checkout.action}
                        className="mt-7"
                    >
                        {Object.entries(checkout.fields).map(
                            ([name, value]) => (
                                <input
                                    key={name}
                                    type="hidden"
                                    name={name}
                                    value={value}
                                />
                            ),
                        )}
                        <button
                            type="submit"
                            className="w-full rounded-full bg-red-600 px-5 py-3.5 text-sm font-bold text-white transition hover:bg-red-500"
                        >
                            Continue to PayHere
                        </button>
                    </form>
                    <p className="mt-4 text-xs text-white/45">
                        Payment confirmation will appear here after PayHere
                        sends its secure notification.
                    </p>
                </section>
            </main>
        </>
    );
}
