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

interface FormShape {
    heading: string;
    body: string;
    image_url: string;
    theme: RsvpThemeKey;
    font_style: FontStyleKey;
    button_style: ButtonStyleKey;
}

interface IncomingSettings {
    heading: string | null;
    body: string | null;
    image_url: string | null;
    theme: RsvpThemeKey;
    font_style: FontStyleKey;
    button_style: ButtonStyleKey;
}

interface Props {
    wedding: { id: string; partner_a_name: string; partner_b_name: string };
    settings: IncomingSettings;
}

export default function RsvpSettings({ wedding, settings }: Props) {
    const t = useTranslator();
    const { data, setData, put, processing } = useForm<FormShape>({
        heading:      settings.heading      ?? '',
        body:         settings.body         ?? '',
        image_url:    settings.image_url    ?? '',
        theme:        settings.theme        ?? 'rose',
        font_style:   settings.font_style   ?? 'serif',
        button_style: settings.button_style ?? 'rounded',
    });

    const [uploading, setUploading] = useState(false);
    const fileRef = useRef<HTMLInputElement>(null);

    function handleSubmit(e: React.FormEvent) {
        e.preventDefault();
        put(`/weddings/${wedding.id}/rsvp-settings`, { preserveScroll: true });
    }

    async function handleUpload(e: React.ChangeEvent<HTMLInputElement>) {
        const file = e.target.files?.[0];
        if (!file) return;
        setUploading(true);
        try {
            const fd = new FormData();
            fd.append('image', file);
            const res = await fetch(`/weddings/${wedding.id}/rsvp-settings/upload`, {
                method: 'POST',
                headers: { 'X-CSRF-TOKEN': (document.querySelector('meta[name=csrf-token]') as HTMLMetaElement)?.content ?? '' },
                body: fd,
            });
            const json = await res.json();
            if (json.url) setData('image_url', json.url);
        } finally {
            setUploading(false);
            if (fileRef.current) fileRef.current.value = '';
        }
    }

    return (
        <AppLayout wedding={wedding as any}>
            <div className="max-w-6xl 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">
                        RSVP page
                    </p>
                    <h1 className="font-serif text-[2.2rem] sm:text-[2.6rem] tracking-[-0.022em] leading-[1.05]">
                        Customise your <em className="italic text-primary">{t('rsvp.title')}</em>.
                    </h1>
                    <p className="text-[14.5px] text-muted-foreground mt-2 max-w-xl leading-[1.6]">
                        Pick a theme, font and button shape. Changes apply to the public RSVP page guests see.
                    </p>
                </div>

                <div className="grid lg:grid-cols-[1fr_1.05fr] gap-10">
                    {/* ── Form ─────────────────────────────────────────────────── */}
                    <form onSubmit={handleSubmit} className="space-y-6">
                        <div>
                            <label className="block text-[12px] font-medium text-muted-foreground mb-1.5">
                                Heading
                            </label>
                            <input
                                type="text"
                                value={data.heading}
                                onChange={(e) => setData('heading', e.target.value)}
                                className="input"
                                placeholder={t('rsvp.heading_placeholder')}
                            />
                        </div>

                        <div>
                            <label className="block text-[12px] font-medium text-muted-foreground mb-1.5">
                                Body
                            </label>
                            <textarea
                                rows={4}
                                value={data.body}
                                onChange={(e) => setData('body', e.target.value)}
                                className="input"
                                placeholder={t('rsvp.message_placeholder')}
                            />
                        </div>

                        <div>
                            <label className="block text-[12px] font-medium text-muted-foreground mb-1.5">
                                Header image
                            </label>
                            {data.image_url ? (
                                <div className="relative w-full aspect-[16/9] rounded-xl overflow-hidden border border-border mb-2">
                                    <img src={data.image_url} alt="" className="absolute inset-0 w-full h-full object-cover" />
                                    <button
                                        type="button"
                                        onClick={() => setData('image_url', '')}
                                        className="absolute top-2 right-2 bg-foreground/85 text-background text-[11px] font-medium px-2.5 py-1 rounded-full hover:bg-foreground transition-colors"
                                    >
                                        Remove
                                    </button>
                                </div>
                            ) : null}
                            <input
                                ref={fileRef}
                                type="file"
                                accept="image/*"
                                onChange={handleUpload}
                                disabled={uploading}
                                className="w-full text-[13.5px] file:mr-3 file:px-3 file:py-2 file:rounded-lg file:border file:border-border file:bg-card file:text-foreground file:text-[12.5px] file:cursor-pointer file:hover:bg-foreground/[0.04]"
                            />
                            {uploading && <p className="text-[11px] text-muted-foreground mt-1.5">{t('common.uploading')}</p>}
                        </div>

                        {/* Theme picker */}
                        <div>
                            <label className="block text-[12px] font-medium text-muted-foreground mb-2">
                                Colour theme
                            </label>
                            <div className="grid grid-cols-5 gap-2">
                                {(Object.keys(RSVP_THEMES) as RsvpThemeKey[]).map((key) => {
                                    const t = RSVP_THEMES[key];
                                    const active = data.theme === key;
                                    return (
                                        <button
                                            key={key}
                                            type="button"
                                            onClick={() => setData('theme', key)}
                                            className={`flex flex-col items-center gap-1.5 p-2 rounded-xl border transition-all ${
                                                active
                                                    ? 'border-foreground shadow-[0_8px_20px_-12px_rgba(0,0,0,0.35)]'
                                                    : 'border-border hover:border-foreground/30'
                                            }`}
                                            title={t.label}
                                        >
                                            <span
                                                className="w-7 h-7 rounded-full border border-border"
                                                style={{ backgroundColor: t.swatch }}
                                            />
                                            <span className="text-[10.5px] tracking-tight text-foreground/85">{t.label}</span>
                                        </button>
                                    );
                                })}
                            </div>
                        </div>

                        {/* Font picker */}
                        <div>
                            <label className="block text-[12px] font-medium text-muted-foreground mb-2">
                                Font style
                            </label>
                            <div className="grid grid-cols-2 gap-2">
                                {(Object.keys(FONT_STYLES) as FontStyleKey[]).map((key) => {
                                    const active = data.font_style === key;
                                    return (
                                        <button
                                            key={key}
                                            type="button"
                                            onClick={() => setData('font_style', key)}
                                            className={`px-4 py-3 rounded-xl border text-[14px] transition-all ${
                                                active
                                                    ? 'border-foreground bg-foreground/[0.04]'
                                                    : 'border-border hover:border-foreground/30'
                                            }`}
                                            style={{ fontFamily: FONT_STYLES[key].family }}
                                        >
                                            {FONT_STYLES[key].label}
                                        </button>
                                    );
                                })}
                            </div>
                        </div>

                        {/* Button picker */}
                        <div>
                            <label className="block text-[12px] font-medium text-muted-foreground mb-2">
                                Button shape
                            </label>
                            <div className="grid grid-cols-3 gap-2">
                                {(Object.keys(BUTTON_STYLES) as ButtonStyleKey[]).map((key) => {
                                    const active = data.button_style === key;
                                    return (
                                        <button
                                            key={key}
                                            type="button"
                                            onClick={() => setData('button_style', key)}
                                            className={`px-3 py-2.5 border text-[13px] transition-all ${
                                                active
                                                    ? 'border-foreground bg-foreground/[0.04]'
                                                    : 'border-border hover:border-foreground/30'
                                            }`}
                                            style={{ borderRadius: BUTTON_STYLES[key].radius }}
                                        >
                                            {BUTTON_STYLES[key].label}
                                        </button>
                                    );
                                })}
                            </div>
                        </div>

                        <div className="pt-4">
                            <button type="submit" disabled={processing} className="btn-charcoal w-full sm:w-auto">
                                {processing ? 'Saving…' : 'Save settings'}
                            </button>
                        </div>
                    </form>

                    {/* ── Live preview ─────────────────────────────────────────── */}
                    <div className="lg:sticky lg:top-6 self-start">
                        <p className="text-[11px] font-medium tracking-[0.22em] uppercase text-primary mb-3">
                            Live preview
                        </p>
                        <RsvpPreview
                            heading={data.heading || "You're Invited"}
                            body={data.body || 'Please let us know if you can make it.'}
                            imageUrl={data.image_url}
                            theme={data.theme}
                            fontStyle={data.font_style}
                            buttonStyle={data.button_style}
                            coupleNames={`${wedding.partner_a_name} & ${wedding.partner_b_name}`}
                        />
                    </div>
                </div>
            </div>
        </AppLayout>
    );
}

