import { Link, useForm } from '@inertiajs/react';
import AppLayout from '@/layouts/AppLayout';
import { useState } from 'react';
import { CURRENCIES, currencyForCountry, capitalForCountry } from '@/lib/locales';
import { CountryCombobox } from '@/components/country-combobox';
import { useTranslator, useLocale } from '@/lib/i18n';

interface Wedding {
    id: string;
    partner_a_name: string;
    partner_b_name: string;
    wedding_date?: string;
    venue_name?: string;
    venue_city?: string;
    venue_country?: string;
    created_at: string;
}

interface Props {
    weddings: Wedding[];
    weddingLimit: number | null;
    canCreateWedding: boolean;
}

export default function WeddingsIndex({ weddings, weddingLimit, canCreateWedding }: Props) {
    const t = useTranslator();
    const locale = useLocale();
    const dateLocale = locale === 'fr' ? 'fr-FR' : 'en-US';
    const [showCreate, setShowCreate] = useState(false);
    const [showUpgrade, setShowUpgrade] = useState(false);

    // Clicking "New Wedding" at the plan cap opens an upgrade panel that
    // explains the limit, rather than a create form that would be silently
    // rejected server-side by Plans::checkWeddingLimit.
    function handleNewWedding() {
        if (canCreateWedding) setShowCreate(true);
        else setShowUpgrade(true);
    }
    const { data, setData, post, processing, errors, reset } = useForm({
        partner_a_name: '',
        partner_b_name: '',
        wedding_date: '',
        venue_name: '',
        venue_city: '',
        venue_country: '',
        currency: 'USD',
    });

    function handleSubmit(e: React.FormEvent) {
        e.preventDefault();
        post('/weddings', {
            onSuccess: () => { reset(); setShowCreate(false); },
        });
    }

    return (
        <AppLayout>
            <div className="max-w-3xl mx-auto px-6 py-10">
                <div className="flex items-center justify-between mb-8">
                    <div>
                        <h1 className="font-serif text-[2rem] text-foreground">{t('weddings_index.title')}</h1>
                        {weddings.length > 0 && (
                            <p className="text-sm text-muted-foreground mt-1">
                                {weddings.length} {weddings.length === 1 ? t('weddings_index.wedding_one') : t('weddings_index.wedding_other')}
                            </p>
                        )}
                    </div>
                    <button
                        onClick={handleNewWedding}
                        className="bg-primary text-primary-foreground px-4 py-2 rounded-xl text-sm font-medium hover:opacity-90 transition-opacity flex items-center gap-1.5"
                    >
                        <span className="text-base leading-none">+</span>
                        {t('weddings_index.new_wedding')}
                    </button>
                </div>

                {weddings.length === 0 ? (
                    <div className="text-center py-24 border border-dashed border-border rounded-2xl">
                        <p className="text-4xl mb-5 opacity-60">◉</p>
                        <h2 className="font-serif text-2xl text-foreground mb-2">{t('weddings_index.empty_title')}</h2>
                        <p className="text-muted-foreground mb-7 text-[15px]">
                            {t('weddings_index.empty_desc')}
                        </p>
                        <button
                            onClick={handleNewWedding}
                            className="bg-primary text-primary-foreground px-6 py-2.5 rounded-xl font-medium hover:opacity-90 transition-opacity text-sm"
                        >
                            {t('weddings_index.create_wedding')}
                        </button>
                    </div>
                ) : (
                    <div className="grid gap-3">
                        {weddings.map((w) => {
                            const venue = [w.venue_name, w.venue_city, w.venue_country].filter(Boolean).join(', ');
                            return (
                                <Link
                                    key={w.id}
                                    href={`/weddings/${w.id}`}
                                    className="bg-card border border-border rounded-2xl p-6 hover:border-primary/25 hover:shadow-md transition-all duration-150 block group"
                                >
                                    <div className="flex items-start justify-between gap-4">
                                        <div className="min-w-0">
                                            <h2 className="font-serif text-[1.35rem] text-foreground group-hover:text-primary transition-colors leading-tight">
                                                {w.partner_a_name} & {w.partner_b_name}
                                            </h2>
                                            {venue && (
                                                <p className="text-sm text-muted-foreground mt-1 truncate">
                                                    {venue}
                                                </p>
                                            )}
                                        </div>
                                        {w.wedding_date && (
                                            <span className="text-[12px] text-muted-foreground bg-muted px-3 py-1.5 rounded-full whitespace-nowrap flex-shrink-0">
                                                {new Date(w.wedding_date).toLocaleDateString(dateLocale, {
                                                    month: 'short', day: 'numeric', year: 'numeric',
                                                })}
                                            </span>
                                        )}
                                    </div>
                                </Link>
                            );
                        })}
                    </div>
                )}
            </div>

            {/* Create Modal */}
            {showCreate && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm animate-fade-in">
                    <div className="bg-card rounded-2xl w-full max-w-lg shadow-xl shadow-foreground/10 border border-border animate-fade-up">
                        <div className="p-7">
                            <h2 className="font-serif text-2xl mb-6">{t('weddings_index.create_new')}</h2>
                            <form onSubmit={handleSubmit} className="space-y-4">
                                <div className="grid grid-cols-2 gap-3">
                                    <div>
                                        <label className="block text-[12px] font-medium text-muted-foreground mb-1.5">
                                            {t('wedding.partner_a_name')} *
                                        </label>
                                        <input
                                            type="text"
                                            value={data.partner_a_name}
                                            onChange={e => setData('partner_a_name', e.target.value)}
                                            className="input"
                                            placeholder="Alex"
                                            required
                                        />
                                        {errors.partner_a_name && <p className="text-danger text-xs mt-1">{errors.partner_a_name}</p>}
                                    </div>
                                    <div>
                                        <label className="block text-[12px] font-medium text-muted-foreground mb-1.5">
                                            {t('wedding.partner_b_name')} *
                                        </label>
                                        <input
                                            type="text"
                                            value={data.partner_b_name}
                                            onChange={e => setData('partner_b_name', e.target.value)}
                                            className="input"
                                            placeholder="Jordan"
                                            required
                                        />
                                        {errors.partner_b_name && <p className="text-danger text-xs mt-1">{errors.partner_b_name}</p>}
                                    </div>
                                </div>

                                <div>
                                    <label className="block text-[12px] font-medium text-muted-foreground mb-1.5">
                                        {t('wedding.wedding_date')}
                                    </label>
                                    <input
                                        type="date"
                                        value={data.wedding_date}
                                        onChange={e => setData('wedding_date', e.target.value)}
                                        className="input"
                                    />
                                </div>

                                <div>
                                    <label className="block text-[12px] font-medium text-muted-foreground mb-1.5">
                                        {t('wedding.venue_name')}
                                    </label>
                                    <input
                                        type="text"
                                        value={data.venue_name}
                                        onChange={e => setData('venue_name', e.target.value)}
                                        placeholder={t('weddings_index.venue_placeholder')}
                                        className="input"
                                    />
                                </div>

                                <div className="grid grid-cols-2 gap-3">
                                    <div>
                                        <label className="block text-[12px] font-medium text-muted-foreground mb-1.5">{t('wedding.venue_city')}</label>
                                        <input
                                            type="text"
                                            value={data.venue_city}
                                            onChange={e => setData('venue_city', e.target.value)}
                                            placeholder={t('weddings_index.city_placeholder')}
                                            className="input"
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-[12px] font-medium text-muted-foreground mb-1.5">{t('wedding.venue_country')}</label>
                                        <CountryCombobox
                                            value={data.venue_country}
                                            onChange={(code) => {
                                                setData('venue_country', code);
                                                // Auto-fill currency only if user hasn't intentionally changed it.
                                                const nextCurrency = currencyForCountry(code);
                                                if (nextCurrency && data.currency === 'USD') {
                                                    setData('currency', nextCurrency);
                                                }
                                                // Auto-fill venue_city with the capital, only when empty.
                                                const cap = capitalForCountry(code);
                                                if (cap && !data.venue_city) {
                                                    setData('venue_city', cap);
                                                }
                                            }}
                                            placeholder={t('wedding_edit.country_placeholder')}
                                        />
                                    </div>
                                </div>

                                <div>
                                    <label className="block text-[12px] font-medium text-muted-foreground mb-1.5">
                                        {t('wedding.currency')}
                                    </label>
                                    <select
                                        value={data.currency}
                                        onChange={(e) => setData('currency', e.target.value)}
                                        className="input"
                                    >
                                        {CURRENCIES.map((c) => (
                                            <option key={c.code} value={c.code}>
                                                {c.code} — {c.name} ({c.symbol})
                                            </option>
                                        ))}
                                    </select>
                                    <p className="text-[11.5px] text-muted-foreground mt-1.5">
                                        {t('weddings_index.currency_help')}
                                    </p>
                                </div>

                                <div className="flex gap-3 pt-2">
                                    <button
                                        type="button"
                                        onClick={() => { setShowCreate(false); reset(); }}
                                        className="flex-1 border border-border rounded-xl py-2.5 text-sm text-muted-foreground hover:text-foreground hover:bg-muted transition-all"
                                    >
                                        {t('common.cancel')}
                                    </button>
                                    <button
                                        type="submit"
                                        disabled={processing}
                                        className="flex-1 bg-primary text-primary-foreground rounded-xl py-2.5 text-sm font-medium hover:opacity-90 disabled:opacity-50 transition-all"
                                    >
                                        {processing ? t('weddings_index.creating') : t('weddings_index.create_wedding')}
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            )}

            {/* Plan-limit upgrade panel — shown when "New Wedding" is clicked at the cap */}
            {showUpgrade && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm animate-fade-in">
                    <div className="bg-card rounded-2xl w-full max-w-md shadow-xl shadow-foreground/10 border border-border animate-fade-up">
                        <div className="p-7 text-center">
                            <div className="w-12 h-12 rounded-xl bg-primary/[0.12] flex items-center justify-center mx-auto mb-5">
                                <svg className="w-6 h-6 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                                    <path d="M12 2 4 6v6c0 4.5 3.3 8.5 8 9 4.7-.5 8-4.5 8-9V6l-8-3z" />
                                </svg>
                            </div>
                            <p className="text-[10.5px] font-medium tracking-[0.22em] uppercase text-primary mb-2">
                                {t('billing.plan_limit_reached')}
                            </p>
                            <h2 className="font-serif text-2xl mb-2">
                                {weddingLimit === 1 ? t('weddings_index.upgrade_title_one') : t('weddings_index.upgrade_title_other', { count: weddingLimit ?? 0 })}
                            </h2>
                            <p className="text-[14px] text-muted-foreground leading-relaxed mb-7">
                                {t('weddings_index.upgrade_desc')}
                            </p>
                            <div className="flex gap-3">
                                <button
                                    type="button"
                                    onClick={() => setShowUpgrade(false)}
                                    className="flex-1 border border-border rounded-xl py-2.5 text-sm text-muted-foreground hover:text-foreground hover:bg-muted transition-all"
                                >
                                    {t('weddings_index.not_now')}
                                </button>
                                <Link
                                    href="/pricing"
                                    className="flex-1 bg-primary text-primary-foreground rounded-xl py-2.5 text-sm font-medium hover:opacity-90 transition-all flex items-center justify-center"
                                >
                                    {t('billing.view_plans')}
                                </Link>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </AppLayout>
    );
}
