import { useForm, Head } from '@inertiajs/react';
import {
    RSVP_THEMES, FONT_STYLES, BUTTON_STYLES,
    type RsvpThemeKey, type FontStyleKey, type ButtonStyleKey,
} from '@/lib/rsvp-themes';
import { useTranslator, useLocale } from '@/lib/i18n';

interface Props {
    guest: {
        id: string;
        first_name: string;
        last_name?: string;
        party_count: number;
        rsvp_status: string;
        meal_preference?: string;
        dietary_notes?: string;
    };
    wedding: {
        partner_a_name: string;
        partner_b_name: string;
        wedding_date?: string;
        venue_name?: string;
        venue_city?: string;
        venue_country?: string;
    };
    settings?: {
        heading?: string;
        body?: string;
        image_url?: string;
        theme?: string;
        font_style?: string;
        button_style?: string;
    };
}

export default function RsvpShow({ guest, wedding, settings }: Props) {
    const tr = useTranslator();
    const locale = useLocale();
    const { data, setData, post, processing, wasSuccessful } = useForm({
        rsvp_status: guest.rsvp_status,
        meal_preference: guest.meal_preference ?? '',
        dietary_notes: guest.dietary_notes ?? '',
    });

    // Theme resolution with sane defaults.
    const themeKey: RsvpThemeKey = (settings?.theme as RsvpThemeKey | undefined) ?? 'rose';
    const fontKey:  FontStyleKey = (settings?.font_style as FontStyleKey | undefined) ?? 'serif';
    const btnKey:   ButtonStyleKey = (settings?.button_style as ButtonStyleKey | undefined) ?? 'rounded';

    const t = RSVP_THEMES[themeKey] ?? RSVP_THEMES.rose;
    const font = FONT_STYLES[fontKey] ?? FONT_STYLES.serif;
    const btn = BUTTON_STYLES[btnKey] ?? BUTTON_STYLES.rounded;

    const heading = settings?.heading ?? tr('rsvp.heading_placeholder');
    const body = settings?.body ?? tr('rsvp.message_placeholder');
    const coupleNames = `${wedding.partner_a_name} & ${wedding.partner_b_name}`;

    function handleSubmit(e: React.FormEvent) {
        e.preventDefault();
        post('', { preserveScroll: true });
    }

    const dateStr = wedding.wedding_date
        ? new Date(wedding.wedding_date).toLocaleDateString(locale === 'fr' ? 'fr-FR' : 'en-US', { month: 'long', day: 'numeric', year: 'numeric' })
        : null;
    const venue = [wedding.venue_name, wedding.venue_city, wedding.venue_country].filter(Boolean).join(', ');

    // Resolve OG image to an absolute URL so WhatsApp/Facebook can fetch it.
    const ogImage = settings?.image_url
        ? (settings.image_url.startsWith('http')
            ? settings.image_url
            : `${typeof window !== 'undefined' ? window.location.origin : ''}${settings.image_url}`)
        : null;

    const ogTitle = `${heading} — ${coupleNames}`;
    const ogDesc = body;

    return (
        <>
            <Head>
                <title>{`${ogTitle}`}</title>
                <meta name="description" content={ogDesc} />
                <meta property="og:title" content={ogTitle} />
                <meta property="og:description" content={ogDesc} />
                <meta property="og:type" content="website" />
                {ogImage && <meta property="og:image" content={ogImage} />}
                <meta name="twitter:card" content="summary_large_image" />
                <meta name="twitter:title" content={ogTitle} />
                <meta name="twitter:description" content={ogDesc} />
                {ogImage && <meta name="twitter:image" content={ogImage} />}
            </Head>

            <div
                className="min-h-screen flex flex-col"
                style={{ backgroundColor: t.bg, color: t.textPrimary, fontFamily: font.family }}
            >
                {/* Top strip */}
                <header
                    className="border-b backdrop-blur-md"
                    style={{ backgroundColor: t.stripBg, borderColor: t.cardBorder }}
                >
                    <div className="max-w-2xl mx-auto px-4 sm:px-6 h-14 flex items-center justify-between">
                        <p
                            className="text-[1.1rem] italic tracking-tight"
                            style={{ fontFamily: FONT_STYLES.serif.family, color: t.textPrimary }}
                        >
                            {wedding.partner_a_name}{' '}
                            <span style={{ color: t.textMuted }}>&amp;</span>{' '}
                            {wedding.partner_b_name}
                        </p>
                        <span
                            className="text-[10.5px] tracking-[0.22em] uppercase"
                            style={{ color: t.accent }}
                        >
                            RSVP
                        </span>
                    </div>
                </header>

                <main className="flex-1 flex items-center justify-center px-4 py-12 sm:py-16">
                    <div className="w-full max-w-md">
                        {settings?.image_url && (
                            <div
                                className="w-full aspect-[16/9] rounded-2xl overflow-hidden mb-8 border"
                                style={{ borderColor: t.cardBorder }}
                            >
                                <img src={settings.image_url} alt="" className="w-full h-full object-cover" />
                            </div>
                        )}

                        <div
                            className="rounded-3xl p-7 sm:p-9 border"
                            style={{ backgroundColor: t.cardBg, borderColor: t.cardBorder }}
                        >
                            <div className="text-center mb-7">
                                <p
                                    className="text-[11px] font-medium tracking-[0.22em] uppercase mb-3"
                                    style={{ color: t.accent }}
                                >
                                    {tr('rsvp.eyebrow_invited')}
                                </p>
                                <h1
                                    className="text-[2.2rem] sm:text-[2.6rem] tracking-[-0.022em] leading-[1.05] mb-3"
                                    style={{ color: t.textPrimary }}
                                >
                                    {heading}
                                </h1>
                                {dateStr && (
                                    <p className="text-[14px]" style={{ color: t.textMuted }}>{dateStr}</p>
                                )}
                                {venue && (
                                    <p className="text-[13px] mt-0.5" style={{ color: t.textMuted }}>{venue}</p>
                                )}
                                {body && (
                                    <p className="mt-5 text-[14.5px] leading-[1.65]" style={{ color: t.textPrimary, opacity: 0.85 }}>
                                        {body}
                                    </p>
                                )}
                            </div>

                            {wasSuccessful ? (
                                <div className="text-center py-6">
                                    <p
                                        className="text-[11px] font-medium tracking-[0.22em] uppercase mb-3"
                                        style={{ color: t.accent }}
                                    >
                                        {tr('rsvp.thank_you')}
                                    </p>
                                    <p
                                        className="text-[1.75rem] tracking-[-0.022em] leading-[1.1] mb-3"
                                        style={{ color: t.textPrimary }}
                                    >
                                        {tr('rsvp.thank_you_prefix')}{' '}
                                        <span style={{ fontStyle: 'italic', color: t.accent }}>{guest.first_name}</span>.
                                    </p>
                                    <p className="text-[14px] leading-[1.6]" style={{ color: t.textMuted }}>
                                        {data.rsvp_status === 'confirmed'
                                            ? tr('rsvp.confirmed_msg')
                                            : tr('rsvp.declined_msg')}
                                    </p>
                                </div>
                            ) : (
                                <form onSubmit={handleSubmit} className="space-y-5">
                                    <p className="text-[14.5px] font-medium" style={{ color: t.textPrimary }}>
                                        {tr('rsvp.hi', { name: guest.first_name })}
                                    </p>

                                    <div>
                                        <label
                                            className="block text-[12px] font-medium mb-2"
                                            style={{ color: t.textMuted }}
                                        >
                                            {tr('rsvp.attending_q')}
                                        </label>
                                        <div className="grid grid-cols-3 gap-2">
                                            {(['confirmed', 'declined', 'maybe'] as const).map((status) => {
                                                const active = data.rsvp_status === status;
                                                return (
                                                    <button
                                                        key={status}
                                                        type="button"
                                                        onClick={() => setData('rsvp_status', status)}
                                                        className="py-2.5 text-[13px] font-medium capitalize transition-all border"
                                                        style={{
                                                            borderRadius: btn.radius,
                                                            backgroundColor: active ? t.accent : 'transparent',
                                                            color: active ? '#ffffff' : t.textPrimary,
                                                            borderColor: active ? t.accent : t.selectBorder,
                                                        }}
                                                    >
                                                        {status === 'confirmed' ? tr('common.yes') : status === 'declined' ? tr('common.no') : tr('rsvp.maybe')}
                                                    </button>
                                                );
                                            })}
                                        </div>
                                    </div>

                                    {data.rsvp_status === 'confirmed' && (
                                        <>
                                            <div>
                                                <label
                                                    className="block text-[12px] font-medium mb-1.5"
                                                    style={{ color: t.textMuted }}
                                                >
                                                    {tr('guests.meal_preference')}
                                                </label>
                                                <select
                                                    value={data.meal_preference}
                                                    onChange={(e) => setData('meal_preference', e.target.value)}
                                                    className="w-full px-3.5 py-3 text-[14px] outline-none transition-all border"
                                                    style={{
                                                        borderRadius: btn.radius,
                                                        backgroundColor: t.cardBg,
                                                        color: t.textPrimary,
                                                        borderColor: t.selectBorder,
                                                    }}
                                                >
                                                    <option value="">{tr('rsvp.meal_none')}</option>
                                                    <option value="chicken">{tr('rsvp.meal_chicken')}</option>
                                                    <option value="beef">{tr('rsvp.meal_beef')}</option>
                                                    <option value="fish">{tr('rsvp.meal_fish')}</option>
                                                    <option value="vegetarian">{tr('rsvp.meal_vegetarian')}</option>
                                                    <option value="vegan">{tr('rsvp.meal_vegan')}</option>
                                                </select>
                                            </div>
                                            <div>
                                                <label
                                                    className="block text-[12px] font-medium mb-1.5"
                                                    style={{ color: t.textMuted }}
                                                >
                                                    {tr('rsvp.dietary_label')}
                                                </label>
                                                <textarea
                                                    value={data.dietary_notes}
                                                    onChange={(e) => setData('dietary_notes', e.target.value)}
                                                    className="w-full px-3.5 py-3 text-[14px] outline-none transition-all border"
                                                    style={{
                                                        borderRadius: btn.radius,
                                                        backgroundColor: t.cardBg,
                                                        color: t.textPrimary,
                                                        borderColor: t.selectBorder,
                                                    }}
                                                    rows={2}
                                                    placeholder={tr('rsvp.dietary_placeholder')}
                                                />
                                            </div>
                                        </>
                                    )}

                                    <button
                                        type="submit"
                                        disabled={processing}
                                        className="w-full py-3 text-[14px] font-medium transition-all disabled:opacity-60"
                                        style={{
                                            borderRadius: btn.radius,
                                            backgroundColor: t.accent,
                                            color: '#ffffff',
                                        }}
                                    >
                                        {processing ? tr('rsvp.submitting') : tr('rsvp.submit_rsvp')}
                                    </button>
                                </form>
                            )}
                        </div>
                    </div>
                </main>

                <footer
                    className="border-t py-5"
                    style={{ borderColor: t.cardBorder }}
                >
                    <p
                        className="text-center text-[11.5px] tracking-wide"
                        style={{ color: t.textMuted }}
                    >
                        {tr('rsvp.powered_by')}{' '}
                        <span style={{ fontFamily: FONT_STYLES.serif.family, fontStyle: 'italic', color: t.textPrimary }}>
                            WedFlow
                        </span>
                    </p>
                </footer>
            </div>
        </>
    );
}
