import { useCurrency } from '@/hooks/useCurrency';
import ClientLayout from '@/Layouts/ClientLayout';
import { PageProps, PlanOption } from '@/types';
import { Head, useForm } from '@inertiajs/react';
import { CheckCircle2, CreditCard, Sparkles } from 'lucide-react';
import { useState } from 'react';
import SetupStepper from './components/SetupStepper';

type Props = PageProps<{
    tenant: { id: string; name: string };
    plans: PlanOption[];
    currentPlanId: number | null;
}>;

export default function Plan({ tenant, plans, currentPlanId }: Props) {
    const [cycle, setCycle] = useState<'monthly' | 'yearly'>('monthly');
    const { format } = useCurrency();

    function formatPrice(plan: PlanOption, c: 'monthly' | 'yearly'): string {
        const price = c === 'yearly' ? plan.price_yearly : plan.price_monthly;
        const num = parseFloat(price);
        if (num === 0) return 'Free';
        return `${format(num)}/${c === 'yearly' ? 'yr' : 'mo'}`;
    }

    const { data, setData, post, processing, errors } = useForm({
        plan_id: currentPlanId ?? plans[0]?.id ?? 0,
        billing_cycle: cycle,
    });

    function submit(e: React.FormEvent) {
        e.preventDefault();
        post(route('setup.plan.store', { tenant: tenant.id }));
    }

    return (
        <ClientLayout title="Setup — Plan">
            <Head title="Setup: Select Plan" />

            <div className="mx-auto max-w-3xl space-y-6 p-6 lg:p-8">
                <SetupStepper current={3} />

                <div className="pf-glass p-6 sm:p-8">
                    <div className="mb-6 flex items-center gap-3">
                        <span className="bg-primary/10 flex h-10 w-10 items-center justify-center rounded-xl">
                            <CreditCard className="text-primary h-5 w-5" />
                        </span>
                        <div>
                            <h1 className="text-foreground text-lg font-semibold">
                                Select a plan for {tenant.name}
                            </h1>
                            <p className="text-muted-foreground text-sm">
                                Every plan starts with a free trial. No credit
                                card required.
                            </p>
                        </div>
                    </div>

                    <form onSubmit={submit} className="space-y-6">
                        {/* Billing cycle toggle */}
                        <div className="flex justify-center">
                            <div className="bg-muted/40 border-border inline-flex rounded-xl border p-1">
                                {(['monthly', 'yearly'] as const).map((c) => (
                                    <button
                                        key={c}
                                        type="button"
                                        onClick={() => {
                                            setCycle(c);
                                            setData('billing_cycle', c);
                                        }}
                                        className={`rounded-lg px-4 py-1.5 text-sm font-medium transition-all ${
                                            cycle === c
                                                ? 'bg-background text-foreground shadow-sm'
                                                : 'text-muted-foreground hover:text-foreground'
                                        }`}
                                    >
                                        {c === 'monthly' ? 'Monthly' : 'Yearly'}
                                        {c === 'yearly' && (
                                            <span className="text-primary ml-1.5 text-[10px] font-bold">
                                                SAVE 20%
                                            </span>
                                        )}
                                    </button>
                                ))}
                            </div>
                        </div>

                        {/* Plan cards */}
                        {plans.length === 0 ? (
                            <div className="py-12 text-center">
                                <Sparkles className="text-muted-foreground dark:text-muted-foreground/40 mx-auto mb-3 h-8 w-8" />
                                <p className="text-muted-foreground text-sm">
                                    No plans available yet. Contact support.
                                </p>
                            </div>
                        ) : (
                            <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
                                {plans.map((plan) => {
                                    const selected = data.plan_id === plan.id;
                                    return (
                                        <button
                                            key={plan.id}
                                            type="button"
                                            onClick={() =>
                                                setData('plan_id', plan.id)
                                            }
                                            className={`relative rounded-xl border p-5 text-left transition-all ${
                                                selected
                                                    ? 'border-primary bg-primary/5 ring-primary/30 ring-2'
                                                    : 'border-border hover:border-primary/40 hover:bg-muted/20'
                                            }`}
                                        >
                                            {selected && (
                                                <CheckCircle2 className="text-primary absolute top-3 right-3 h-4 w-4" />
                                            )}
                                            <p className="text-foreground mb-1 text-sm font-semibold">
                                                {plan.name}
                                            </p>
                                            <p className="text-primary mb-3 text-lg font-bold">
                                                {formatPrice(plan, cycle)}
                                            </p>
                                            {plan.description && (
                                                <p className="text-muted-foreground text-xs leading-relaxed">
                                                    {plan.description}
                                                </p>
                                            )}
                                            {(plan.trial_days ?? 0) > 0 && (
                                                <p className="text-primary mt-3 text-xs font-medium">
                                                    {plan.trial_days}-day free
                                                    trial
                                                </p>
                                            )}
                                        </button>
                                    );
                                })}
                            </div>
                        )}

                        {errors.plan_id && (
                            <p className="text-destructive text-xs">
                                {errors.plan_id}
                            </p>
                        )}

                        <div className="flex items-center justify-between pt-2">
                            <a
                                href={route('setup.subdomain', {
                                    tenant: tenant.id,
                                })}
                                className="text-muted-foreground hover:text-foreground text-sm transition-colors"
                            >
                                ← Back
                            </a>
                            <button
                                type="submit"
                                disabled={processing || !data.plan_id}
                                className="pf-btn px-6 py-2.5 text-sm disabled:cursor-not-allowed disabled:opacity-50"
                            >
                                {processing
                                    ? 'Activating trial…'
                                    : 'Start free trial →'}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </ClientLayout>
    );
}
