import { Head } from "@inertiajs/react";
import { useState } from "react";

import { useI18n } from "@/lib/i18n";
type Props = {
    payment: {
        reference: string;
        status: string;
        amount: number;
        currency: string;
        expires_at: string | null;
        plan: string | null;
    };
    statuses: string[];
};

function csrf(): string | undefined {
    return document.querySelector<HTMLMetaElement>("meta[name=csrf-token]")?.content;
}

export default function SandboxCheckout({ payment, statuses }: Props) {
    const { t } = useI18n();
    const [status, setStatus] = useState(payment.status);
    const [busy, setBusy] = useState(false);
    const [error, setError] = useState("");

    const simulate = async (nextStatus: string) => {
        setBusy(true);
        setError("");
        try {
            const response = await fetch(`/subscription/sandbox/${encodeURIComponent(payment.reference)}/simulate`, {
                method: "POST",
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json",
                    ...(csrf() ? { "X-CSRF-TOKEN": csrf() as string } : {}),
                },
                body: JSON.stringify({ status: nextStatus }),
            });
            const data = await response.json().catch(() => ({}));
            if (!response.ok) throw new Error(data.message ?? "Sandbox payment gagal diproses.");
            const resultingStatus = String(data.payment?.status ?? nextStatus);
            setStatus(resultingStatus);
            // Both provider states are normalized to `paid` by PaymentService.
            // Redirect based on the server result, not the selected simulator label.
            if (resultingStatus === "paid") {
                window.setTimeout(() => {
                    window.location.href = `/pricing?payment=success&reference=${encodeURIComponent(payment.reference)}`;
                }, 500);
            }
        } catch (e) {
            setError(e instanceof Error ? e.message : "Sandbox payment gagal diproses.");
        } finally {
            setBusy(false);
        }
    };

    return (
        <>
            <Head title={t("Payment Sandbox")} />
            <div className="min-h-screen bg-background px-6 py-12 text-foreground">
                <div className="mx-auto max-w-3xl rounded-2xl border bg-card p-6 shadow-sm">
                    <div className="mb-6 flex items-start justify-between gap-4">
                        <div>
                            <p className="text-xs font-bold uppercase tracking-[0.18em] text-warning-500">{t("Developer Sandbox")}</p>
                            <h1 className="mt-2 text-2xl font-bold">{t("Simulate NOWPayments lifecycle")}</h1>
                            <p className="mt-2 text-sm text-muted-foreground">
                                {t("Tidak ada cryptocurrency yang dikirim. Simulator ini melewati signature verification dan payment service yang sama dengan webhook.")}</p>
                        </div>
                        <span className="rounded-full border px-3 py-1 text-xs font-semibold">{status}</span>
                    </div>

                    <div className="grid gap-3 rounded-xl border bg-muted/20 p-4 text-sm sm:grid-cols-2">
                        <div><span className="text-muted-foreground">{t("Reference")}</span><div className="font-mono text-xs">{payment.reference}</div></div>
                        <div><span className="text-muted-foreground">{t("Plan")}</span><div className="font-semibold">{payment.plan ?? "Pro"}</div></div>
                        <div><span className="text-muted-foreground">{t("Amount")}</span><div className="font-semibold">{new Intl.NumberFormat("en-US", { style: "currency", currency: payment.currency }).format(payment.amount)}</div></div>
                        <div><span className="text-muted-foreground">{t("Expires")}</span><div>{payment.expires_at ?? "—"}</div></div>
                    </div>

                    {error && <div className="mt-4 rounded-xl border border-destructive-400/30 bg-destructive-400/5 p-3 text-sm text-destructive-500">{error}</div>}

                    <div className="mt-6">
                        <p className="mb-3 text-sm font-semibold">{t("Simulate provider status")}</p>
                        <div className="flex flex-wrap gap-2">
                            {statuses.map((value) => (
                                <button
                                    key={value}
                                    type="button"
                                    disabled={busy}
                                    onClick={() => simulate(value)}
                                    className="rounded-lg border px-3 py-2 text-xs font-semibold transition hover:bg-muted disabled:cursor-not-allowed disabled:opacity-50"
                                >
                                    {value}
                                </button>
                            ))}
                        </div>
                    </div>

                    <p className="mt-6 text-xs text-muted-foreground">
                        {t("Gunakan")}<strong>{t("confirmed")}</strong> {t("atau")}<strong>{t("finished")}</strong> {t("untuk mensimulasikan pembayaran selesai dan mengaktifkan Pro. Gunakan status lain untuk memeriksa pending/failure/expiry/refund handling.")}</p>
                </div>
            </div>
        </>
    );
}