function RsvpPreview({
    heading,
    body,
    imageUrl,
    theme,
    fontStyle,
    buttonStyle,
    coupleNames,
}: {
    heading: string;
    body: string;
    imageUrl: string;
    theme: RsvpThemeKey;
    fontStyle: FontStyleKey;
    buttonStyle: ButtonStyleKey;
    coupleNames: string;
}) {
    const t = RSVP_THEMES[theme];
    const font = FONT_STYLES[fontStyle];
    const btn = BUTTON_STYLES[buttonStyle];

    return (
        <div
            className="rounded-2xl overflow-hidden border"
            style={{ backgroundColor: t.bg, borderColor: t.cardBorder, fontFamily: font.family }}
        >
            <div
                className="px-5 py-3 border-b flex items-center justify-between"
                style={{ borderColor: t.cardBorder, backgroundColor: t.stripBg }}
            >
                <span
                    className="text-[12.5px] italic"
                    style={{ fontFamily: FONT_STYLES.serif.family, color: t.textPrimary }}
                >
                    {coupleNames}
                </span>
                <span
                    className="text-[10px] uppercase tracking-[0.22em]"
                    style={{ color: t.accent }}
                >
                    RSVP
                </span>
            </div>

            <div className="p-6">
                {imageUrl && (
                    <div className="rounded-xl overflow-hidden mb-5 aspect-[16/9]">
                        <img src={imageUrl} alt="" className="w-full h-full object-cover" />
                    </div>
                )}

                <div
                    className="rounded-2xl p-6 sm:p-7 border"
                    style={{ backgroundColor: t.cardBg, borderColor: t.cardBorder }}
                >
                    <p
                        className="text-[10.5px] font-medium uppercase tracking-[0.22em] mb-3 text-center"
                        style={{ color: t.accent }}
                    >
                        You're invited
                    </p>
                    <h3
                        className="text-[1.8rem] leading-tight tracking-tight text-center mb-3"
                        style={{ color: t.textPrimary }}
                    >
                        {heading}
                    </h3>
                    <p
                        className="text-[13px] leading-[1.65] text-center mb-6"
                        style={{ color: t.textMuted }}
                    >
                        {body}
                    </p>

                    <p className="text-[12px] mb-2.5" style={{ color: t.textPrimary }}>
                        Hi guest,
                    </p>

                    <div className="grid grid-cols-3 gap-2 mb-4">
                        {['Yes', 'No', 'Maybe'].map((label, i) => (
                            <button
                                key={label}
                                type="button"
                                disabled
                                className="py-2.5 text-[12px] font-medium border transition-all"
                                style={{
                                    borderRadius: btn.radius,
                                    backgroundColor: i === 0 ? t.accent : 'transparent',
                                    color: i === 0 ? '#ffffff' : t.textPrimary,
                                    borderColor: i === 0 ? t.accent : t.selectBorder,
                                }}
                            >
                                {label}
                            </button>
                        ))}
                    </div>

                    <button
                        type="button"
                        disabled
                        className="w-full py-3 text-[13px] font-medium"
                        style={{
                            borderRadius: btn.radius,
                            backgroundColor: t.accent,
                            color: '#ffffff',
                        }}
                    >
                        Submit RSVP
                    </button>
                </div>

                <p
                    className="text-center text-[10.5px] tracking-wide mt-5"
                    style={{ color: t.textMuted }}
                >
                    Powered by <span style={{ fontFamily: FONT_STYLES.serif.family, fontStyle: 'italic' }}>WedFlow</span>
                </p>
            </div>
        </div>
    );
}
