import { Link, usePage } from '@inertiajs/react';
import AppLayout from '@/layouts/AppLayout';
import { useState } from 'react';
import { useTranslator } from '@/lib/i18n';

type Gateway = { key: string; label: string; offline: boolean };

interface Props {
    plan: 'free' | 'premium' | 'planner';
    hasStripeCustomer: boolean;
    gateways?: Gateway[];
}

export default function Billing({ plan, hasStripeCustomer, gateways = [] }: Props) {
    const t = useTranslator();
    const { auth } = usePage<any>().props;
    const csrf = (document.querySelector('meta[name=csrf-token]') as HTMLMetaElement | null)?.content ?? '';
    const planLabel = t(`billing.${plan}`);
    const planDesc = t(`billing.plan_${plan}_desc`);

    return (
        <AppLayout>
            <div className="max-w-3xl mx-auto px-4 sm:px-6 py-10">
                <div className="mb-10">
                    <p className="text-[11px] font-medium tracking-[0.22em] uppercase text-primary mb-2">
                        {t('billing.eyebrow')}
                    </p>
                    <h1 className="font-serif text-[2.2rem] sm:text-[2.6rem] tracking-[-0.022em] leading-[1.05]">
                        {t('billing.heading_your')} <em className="italic text-primary">{t('billing.heading_plan')}</em>
                    </h1>
                </div>

                {/* Current plan card */}
                <div className="bg-card border border-border rounded-3xl p-6 sm:p-7 mb-6">
                    <div className="flex items-baseline justify-between flex-wrap gap-3 mb-5">
                        <div>
                            <p className="text-[10.5px] font-medium tracking-[0.22em] uppercase text-muted-foreground mb-1.5">
                                {t('billing.current_plan')}
                            </p>
                            <h2 className="font-serif text-[2rem] tracking-tight leading-none">
                                {planLabel}
                            </h2>
                            <p className="text-[14px] text-muted-foreground mt-2 max-w-md">{planDesc}</p>
                        </div>
                        <span className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-[11.5px] font-medium tracking-tight ${
                            plan === 'free'
                                ? 'bg-muted text-foreground/70 border border-border'
                                : 'bg-primary/[0.10] text-primary border border-primary/20'
                        }`}>
                            <span className="w-1.5 h-1.5 rounded-full bg-current" />
                            {`${t('billing.active')} · ${planLabel}`}
                        </span>
                    </div>

                    <div className="flex flex-wrap gap-3 pt-2 border-t border-border">
                        {plan === 'free' && (
                            <Link href="/pricing" className="btn-charcoal !py-2.5 !px-5 !text-[13.5px]">
                                {t('billing.compare_plans')}
                            </Link>
                        )}

                        {plan === 'free' && (
                            <UpgradeButton plan="premium" label={t('billing.upgrade_to', { plan: t('billing.premium') })} csrf={csrf} gateways={gateways} />
                        )}

                        {hasStripeCustomer && (
                            <form method="POST" action="/billing/portal">
                                <input type="hidden" name="_token" value={csrf} />
                                <input type="hidden" name="return_url" value="/settings/billing" />
                                <button type="submit" className="btn-outline !py-2.5 !px-5 !text-[13.5px]">
                                    {t('billing.manage_stripe')}
                                </button>
                            </form>
                        )}

                        {hasStripeCustomer && (
                            <form method="POST" action="/billing/sync">
                                <input type="hidden" name="_token" value={csrf} />
                                <button type="submit" className="text-[12.5px] text-muted-foreground hover:text-foreground transition-colors px-2 py-2.5">
                                    {t('billing.refresh_stripe')}
                                </button>
                            </form>
                        )}
                    </div>
                </div>

                {/* Upgrade card — only shown to non-Planner */}
                {plan !== 'planner' && (
                    <div className="rounded-3xl border border-border bg-muted/30 p-6 sm:p-7">
                        <p className="text-[10.5px] font-medium tracking-[0.22em] uppercase text-primary mb-2">
                            {t('billing.for_planners')}
                        </p>
                        <h3 className="font-serif text-[1.5rem] tracking-tight mb-1.5">
                            {t('billing.manage_multiple')}
                        </h3>
                        <p className="text-[14px] text-muted-foreground mb-5 max-w-md">
                            {t('billing.planner_pitch')}
                        </p>
                        <UpgradeButton plan="planner" label={t('billing.upgrade_to', { plan: t('billing.planner') })} csrf={csrf} gateways={gateways} />
                    </div>
                )}

                <p className="text-[11.5px] text-muted-foreground mt-8 text-center">
                    {t('billing.signed_in_as')} <span className="text-foreground">{auth?.user?.email}</span>
                </p>
            </div>
        </AppLayout>
    );
}

function UpgradeButton({ plan, label, csrf, gateways }: { plan: string; label: string; csrf: string; gateways: Gateway[] }) {
    const [gateway, setGateway] = useState(gateways[0]?.key ?? 'stripe');
    return (
        <form method="POST" action="/billing/checkout" className="inline-flex items-center gap-2">
            <input type="hidden" name="_token" value={csrf} />
            <input type="hidden" name="plan" value={plan} />
            <input type="hidden" name="gateway" value={gateway} />
            {gateways.length > 1 && (
                <select
                    value={gateway}
                    onChange={(e) => setGateway(e.target.value)}
                    className="border border-border rounded-lg px-2.5 py-2.5 text-[13px] bg-card"
                >
                    {gateways.map((g) => <option key={g.key} value={g.key}>{g.label}</option>)}
                </select>
            )}
            <button type="submit" className="btn-charcoal !py-2.5 !px-5 !text-[13.5px]">
                {label}
            </button>
        </form>
    );
}
