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

interface Props {
    wedding: any;
    website?: {
        id: string;
        slug: string;
        published: boolean;
        theme: string;
        sections?: any[];
    };
    premiumThemes?: string[];
    canPremiumThemes?: boolean;
}

const THEMES = ['lumiere', 'marquee', 'botanica', 'soiree', 'rose', 'garden', 'minimal', 'luxe', 'coastal'];

// Visual tokens for the in-editor theme preview cards. The premium entries
// mirror their actual theme (palette + display font); the palette themes use a
// neutral serif. `upper` renders the names in caps to hint the layout.
const THEME_PREVIEWS: Record<string, { label: string; bg: string; ink: string; accent: string; font: string; upper?: boolean; tag: string }> = {
    lumiere:  { label: 'Lumière',  bg: '#FBF7F0', ink: '#2B2723', accent: '#B08D57', font: "'Cormorant Garamond', serif", tag: 'Romantic · ivory' },
    marquee:  { label: 'Marquee',  bg: '#F4F0E8', ink: '#181410', accent: '#8C2F39', font: "'Fraunces', serif", upper: true, tag: 'Bold · modern' },
    botanica: { label: 'Botanica', bg: '#F2F1E6', ink: '#2C322A', accent: '#6E8B6A', font: "'Gilda Display', serif", tag: 'Garden · organic' },
    soiree:   { label: 'Soirée',   bg: '#14110E', ink: '#EFE7D8', accent: '#C6A35A', font: "'Cinzel', serif", upper: true, tag: 'Deco · evening' },
    rose:     { label: 'Rose',     bg: '#FFF1F2', ink: '#881337', accent: '#E11D48', font: 'Georgia, serif', tag: 'Soft blush' },
    garden:   { label: 'Garden',   bg: '#F0FDF4', ink: '#14532D', accent: '#16A34A', font: 'Georgia, serif', tag: 'Fresh green' },
    minimal:  { label: 'Minimal',  bg: '#FFFFFF', ink: '#111827', accent: '#111827', font: 'Georgia, serif', tag: 'Clean mono' },
    luxe:     { label: 'Luxe',     bg: '#1C1917', ink: '#F5F5F4', accent: '#F59E0B', font: 'Georgia, serif', upper: true, tag: 'Dark amber' },
    coastal:  { label: 'Coastal',  bg: '#F0F9FF', ink: '#0C4A6E', accent: '#0284C7', font: 'Georgia, serif', tag: 'Sea blue' },
};

// #24: 'details' heading no longer auto-populates with "Ceremony & Reception"
// — if the couple doesn't change it, that string would be pushed publicly even
// if their ceremony and reception aren't both happening. Empty default = no
// surprise text on the public site.
const DEFAULT_SECTIONS = [
    { id: 'hero', label: 'Hero', visible: true, content: { heading: '', subheading: '', backgroundUrl: '' } },
    { id: 'story', label: 'Our Story', visible: true, content: { heading: 'Our Story', body: '' } },
    { id: 'details', label: 'Event Details', visible: true, content: { heading: '', ceremonyTime: '', ceremonyVenue: '', receptionTime: '', receptionVenue: '' } },
    { id: 'timeline', label: 'Day-of Timeline', visible: false, content: { heading: '' } },
    { id: 'rsvp', label: 'RSVP', visible: false, content: { heading: '', body: '' } },
    { id: 'registry', label: 'Registry', visible: false, content: { heading: '', body: '' } },
    { id: 'faq', label: 'FAQ', visible: false, content: { heading: '', body: '' } },
];

