import { Head, router } from '@inertiajs/react';
import { Check } from 'lucide-react';
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import {
    Dialog,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import AppLayout from '@/layouts/app-layout';
import { useT } from '@/lib/i18n';

type Gateway = 'stripe' | 'paypal' | 'razorpay';

type Plan = {
    id: string;
    name: string;
    slug: 'free' | 'standard' | 'pro' | 'custom' | string;
    monthly_conversations: number;
    price_cents: number;
    features: string[] | null;
    is_purchasable: boolean;
};

type Summary = {
    plan: {
        id: string;
        name: string;
        slug: string;
        monthly_conversations: number;
        price_cents: number;
    } | null;
    used: number;
    limit: number;
    percent: number;
    subscription_status: string | null;
};

type Props = {
    plans: Plan[];
    summary: Summary;
    stripe_configured: boolean;
    available_gateways: Gateway[];
    has_active_subscription: boolean;
    active_gateway: Gateway | null;
    subscription_cancel_at_period_end: boolean;
    flash_checkout?: { status: string | null; gateway?: string | null };
};

const formatPrice = (
    cents: number,
    slug: string,
    t: (key: string) => string,
): string => {
    if (slug === 'custom') {
        return t('Custom');
    }

    if (cents === 0) {
        return '$0';
    }

    return `$${Math.round(cents / 100)}`;
};

const formatLimit = (n: number, t: (key: string) => string): string => {
    if (n === 0) {
        return t('Unlimited');
    }

    if (n >= 1000) {
        return `${(n / 1000).toFixed(n % 1000 === 0 ? 0 : 1)}k`;
    }

    return n.toLocaleString();
};

export default function BillingPage({
    plans,
    summary,
    stripe_configured,
    available_gateways,
    has_active_subscription,
    active_gateway,
    subscription_cancel_at_period_end,
    flash_checkout,
}: Props) {
    const { t } = useT();
    const TAGLINE: Record<string, string> = {
        free: t('For getting live fast'),
        standard: t('Level up productivity'),
        pro: t('For teams ready to scale'),
        custom: t('Tailored solutions for enterprises'),
    };
    const GATEWAY_LABEL: Record<Gateway, string> = {
        stripe: t('Credit / debit card (Stripe)'),
        paypal: t('PayPal'),
        razorpay: t('Razorpay (UPI, cards, netbanking)'),
    };
    const currentSlug = summary.plan?.slug ?? 'free';
    const checkoutStatus = flash_checkout?.status ?? null;

    const gateways = available_gateways ?? [];
    const anyConfigured = gateways.length > 0;

    // Pending plan slug while picking a gateway. Null when the modal isn't
    // open. We always pick a default gateway (first available) so the
    // submit button works without a forced selection.
    const [pendingSlug, setPendingSlug] = useState<string | null>(null);
    const [pendingGateway, setPendingGateway] = useState<Gateway | null>(
        gateways[0] ?? null,
    );

    const onChoose = (slug: string) => {
        if (!anyConfigured) {
            return;
        }

        // Already on a paid plan with this gateway? Use the in-place swap
        // path on Stripe; non-Stripe gateways re-enter the checkout flow
        // (CheckoutController orphan-cancels the prior sub before creating
        // the new one).
        if (has_active_subscription && active_gateway === 'stripe') {
            if (
                !window.confirm(
                    t(
                        'Swap to :name now? The change is immediate and Stripe will prorate the difference on your next invoice.',
                        { name: slug },
                    ),
                )
            ) {
                return;
            }

            router.post('/billing/swap', { plan_slug: slug });

            return;
        }

        // Only one gateway live? Skip the picker — submit straight through.
        if (gateways.length === 1) {
            router.post('/billing/checkout', {
                plan_slug: slug,
                gateway: gateways[0],
            });

            return;
        }

        setPendingSlug(slug);
        setPendingGateway(gateways[0] ?? null);
    };

    const onCancel = () => {
        if (
            !window.confirm(
                t(
                    'Cancel your subscription? You keep access until the end of the current billing period, then drop back to Free.',
                ),
            )
        ) {
            return;
        }

        router.post('/billing/cancel', {});
    };

    const onResume = () => {
        router.post('/billing/resume', {});
    };

    const onConfirmGateway = () => {
        if (pendingSlug === null || pendingGateway === null) {
            return;
        }

        router.post('/billing/checkout', {
            plan_slug: pendingSlug,
            gateway: pendingGateway,
        });

        setPendingSlug(null);
    };

    const usagePercent =
        summary.limit === 0 ? 0 : Math.min(100, summary.percent);
    const overLimit = summary.limit > 0 && summary.used >= summary.limit;
    const nearLimit = !overLimit && usagePercent >= 80;

    const getPlanFeatures = (plan: Plan): string[] => {
        return Array.isArray(plan.features) ? plan.features : [];
    };

    return (
        <AppLayout
            breadcrumbs={[{ title: t('Billing'), href: '/app/billing' }]}
        >
            <Head title={t('Billing')} />
            <div className="flex flex-1 flex-col gap-6 p-4">
                <div>
                    <h1 className="text-2xl font-semibold tracking-tight">
                        {t('Billing')}
                    </h1>
                    <p className="mt-1 text-sm text-muted-foreground">
                        {t(
                            'Plans, usage, and subscription for this workspace.',
                        )}
                    </p>
                </div>

                {checkoutStatus === 'success' && (
                    <Card className="border-emerald-500/30 bg-emerald-500/5 p-4">
                        <p className="text-sm text-emerald-700 dark:text-emerald-400">
                            {t(
                                "Subscription confirmed — your new plan is active. If you don't see the change yet, it'll appear once the payment provider finishes notifying us (usually within a few seconds).",
                            )}
                        </p>
                    </Card>
                )}
                {checkoutStatus === 'cancelled' && (
                    <Card className="border-amber-500/30 bg-amber-500/5 p-4">
                        <p className="text-sm text-amber-700 dark:text-amber-400">
                            {t('Checkout cancelled — no charge was made.')}
                        </p>
                    </Card>
                )}

                <Card className="p-5">
                    <div className="flex flex-wrap items-center justify-between gap-3">
                        <div>
                            <p className="text-xs tracking-wide text-muted-foreground uppercase">
                                {t('Current plan')}
                            </p>
                            <p className="mt-1 text-xl font-semibold">
                                {summary.plan?.name ?? t('Free')}
                            </p>
                        </div>
                        <div className="text-end">
                            <p className="text-xs tracking-wide text-muted-foreground uppercase">
                                {t('This month')}
                            </p>
                            <p className="mt-1 text-xl font-semibold">
                                {summary.used.toLocaleString()}
                                <span className="text-sm font-normal text-muted-foreground">
                                    {' '}
                                    /{' '}
                                    {summary.limit === 0
                                        ? t('Unlimited')
                                        : t(':count conversations', {
                                              count: summary.limit.toLocaleString(),
                                          })}
                                </span>
                            </p>
                        </div>
                    </div>
                    {has_active_subscription && (
                        <div className="mt-4 flex flex-wrap justify-end gap-2">
                            {subscription_cancel_at_period_end &&
                                active_gateway === 'stripe' && (
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={onResume}
                                    >
                                        {t('Resume subscription')}
                                    </Button>
                                )}
                            {!subscription_cancel_at_period_end && (
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={onCancel}
                                    className="text-rose-600 hover:bg-rose-500/10 hover:text-rose-700"
                                >
                                    {t('Cancel subscription')}
                                </Button>
                            )}
                            <Button asChild variant="outline" size="sm">
                                <a href="/billing/portal">
                                    {t('Manage subscription')}
                                </a>
                            </Button>
                        </div>
                    )}
                    {subscription_cancel_at_period_end && (
                        <p className="mt-3 text-xs text-amber-600 dark:text-amber-400">
                            {t(
                                'Your subscription is scheduled to end at the close of the current billing period. Resume to keep your plan.',
                            )}
                        </p>
                    )}
                    {summary.limit > 0 && (
                        <div className="mt-4">
                            <div className="h-2 w-full overflow-hidden rounded-full bg-muted">
                                <div
                                    className={`h-full transition-all ${
                                        overLimit
                                            ? 'bg-rose-500'
                                            : nearLimit
                                              ? 'bg-amber-500'
                                              : 'bg-emerald-500'
                                    }`}
                                    style={{ width: `${usagePercent}%` }}
                                />
                            </div>
                            {overLimit && (
                                <p className="mt-2 text-xs text-rose-600 dark:text-rose-400">
                                    {t(
                                        'You\'ve reached your monthly conversation limit. New visitors get a friendly "we\'re full" message until you upgrade or the month resets.',
                                    )}
                                </p>
                            )}
                            {nearLimit && (
                                <p className="mt-2 text-xs text-amber-600 dark:text-amber-400">
                                    {t(
                                        ':pct% of your monthly conversation budget remaining.',
                                        { pct: 100 - usagePercent },
                                    )}
                                </p>
                            )}
                        </div>
                    )}
                </Card>

                <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                    {plans.map((plan) => {
                        const isCurrent = plan.slug === currentSlug;
                        const tagline = TAGLINE[plan.slug] ?? '';

                        return (
                            <Card
                                key={plan.id}
                                className={`flex flex-col p-5 ${isCurrent ? 'border-foreground/30 ring-1 ring-foreground/20' : ''}`}
                            >
                                <div className="mb-4 flex items-center gap-2">
                                    <h2 className="text-xl font-semibold tracking-tight">
                                        {plan.name}
                                    </h2>
                                    {plan.slug === 'standard' && (
                                        <span className="rounded bg-gradient-to-r from-violet-500 to-orange-500 px-1.5 py-0.5 text-[10px] font-semibold tracking-wide text-white uppercase">
                                            {t('Popular')}
                                        </span>
                                    )}
                                    {isCurrent && (
                                        <span className="rounded bg-foreground/10 px-1.5 py-0.5 text-[10px] font-semibold tracking-wide uppercase">
                                            {t('Current')}
                                        </span>
                                    )}
                                </div>
                                <p className="text-xs text-muted-foreground">
                                    {tagline}
                                </p>

                                <div className="mt-6">
                                    <span className="text-3xl font-semibold">
                                        {formatPrice(
                                            plan.price_cents,
                                            plan.slug,
                                            t,
                                        )}
                                    </span>
                                    {plan.slug !== 'custom' && (
                                        <span className="ms-1 text-xs text-muted-foreground">
                                            {t('/ month')}
                                        </span>
                                    )}
                                </div>

                                <ul className="mt-5 flex-1 space-y-2 text-sm">
                                    <li className="flex items-start gap-2">
                                        <Check className="mt-0.5 size-4 shrink-0 text-emerald-600" />
                                        <span>
                                            {formatLimit(
                                                plan.monthly_conversations,
                                                t,
                                            )}
                                            {plan.monthly_conversations > 0
                                                ? ` ${t('conversations')}`
                                                : ` ${t('conversations')}`}
                                        </span>
                                    </li>
                                    <li className="flex items-start gap-2">
                                        <Check className="mt-0.5 size-4 shrink-0 text-emerald-600" />
                                        <span>
                                            {t('Unlimited data sources')}
                                        </span>
                                    </li>
                                    {getPlanFeatures(plan).map((f) => (
                                        <li
                                            key={f}
                                            className="flex items-start gap-2"
                                        >
                                            <Check className="mt-0.5 size-4 shrink-0 text-emerald-600" />
                                            <span>{f}</span>
                                        </li>
                                    ))}
                                </ul>

                                <div className="mt-6">
                                    {isCurrent ? (
                                        <Button
                                            variant="outline"
                                            className="w-full"
                                            disabled
                                        >
                                            {t('Current plan')}
                                        </Button>
                                    ) : plan.slug === 'custom' ? (
                                        <Button
                                            asChild
                                            variant="outline"
                                            className="w-full"
                                        >
                                            <a href="mailto:sales@pitchbar.io?subject=Custom plan">
                                                {t('Contact sales')}
                                            </a>
                                        </Button>
                                    ) : (
                                        <Button
                                            className="w-full"
                                            disabled={!plan.is_purchasable}
                                            onClick={() => onChoose(plan.slug)}
                                            title={
                                                !plan.is_purchasable
                                                    ? t(
                                                          'No payment gateway is configured for this install yet',
                                                      )
                                                    : undefined
                                            }
                                        >
                                            {!plan.is_purchasable
                                                ? t('Coming soon')
                                                : has_active_subscription
                                                  ? (summary.plan?.price_cents ??
                                                        0) < plan.price_cents
                                                      ? t('Upgrade to :name', {
                                                            name: plan.name,
                                                        })
                                                      : t('Downgrade to :name', {
                                                            name: plan.name,
                                                        })
                                                  : t('Choose :name', {
                                                        name: plan.name,
                                                    })}
                                        </Button>
                                    )}
                                </div>
                            </Card>
                        );
                    })}
                </div>

                {!anyConfigured && (
                    <Card className="border-dashed p-4">
                        <p className="text-sm text-muted-foreground">
                            {t(
                                'No payment gateway is configured yet, so paid plans show as "Coming soon". Configure Stripe, PayPal, or Razorpay in',
                            )}{' '}
                            <code className="rounded bg-muted px-1 py-0.5 text-xs">
                                {t('Settings → System → Billing')}
                            </code>{' '}
                            {t('to enable upgrades.')}
                        </p>
                    </Card>
                )}

                {!stripe_configured && anyConfigured && (
                    <Card className="border-dashed p-4">
                        <p className="text-xs text-muted-foreground">
                            {t(
                                "Stripe isn't configured on this install — paid plans still work via :gateways but card-only checkout via Stripe is unavailable.",
                                { gateways: gateways.join(' / ') },
                            )}
                        </p>
                    </Card>
                )}
            </div>

            <Dialog
                open={pendingSlug !== null}
                onOpenChange={(open) => {
                    if (!open) {
                        setPendingSlug(null);
                    }
                }}
            >
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>{t('Pick a payment method')}</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-2">
                        {gateways.map((g) => (
                            <label
                                key={g}
                                className={`flex cursor-pointer items-center gap-3 rounded border p-3 text-sm transition ${
                                    pendingGateway === g
                                        ? 'border-foreground/40 bg-foreground/5'
                                        : 'border-border hover:bg-foreground/5'
                                }`}
                            >
                                <input
                                    type="radio"
                                    name="gateway"
                                    value={g}
                                    checked={pendingGateway === g}
                                    onChange={() => setPendingGateway(g)}
                                />
                                <span>{GATEWAY_LABEL[g]}</span>
                            </label>
                        ))}
                    </div>
                    <DialogFooter>
                        <Button
                            variant="outline"
                            onClick={() => setPendingSlug(null)}
                        >
                            {t('Cancel')}
                        </Button>
                        <Button
                            onClick={onConfirmGateway}
                            disabled={pendingGateway === null}
                        >
                            {t('Continue')}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </AppLayout>
    );
}
