"use client";

import React from "react";
import { TailwindSpinner } from "@/components/common/GlobalLoad";
import { useSearchParams } from "next/navigation";
import { createCheckoutSession, buyTokens } from "@/lib/stripe";

export default function PayRedirectPage() {
    const [status, setStatus] = React.useState<string>("Preparing checkout...");
    const [error, setError] = React.useState<string>("");
    const searchParams = useSearchParams();

    React.useEffect(() => {
        const type = (searchParams.get("type") || "").toLowerCase();
        if (!type) {
            setStatus("");
            setError("Missing payment type.");
            return;
        }

        const redirectTo = async () => {
            try {
                if (type === "token") {
                    const amountStr = searchParams.get("amount");
                    const pkg = searchParams.get("pkg") || "basic";
                    const amount = Number(amountStr);
                    if (!amount || amount <= 0) {
                        throw new Error("Invalid token amount");
                    }
                    setStatus("Creating token purchase session...");
                    const resp = await buyTokens({ token_amount: amount, package_type: pkg });
                    if (resp?.successful && resp?.data?.checkout_url) {
                        setStatus("Redirecting to Stripe Checkout...");
                        window.location.href = resp.data.checkout_url as string;
                        return;
                    }
                    throw new Error(resp?.message || "Failed to create token checkout session");
                }

                if (type === "subscription") {
                    const plan = searchParams.get("plan");
                    const billing = (searchParams.get("billing") || "month") as "month" | "year";
                    if (!plan) {
                        throw new Error("Missing plan name");
                    }
                    const currentUser = JSON.parse(localStorage.getItem("currentUser") || "{}");
                    if (!currentUser?.id) {
                        throw new Error("Not logged in. Please sign in and try again.");
                    }
                    setStatus("Creating subscription session...");
                    const result = await createCheckoutSession({
                        user_id: String(currentUser.id),
                        plan_name: plan,
                        billing_cycle: billing,
                    });
                    if (result?.successful && result?.data?.checkout_url) {
                        setStatus("Redirecting to Stripe Checkout...");
                        window.location.href = result.data.checkout_url as string;
                        return;
                    }
                    throw new Error(result?.message || "Failed to create subscription session");
                }

                throw new Error("Unsupported payment type");
            } catch (e: unknown) {
                setStatus("");
                setError(e instanceof Error ? e.message : "Failed to prepare checkout.");
            }
        };

        redirectTo();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [searchParams]);

    return (
        <div data-alt="pay-redirect-page" className="min-h-screen w-full flex items-center justify-center bg-black text-white">
            <div data-alt="pay-redirect-card" className="max-w-md w-full p-6 rounded-xl border border-white/10 bg-white/5 backdrop-blur">
                <h1 className="text-lg font-semibold mb-2">Preparing to redirect</h1>
                {status && <p className="text-sm text-white/80 mb-2">{status}</p>}
                {!error && (
                    <div data-alt="loading-indicator" className="flex items-center justify-center my-3">
                        <TailwindSpinner diameter={40} />
                    </div>
                )}
                {error && <p className="text-sm text-red-300">{error}</p>}
                {!error && (
                    <p className="text-xs text-white/60 mt-2">If it takes too long, please return to the previous page or check your network.</p>
                )}
            </div>
        </div>
    );
}