// Hover/subtitle text per section so couples know what each one does without
// having to publish and check the public site to find out.
const SECTION_HELP: Record<string, string> = {
    hero:     'Full-width landing image + couple names. The first thing guests see when they open the site.',
    story:    'How you met, the proposal, anything you want to share — optional.',
    details:  'Ceremony and reception times + venues. Pulled from the wedding\'s main details by default.',
    timeline: 'Hour-by-hour schedule of the wedding day. Pulled live from your Timeline tab — edit it there.',
    rsvp:     'Adds a button on your public site that points guests to /rsvp/{token}. The RSVP form itself is configured in Guests → RSVP Settings.',
    registry: 'Links to your gift registries (Amazon, Crate & Barrel, etc.). One link per line.',
    faq:      'Common questions: dress code, parking, accommodation suggestions, kid-friendly?',
};

export default function Website({ wedding, website, premiumThemes = [], canPremiumThemes = false }: Props) {
    const t = useTranslator();
    const weddingDateLabel = wedding?.wedding_date
        ? new Date(wedding.wedding_date).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })
        : t('wsite.the_day');
    const [activeSection, setActiveSection] = useState('hero');
    const sections = website?.sections ?? DEFAULT_SECTIONS;
    const [sectionData, setSectionData] = useState<any[]>(sections);
    // Which photo field is mid-upload, keyed `${sectionId}.${key}`.
    const [uploadingField, setUploadingField] = useState<string | null>(null);

    const form = useForm({
        published: website?.published ?? false,
        theme: website?.theme ?? 'rose',
        sections: sectionData,
    });

    function toggleSection(id: string) {
        const updated = sectionData.map(s => s.id === id ? { ...s, visible: !s.visible } : s);
        setSectionData(updated);
        form.setData('sections', updated);
    }

    function updateSection(id: string, key: string, value: string) {
        const updated = sectionData.map(s => s.id === id ? { ...s, content: { ...s.content, [key]: value } } : s);
        setSectionData(updated);
        form.setData('sections', updated);
    }

    function save() {
        form.put(`/weddings/${wedding.id}/website`, { preserveScroll: true });
    }

    // #17: photo upload for any *Url field. Hits the website/upload endpoint,
    // gets back a /storage/... URL, writes it into the section content.
    async function uploadPhoto(sectionId: string, key: string, file: File) {
        const fd = new FormData();
        fd.append('image', file);
        const csrf = (document.querySelector('meta[name=csrf-token]') as HTMLMetaElement)?.content ?? '';
        setUploadingField(`${sectionId}.${key}`);
        try {
            const res = await fetch(`/weddings/${wedding.id}/website/upload`, {
                method: 'POST',
                headers: { 'X-CSRF-TOKEN': csrf, 'Accept': 'application/json' },
                body: fd,
            });
            if (!res.ok) throw new Error('Upload failed');
            const { url } = await res.json();
            updateSection(sectionId, key, url);
        } catch (e) {
            alert(t('website.upload_failed'));
        } finally {
            setUploadingField(null);
        }
    }

    const activeS = sectionData.find(s => s.id === activeSection);
    const publicUrl = website?.published ? `${window.location.origin}/w/${website.slug}` : null;

    return (
        <AppLayout wedding={wedding}>
            <div className="max-w-6xl mx-auto px-6 py-8">
                <div className="flex items-center justify-between mb-8">
                    <div>
                        <h1 className="font-serif text-3xl">{t('website.title')}</h1>
                        {publicUrl && (
                            <a href={publicUrl} target="_blank" rel="noreferrer" className="text-sm text-primary hover:underline">
                                {t('website.view_live')} →
                            </a>
                        )}
                    </div>
                    <div className="flex items-center gap-3">
                        <label className="flex items-center gap-2 text-sm">
                            <input type="checkbox" checked={form.data.published} onChange={e => form.setData('published', e.target.checked)} />
                            {t('website.published')}
                        </label>
                        <button onClick={save} disabled={form.processing} className="bg-primary text-primary-foreground px-4 py-2 rounded-lg text-sm">
                            {form.processing ? t('common.saving') : t('common.save')}
                        </button>
                    </div>
                </div>

                <div className="grid grid-cols-4 gap-6">
                    {/* Left panel */}
                    <div className="space-y-4">
                        <div>
                            {/* Display fonts for the live preview cards (hoisted + deduped by React 19). */}
                            <link rel="preconnect" href="https://fonts.googleapis.com" />
                            <link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
                            <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@500&family=Fraunces:wght@600;900&family=Gilda+Display&family=Cinzel:wght@600&display=swap" />
                            <label className="block text-sm font-medium mb-2">{t('website.theme')}</label>
                            <div className="grid grid-cols-2 gap-2">
                                {THEMES.map(themeName => {
                                    const meta = THEME_PREVIEWS[themeName];
                                    if (!meta) return null;
                                    const isPremium = premiumThemes.includes(themeName);
                                    const locked = isPremium && !canPremiumThemes;
                                    const active = form.data.theme === themeName;
                                    return (
                                        <button
                                            key={themeName}
                                            type="button"
                                            onClick={() => locked ? router.visit('/pricing') : form.setData('theme', themeName)}
                                            title={locked ? t('website.premium_theme_hint') : meta.label}
                                            className={`group relative text-left rounded-xl overflow-hidden border transition-all ${active ? 'border-primary ring-2 ring-primary/30' : 'border-border hover:border-foreground/30'}`}
                                        >
                                            {/* Mini website preview */}
                                            <div
                                                className="relative aspect-[4/3] flex flex-col items-center justify-center px-2 text-center overflow-hidden"
                                                style={{ background: meta.bg, color: meta.ink }}
                                            >
                                                <span className="text-[6px] tracking-[0.18em] uppercase mb-1" style={{ color: meta.accent }}>
                                                    {t('wsite.eyebrow_wedding')}
                                                </span>
                                                <span
                                                    className="leading-[1.05] line-clamp-2"
                                                    style={{ fontFamily: meta.font, fontSize: '13px', textTransform: meta.upper ? 'uppercase' : 'none', letterSpacing: meta.upper ? '0.03em' : 0 }}
                                                >
                                                    {(wedding?.partner_a_name || 'Alex')} <span style={{ color: meta.accent, fontStyle: 'italic' }}>&amp;</span> {(wedding?.partner_b_name || 'Sam')}
                                                </span>
                                                <span className="block w-5 h-px my-1.5" style={{ background: meta.accent, opacity: 0.7 }} />
                                                <span className="text-[6.5px] tracking-[0.16em] uppercase" style={{ opacity: 0.6 }}>
                                                    {weddingDateLabel}
                                                </span>
                                                {locked && (
                                                    <span className="absolute inset-0 flex items-center justify-center bg-black/35 backdrop-blur-[1px]">
                                                        <svg className="w-4 h-4 text-white" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6">
                                                            <rect x="3.5" y="7" width="9" height="6.5" rx="1.4" /><path d="M5.5 7V5a2.5 2.5 0 0 1 5 0v2" />
                                                        </svg>
                                                    </span>
                                                )}
                                            </div>
                                            {/* Label row */}
                                            <div className={`flex items-center justify-between gap-1 px-2 py-1.5 ${active ? 'bg-primary/10' : 'bg-card'}`}>
                                                <span className="text-[11px] font-medium truncate">{meta.label}</span>
                                                {isPremium && (
                                                    <span className="shrink-0 text-[8px] font-semibold uppercase tracking-wide px-1 py-0.5 rounded bg-primary/15 text-primary">
                                                        {t('website.premium_badge')}
                                                    </span>
                                                )}
                                            </div>
                                        </button>
                                    );
                                })}
                            </div>
                        </div>
                        <div>
                            <label className="block text-sm font-medium mb-2">{t('website.sections')}</label>
                            <div className="space-y-1">
                                {sectionData.map(s => (
                                    <div key={s.id} className="flex items-center justify-between">
                                        <button
                                            onClick={() => setActiveSection(s.id)}
                                            title={SECTION_HELP[s.id]}
                                            className={`flex-1 text-left px-3 py-1.5 rounded-lg text-sm ${activeSection === s.id ? 'bg-primary/10 text-primary font-medium' : 'hover:bg-muted'}`}
                                        >
                                            {s.label}
                                        </button>
                                        <button
                                            onClick={() => toggleSection(s.id)}
                                            className={`text-xs ml-2 ${s.visible ? 'text-green-600' : 'text-muted-foreground'}`}
                                        >
                                            {s.visible ? '●' : '○'}
                                        </button>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>

                    {/* Editor */}
                    <div className="col-span-3 bg-card border border-border rounded-xl p-6">
                        {activeS && (
                            <div>
                                <h2 className="font-semibold mb-1">{activeS.label}</h2>
                                {SECTION_HELP[activeS.id] && (
                                    <p className="text-xs text-muted-foreground mb-4">{SECTION_HELP[activeS.id]}</p>
                                )}
                                <div className="space-y-3">
                                    {Object.entries(activeS.content).map(([key, value]) => {
                                        const isPhotoField = key.endsWith('Url') || key.endsWith('URL');
                                        // Photo fields always keep the input + upload control, even when the
                                        // pasted URL is long — otherwise they'd flip to a textarea and the
                                        // upload button would disappear.
                                        const isLongText = !isPhotoField && (String(value).length > 80 || key === 'body');
                                        return (
                                            <div key={key}>
                                                <label className="block text-sm font-medium mb-1 capitalize">{key.replace(/([A-Z])/g, ' $1')}</label>
                                                {isLongText ? (
                                                    <textarea
                                                        value={String(value)}
                                                        onChange={e => updateSection(activeS.id, key, e.target.value)}
                                                        className="w-full border border-border rounded-lg px-3 py-2 text-sm"
                                                        rows={4}
                                                    />
                                                ) : (
                                                    <>
                                                        <input
                                                            type="text"
                                                            value={String(value)}
                                                            onChange={e => updateSection(activeS.id, key, e.target.value)}
                                                            placeholder={isPhotoField ? t('website.image_url_placeholder') : ''}
                                                            className="w-full border border-border rounded-lg px-3 py-2 text-sm"
                                                        />
                                                        {isPhotoField && (
                                                            <div className="mt-2 flex items-center gap-3">
                                                                {String(value) && (
                                                                    <img
                                                                        src={String(value)}
                                                                        alt=""
                                                                        className="w-16 h-16 rounded-lg object-cover border border-border bg-muted shrink-0"
                                                                    />
                                                                )}
                                                                <label className={`inline-flex items-center gap-1.5 border border-border rounded-lg px-3 py-1.5 text-xs cursor-pointer hover:border-foreground/30 transition-colors ${uploadingField === `${activeS.id}.${key}` ? 'opacity-60 pointer-events-none' : ''}`}>
                                                                    <UploadIcon className="w-3.5 h-3.5" />
                                                                    {uploadingField === `${activeS.id}.${key}`
                                                                        ? t('common.uploading')
                                                                        : (String(value) ? t('website.replace_image') : t('website.upload_photo'))}
                                                                    <input
                                                                        type="file"
                                                                        accept="image/jpeg,image/png,image/webp,image/gif"
                                                                        className="hidden"
                                                                        onChange={(e) => {
                                                                            const file = e.target.files?.[0];
                                                                            if (file) uploadPhoto(activeS.id, key, file);
                                                                            e.target.value = '';
                                                                        }}
                                                                    />
                                                                </label>
                                                                {String(value) && (
                                                                    <button
                                                                        type="button"
                                                                        onClick={() => updateSection(activeS.id, key, '')}
                                                                        className="text-xs text-red-500 hover:underline"
                                                                    >
                                                                        {t('common.remove')}
                                                                    </button>
                                                                )}
                                                            </div>
                                                        )}
                                                    </>
                                                )}
                                            </div>
                                        );
                                    })}
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </AppLayout>
    );
}

function UploadIcon({ className = '' }: { className?: string }) {
    return (
        <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
            <path d="M17 8l-5-5-5 5" />
            <path d="M12 3v12" />
        </svg>
    );
}
