import { Head, Link, router, usePage } from "@inertiajs/react";
import { useEffect, useState } from "react";
import { useI18n } from "@/lib/i18n";
import { login, register } from "@/routes";
import { Button } from "@/components/ui/button";
import {
    Card,
    CardContent,
    CardFooter,
    CardHeader,
    CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import {
    Check,
    Sparkles,
    AlertCircle,
    CheckCircle2,
    XCircle,
} from "lucide-react";

interface ReferralData {
    credit_balance: number;
    referrals: number;
    max_referrals: number;
}

interface Plan {
    slug: string;
    name: string;
    price_monthly: number;
    duration_days: number;
    billing_interval: string;
    currency: string;
    features: string[];
    limits: Record<string, number> | null;
}

interface AvailableGateway {
    slug: string;
    name: string;
    driver: string;
    checkout_mode: string;
}

type PaymentState =
    | "checking"
    | "pending"
    | "paid"
    | "failed"
    | "expired"
    | "refunded"
    | "cancelled";

const featureLabelKeys: Record<string, string> = {
    chart: "subscription.feature_chart",
    basic_indicators: "subscription.feature_basic_indicators",
    watchlist: "subscription.feature_watchlist",
    price_alerts: "subscription.feature_price_alerts",
    smc: "subscription.feature_smc",
    macro_insight: "subscription.feature_macro",
    signals: "subscription.feature_signals",
    cross_market: "subscription.feature_cross_market",
    advanced_alerts: "subscription.feature_advanced_alerts",
    backtest: "subscription.feature_backtest",
    advanced_insight: "subscription.feature_advanced_insight",
};

function formatPrice(
    plan: Plan,
    t: (
        key: string,
        fallback?: string,
        replacements?: Record<string, string | number>,
    ) => string,
) {
    const price = new Intl.NumberFormat("en-US", {
        style: "currency",
        currency: plan.currency,
        maximumFractionDigits: 0,
    }).format(Number(plan.price_monthly));

    if (Number(plan.price_monthly) === 0) {
        return price;
    }

    const duration = Number(plan.duration_days);
    const unit =
        duration === 1
            ? t("subscription.day", "day")
            : t("subscription.days", "days");
    return `${price} / ${duration} ${unit}`;
}

type PlansProps = {
    plans?: Plan[];
};

export default function Plans({ plans: initialPlans = [] }: PlansProps) {
    const { t } = useI18n();
    const { props } = usePage();
    const authUser = (props as { auth?: { user?: { email_verified_at?: string | null } | null } }).auth?.user ?? null;
    const isAuthenticated = Boolean(authUser);
    const isVerified = Boolean(authUser?.email_verified_at);
    const [plans, setPlans] = useState<Plan[]>(initialPlans);
    const [gateways, setGateways] = useState<AvailableGateway[]>([]);
    const [selectedGateway, setSelectedGateway] = useState("");
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState("");
    const [referral, setReferral] = useState<ReferralData | null>(null);
    const [paymentState, setPaymentState] = useState<PaymentState | null>(null);
    const [paymentSubscriptionPlan, setPaymentSubscriptionPlan] = useState<
        string | null
    >(null);
    const [paymentReference, setPaymentReference] = useState<string | null>(
        null,
    );

    useEffect(() => {
        if (plans.length === 0) {
            fetch("/subscription/plans", {
                headers: { Accept: "application/json" },
            })
                .then((response) => {
                    if (!response.ok) throw new Error("Unable to load plans.");
                    return response.json();
                })
                .then(setPlans)
                .catch(() => setPlans([]));
        }

        if (!isAuthenticated) return;

        fetch("/referrals/data", { headers: { Accept: "application/json" } })
            .then((response) => (response.ok ? response.json() : null))
            .then((value) => value && setReferral(value))
            .catch(() => undefined);
        if (!isAuthenticated || !isVerified) return;

        fetch("/subscription/payment-gateways", {
            headers: { Accept: "application/json" },
            credentials: "same-origin",
        })
            .then(async (response) => {
                if (!response.ok)
                    throw new Error(
                        t(
                            "subscription.no_payment_gateway",
                            "No payment method is currently available.",
                        ),
                    );
                return response.json() as Promise<{
                    gateways?: AvailableGateway[];
                }>;
            })
            .then((payload) => {
                const available = payload.gateways ?? [];
                setGateways(available);
                setSelectedGateway((current) =>
                    available.some((gateway) => gateway.slug === current)
                        ? current
                        : (available[0]?.slug ?? ""),
                );
            })
            .catch(() => setGateways([]));
    }, [isAuthenticated, isVerified, plans.length]);

    useEffect(() => {
        const params = new URLSearchParams(window.location.search);
        const payment = params.get("payment");
        const reference = params.get("reference");

        if (payment === "cancelled") {
            setPaymentReference(reference);
            setPaymentState("cancelled");
            return;
        }
        if (payment !== "success" || !reference) return;

        setPaymentReference(reference);
        setPaymentSubscriptionPlan(null);
        let stopped = false;
        let attempts = 0;
        let timer: number | null = null;

        const check = async () => {
            if (stopped) return;
            attempts += 1;
            setPaymentState("checking");
            try {
                const response = await fetch(
                    `/subscription/payment-status?reference=${encodeURIComponent(reference)}`,
                    {
                        headers: { Accept: "application/json" },
                        credentials: "same-origin",
                        cache: "no-store",
                    },
                );
                if (response.status === 401 || response.status === 419) {
                    setPaymentState("cancelled");
                    setError(
                        t(
                            "subscription.payment_session_required",
                            "Please log in again to verify this payment. The payment provider may have completed the transaction already.",
                        ),
                    );
                    return;
                }
                const data = await response.json();
                if (!response.ok)
                    throw new Error(
                        data.message ?? "Payment status unavailable.",
                    );

                const status = String(
                    data.payment?.status ?? "pending",
                ) as PaymentState;
                const subscriptionPlan = String(data.subscription?.plan ?? "");
                setPaymentState(status);
                setPaymentSubscriptionPlan(subscriptionPlan || null);
                const hasActivatedPro =
                    status === "paid" &&
                    data.subscription?.active === true &&
                    data.subscription?.plan === "pro";

                if (hasActivatedPro) {
                    window.setTimeout(() => {
                        if (!stopped) {
                            router.visit("/dashboard", {
                                replace: true,
                                preserveScroll: false,
                            });
                        }
                    }, 500);
                    return;
                }
                if (
                    ["failed", "expired", "refunded"].includes(status) ||
                    attempts >= 20
                )
                    return;
            } catch {
                if (attempts >= 20) {
                    setPaymentState("pending");
                    return;
                }
            }
            timer = window.setTimeout(check, 3000);
        };

        check();
        return () => {
            stopped = true;
            if (timer) window.clearTimeout(timer);
        };
    }, []);

    const checkout = async () => {
        if (!isAuthenticated) {
            router.visit(login());
            return;
        }
        if (!isVerified) {
            setError(
                t(
                    "subscription.verify_email_first",
                    "Please verify your email address before starting checkout.",
                ),
            );
            return;
        }
        if (!selectedGateway) {
            setError(
                t(
                    "subscription.no_payment_gateway",
                    "No payment method is currently available.",
                ),
            );
            return;
        }
        setLoading(true);
        setError("");
        try {
            const token = document.querySelector<HTMLMetaElement>(
                "meta[name=csrf-token]",
            )?.content;
            const response = await fetch("/subscription/checkout", {
                method: "POST",
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json",
                    ...(token ? { "X-CSRF-TOKEN": token } : {}),
                },
                body: JSON.stringify({ gateway: selectedGateway }),
            });
            const data = await response.json();
            if (!response.ok)
                throw new Error(data.message ?? "Checkout gagal.");
            if (data.activated_by_referral) {
                router.visit("/dashboard", {
                    replace: true,
                    preserveScroll: false,
                });
                return;
            }
            if (data.checkout_url) window.location.href = data.checkout_url;
        } catch (e) {
            setError(e instanceof Error ? e.message : "Checkout gagal.");
        } finally {
            setLoading(false);
        }
    };

    return (
        <>
            <Head title={t("subscription.title", "Subscription Plans")} />
            <div className="product-page min-h-screen bg-background text-foreground">
                <div className="product-page-content mx-auto w-full max-w-5xl">
                    {/* Header Section */}
                    <div className="mb-12 text-center">
                        <Badge
                            variant="outline"
                            className="mb-3 px-3 py-1 text-xs font-semibold text-success-600 dark:text-success-400 border-success-500/30 bg-success-500/10"
                        >
                            <Sparkles className="mr-1.5 h-3.5 w-3.5" />
                            {t("subscription.badge", "Flexible Pricing")}
                        </Badge>
                        <div className="mb-3 flex items-center justify-center gap-2 text-[10px] font-bold uppercase tracking-[0.2em] text-muted-foreground">
                            <span>Account</span>
                            <span aria-hidden="true">/</span>
                            <span className="text-foreground">Subscription</span>
                        </div>
                        <h1 className="text-3xl font-bold tracking-tight sm:text-4xl">
                            {t(
                                "subscription.choose_plan",
                                "Choose the plan that fits you",
                            )}
                        </h1>
                        <p className="mt-3 text-base text-muted-foreground max-w-xl mx-auto">
                            {t(
                                "subscription.subtitle",
                                "Start with the database-configured trial, then continue with the Pro plan when you are ready.",
                            )}
                        </p>
                    </div>

                    {/* Payment Status Banner */}
                    {paymentState && (
                        <Alert
                            className={`mx-auto mb-8 max-w-3xl ${
                                paymentState === "paid"
                                    ? "border-success-500/30 bg-success-500/10 text-success-900 dark:text-success-200"
                                    : [
                                            "failed",
                                            "expired",
                                            "refunded",
                                        ].includes(paymentState)
                                      ? "border-destructive-500/30 bg-destructive-500/10 text-destructive-900 dark:text-destructive-200"
                                      : "border-warning-500/30 bg-warning-500/10 text-warning-900 dark:text-warning-200"
                            }`}
                        >
                            {paymentState === "paid" ? (
                                <CheckCircle2 className="h-4 w-4 text-success-600 dark:text-success-400" />
                            ) : ["failed", "expired", "refunded"].includes(
                                  paymentState,
                              ) ? (
                                <XCircle className="h-4 w-4 text-destructive-600 dark:text-destructive-400" />
                            ) : (
                                <AlertCircle className="h-4 w-4 text-warning-600 dark:text-warning-400" />
                            )}
                            <AlertTitle className="font-bold">
                                {paymentState === "paid" &&
                                paymentSubscriptionPlan === "pro"
                                    ? t(
                                          "subscription.payment_paid",
                                          "Pro payment confirmed",
                                      )
                                    : paymentState === "paid"
                                      ? t(
                                            "subscription.payment_received",
                                            "Payment received",
                                        )
                                      : paymentState === "failed"
                                        ? t(
                                              "subscription.payment_failed",
                                              "Payment failed",
                                          )
                                        : paymentState === "expired"
                                          ? t(
                                                "subscription.payment_expired",
                                                "Payment expired",
                                            )
                                          : paymentState === "refunded"
                                            ? t(
                                                  "subscription.payment_refunded",
                                                  "Payment refunded",
                                              )
                                            : paymentState === "cancelled"
                                              ? t(
                                                    "subscription.checkout_cancelled",
                                                    "Checkout cancelled",
                                                )
                                              : t(
                                                    "subscription.payment_waiting",
                                                    "Waiting for payment confirmation",
                                                )}
                            </AlertTitle>
                            <AlertDescription className="mt-1 text-xs opacity-90">
                                {paymentState === "paid" &&
                                paymentSubscriptionPlan === "pro"
                                    ? t(
                                          "subscription.payment_active_redirect",
                                          "Your Pro access is active. Redirecting to your dashboard…",
                                      )
                                    : paymentState === "paid"
                                      ? t(
                                            "subscription.payment_activation_pending",
                                            "Payment is confirmed. Activating your Pro access…",
                                        )
                                      : paymentState === "cancelled"
                                        ? t(
                                              "subscription.payment_cancelled_note",
                                              "No subscription was activated. You can start checkout again when you are ready.",
                                          )
                                        : [
                                                "failed",
                                                "expired",
                                                "refunded",
                                            ].includes(paymentState)
                                          ? t(
                                                "subscription.payment_no_access",
                                                "No active Pro access was created from this payment.",
                                            )
                                          : t(
                                                "subscription.payment_processing",
                                                "The payment provider is still processing the transaction. This page checks the status automatically.",
                                            )}
                                {paymentReference && (
                                    <div className="mt-3 inline-block rounded bg-muted px-2 py-1 break-all text-[11px] font-mono opacity-90">
                                        {t(
                                            "subscription.reference",
                                            "Reference",
                                        )}
                                        : {paymentReference}
                                    </div>
                                )}
                            </AlertDescription>
                        </Alert>
                    )}

                    {/* Pricing Cards Grid */}
                    <div className="mx-auto mb-6 flex max-w-4xl flex-wrap items-center justify-center gap-2 text-xs font-medium text-muted-foreground">
                        <Link href="/dashboard" className="rounded-full px-3 py-1.5 transition hover:bg-muted hover:text-foreground">Dashboard</Link>
                        <span aria-hidden="true">•</span>
                        <Link href="/referrals" className="rounded-full px-3 py-1.5 transition hover:bg-muted hover:text-foreground">Referrals</Link>
                        <span aria-hidden="true">•</span>
                        <Link href="/settings/profile" className="rounded-full px-3 py-1.5 transition hover:bg-muted hover:text-foreground">Settings</Link>
                    </div>

                    <div className="mx-auto grid max-w-4xl gap-8 md:grid-cols-2 items-stretch">
                        {plans.map((plan) => {
                            const isPro = plan.slug === "pro";
                            return (
                                <Card
                                    key={plan.slug}
                                    className={`relative flex flex-col justify-between rounded-3xl transition-all duration-200 shadow-sm ${
                                        isPro
                                            ? "border-success-500/50 shadow-md ring-2 ring-success-500/20 bg-card"
                                            : "border-border hover:border-border/80 bg-card"
                                    }`}
                                >
                                    <CardHeader className="p-6 sm:p-8 pb-4">
                                        <div className="flex items-start justify-between gap-3">
                                            <div>
                                                <CardTitle className="text-xl font-semibold">
                                                    {plan.slug === "free"
                                                        ? t(
                                                              "subscription.free_trial",
                                                              "Free Trial",
                                                          )
                                                        : plan.name}
                                                </CardTitle>
                                                {plan.slug === "free" && (
                                                    <p className="mt-1.5 text-xs font-semibold tracking-wider text-success-600 dark:text-success-400 uppercase">
                                                        {plan.duration_days}{" "}
                                                        {t(
                                                            "subscription.full_pro_access",
                                                            "DAYS · FULL PRO ACCESS",
                                                        )}
                                                    </p>
                                                )}
                                            </div>
                                            {isPro && (
                                                <Badge className="bg-success-500/10 text-success-600 dark:text-success-400 ring-1 ring-inset ring-success-500/20 hover:bg-success-500/20">
                                                    {t(
                                                        "subscription.recommended",
                                                        "RECOMMENDED",
                                                    )}
                                                </Badge>
                                            )}
                                        </div>

                                        <div className="mt-6 flex items-baseline gap-1">
                                            <span className="text-3xl sm:text-4xl font-bold tracking-tight">
                                                {formatPrice(plan, t)}
                                            </span>
                                        </div>

                                        {isPro && referral && (
                                            <div className="mt-6 rounded-2xl border bg-muted/40 p-4 text-sm space-y-2.5">
                                                <div className="flex items-center justify-between">
                                                    <span className="text-muted-foreground">
                                                        {t(
                                                            "subscription.referral_credit",
                                                            "Referral Credit",
                                                        )}
                                                    </span>
                                                    <span className="font-semibold text-success-600 dark:text-success-400">
                                                        {new Intl.NumberFormat(
                                                            "en-US",
                                                            {
                                                                style: "currency",
                                                                currency:
                                                                    plan.currency,
                                                                maximumFractionDigits: 0,
                                                            },
                                                        ).format(
                                                            referral.credit_balance,
                                                        )}
                                                    </span>
                                                </div>
                                                <div className="flex items-center justify-between border-t pt-2.5">
                                                    <span className="font-medium">
                                                        {t(
                                                            "subscription.you_pay",
                                                            "You pay",
                                                        )}
                                                    </span>
                                                    <span className="text-lg font-bold">
                                                        {new Intl.NumberFormat(
                                                            "en-US",
                                                            {
                                                                style: "currency",
                                                                currency:
                                                                    plan.currency,
                                                                maximumFractionDigits: 0,
                                                            },
                                                        ).format(
                                                            Math.max(
                                                                0,
                                                                Number(
                                                                    plan.price_monthly,
                                                                ) -
                                                                    referral.credit_balance,
                                                            ),
                                                        )}
                                                    </span>
                                                </div>
                                                <p className="text-[11px] text-muted-foreground pt-1 leading-relaxed">
                                                    {t(
                                                        "subscription.referral_note",
                                                        "Credit is applied to the Pro price. If it covers the full price, no payment gateway is required.",
                                                    )}
                                                </p>
                                            </div>
                                        )}

                                        {plan.slug === "free" && (
                                            <div className="mt-6 rounded-2xl border border-success-500/20 bg-success-500/5 p-4 text-sm">
                                                <p className="font-semibold text-success-700 dark:text-success-300">
                                                    {t(
                                                        "subscription.no_payment",
                                                        "No payment required",
                                                    )}
                                                </p>
                                                <p className="mt-1 text-xs text-muted-foreground leading-relaxed">
                                                    {t(
                                                        "subscription.trial_description",
                                                        `Full access to ${plan.name} features during the configured trial period. Upgrade anytime before your trial ends.`,
                                                    )}
                                                </p>
                                            </div>
                                        )}
                                    </CardHeader>

                                    <CardContent className="p-6 sm:p-8 pt-0 flex-1 flex flex-col justify-between">
                                        <ul className="mt-4 space-y-3.5 text-sm text-muted-foreground">
                                            {plan.features.map((feature) => (
                                                <li
                                                    key={feature}
                                                    className="flex items-start gap-3"
                                                >
                                                    <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-success-500/10 text-success-600 dark:text-success-400 text-xs font-bold">
                                                        <Check className="h-3 w-3" />
                                                    </span>
                                                    <span className="leading-snug text-foreground">
                                                        {t(
                                                            featureLabelKeys[
                                                                feature
                                                            ] ??
                                                                "subscription.feature_unknown",
                                                            feature,
                                                        )}
                                                    </span>
                                                </li>
                                            ))}
                                        </ul>

                                        {plan.limits && (
                                            <div className="mt-6 rounded-xl border bg-muted/30 p-3.5 text-xs text-muted-foreground space-y-1">
                                                <div className="flex justify-between">
                                                    <span>
                                                        {t(
                                                            "subscription.watchlist",
                                                            "Watchlist",
                                                        )}
                                                    </span>
                                                    <span className="font-semibold text-foreground">
                                                        {plan.limits
                                                            .watchlist === -1
                                                            ? t(
                                                                  "common.unlimited",
                                                                  "Unlimited",
                                                              )
                                                            : plan.limits
                                                                  .watchlist}
                                                    </span>
                                                </div>
                                                <div className="flex justify-between">
                                                    <span>
                                                        {t(
                                                            "subscription.alerts",
                                                            "Alerts",
                                                        )}
                                                    </span>
                                                    <span className="font-semibold text-foreground">
                                                        {plan.limits
                                                            .price_alerts === -1
                                                            ? t(
                                                                  "common.unlimited",
                                                                  "Unlimited",
                                                              )
                                                            : plan.limits
                                                                  .price_alerts}
                                                    </span>
                                                </div>
                                            </div>
                                        )}
                                    </CardContent>

                                    <CardFooter className="p-6 sm:p-8 pt-0 flex flex-col gap-4">
                                        {isPro && !isAuthenticated && (
                                            <div className="w-full rounded-xl border border-primary/20 bg-primary/5 p-3 text-sm">
                                                <p className="font-medium">{t("subscription.login_required", "Log in to continue")}</p>
                                                <p className="mt-1 text-xs text-muted-foreground">
                                                    {t("subscription.login_required_note", "Your account is required to start checkout and activate Pro access.")}
                                                </p>
                                                <div className="mt-3 flex gap-2">
                                                    <Button type="button" className="flex-1" onClick={() => router.visit(login())}>
                                                        {t("auth.login", "Log in")}
                                                    </Button>
                                                    <Button type="button" variant="outline" className="flex-1" onClick={() => router.visit(register())}>
                                                        {t("auth.sign_up", "Sign up")}
                                                    </Button>
                                                </div>
                                            </div>
                                        )}

                                        {isPro && isAuthenticated && !isVerified && (
                                            <div className="w-full rounded-xl border border-warning-500/30 bg-warning-500/5 p-3 text-sm">
                                                <p className="font-medium">{t("subscription.verify_email_required", "Verify your email first")}</p>
                                                <p className="mt-1 text-xs text-muted-foreground">
                                                    {t("subscription.verify_email_required_note", "Checkout becomes available after email verification.")}
                                                </p>
                                            </div>
                                        )}

                                        {isPro && isAuthenticated && isVerified && gateways.length > 0 && (
                                            <div className="w-full space-y-2">
                                                <label className="text-sm font-medium">
                                                    {t("subscription.payment_method", "Payment method")}
                                                </label>
                                                <Select value={selectedGateway} onValueChange={setSelectedGateway} disabled={loading}>
                                                    <SelectTrigger className="w-full">
                                                        <SelectValue placeholder={t("subscription.select_gateway", "Select payment method")} />
                                                    </SelectTrigger>
                                                    <SelectContent>
                                                        {gateways.map((gateway) => (
                                                            <SelectItem key={gateway.slug} value={gateway.slug}>
                                                                {gateway.name}
                                                            </SelectItem>
                                                        ))}
                                                    </SelectContent>
                                                </Select>
                                            </div>
                                        )}
                                        <Button
                                            type="button"
                                            className={`w-full font-semibold shadow-sm transition-all duration-200 ${
                                                isPro
                                                    ? "bg-primary hover:bg-primary/90 text-primary-foreground! shadow-primary/20"
                                                    : "bg-muted text-muted-foreground cursor-default border hover:bg-muted"
                                            }`}
                                            disabled={
                                                !isPro ||
                                                loading ||
                                                !isAuthenticated ||
                                                !isVerified ||
                                                gateways.length === 0
                                            }
                                            onClick={isPro ? checkout : undefined}
                                        >
                                            {isPro
                                                ? !isAuthenticated
                                                    ? t("subscription.login_to_upgrade", "Log in to upgrade")
                                                    : !isVerified
                                                      ? t("subscription.verify_to_upgrade", "Verify email to upgrade")
                                                      : loading
                                                        ? t("subscription.creating_checkout", "Creating checkout…")
                                                        : gateways.length === 0
                                                          ? t("subscription.no_payment_gateway", "No payment method is currently available.")
                                                          : `Upgrade to Pro — ${formatPrice({ ...plan, price_monthly: Math.max(0, Number(plan.price_monthly) - (referral?.credit_balance ?? 0)) }, t)}`
                                                : t("subscription.trial_included", "Included with registration")}
                                        </Button>
                                    </CardFooter>
                                </Card>
                            );
                        })}
                    </div>

                    {error && (
                        <div className="mt-6 mx-auto max-w-md rounded-xl bg-destructive/10 border border-destructive/20 p-3 text-center text-sm text-destructive">
                            {error}
                        </div>
                    )}
                    <p className="mt-10 text-center text-xs text-muted-foreground">
                        {gateways.length === 0
                            ? t(
                                  "subscription.no_payment_gateway",
                                  "No payment method is currently available.",
                              )
                            : t(
                                  "subscription.checkout_disclaimer",
                                  "Payment is securely processed by the selected payment provider. You will be redirected to its checkout page.",
                              )}
                    </p>
                </div>
            </div>
        </>
    );
}
