import { useEffect, useRef, useState } from 'react';
import { FloorPlanView, type PublicFloorPlan } from '@/components/floor-plan-view';
import { useTranslator } from '@/lib/i18n';

interface Props {
    share: {
        id: string;
        slug: string;
        title?: string;
        message?: string;
        is_active: boolean;
    };
    wedding: {
        partner_a_name: string;
        partner_b_name: string;
    };
}

interface SeatMatch {
    person_name: string;
    table_name: string | null;
}

export default function ShareShow({ share, wedding }: Props) {
    const t = useTranslator();
    const [uploaderName, setUploaderName] = useState('');
    const [files, setFiles] = useState<File[]>([]);
    const [uploading, setUploading] = useState(false);
    const [uploaded, setUploaded] = useState(0);
    const [photos, setPhotos] = useState<any[]>([]);
    const [photosLoaded, setPhotosLoaded] = useState(false);
    const [successCount, setSuccessCount] = useState<number | null>(null);
    const fileRef = useRef<HTMLInputElement>(null);

    // Seat finder
    const [seatQuery, setSeatQuery] = useState('');
    const [seatMatches, setSeatMatches] = useState<SeatMatch[] | null>(null);
    const [seatSearching, setSeatSearching] = useState(false);
    const [floorPlan, setFloorPlan] = useState<PublicFloorPlan | null>(null);

    useEffect(() => {
        if (!share.is_active) return;
        fetch(`/share/${share.slug}/floorplan`)
            .then((r) => r.ok ? r.json() : null)
            .then((data) => { if (data) setFloorPlan(data); })
            .catch(() => {});
    }, [share.slug, share.is_active]);

    async function handleSeatSearch(e: React.FormEvent) {
        e.preventDefault();
        if (!seatQuery.trim()) {
            setSeatMatches(null);
            return;
        }
        setSeatSearching(true);
        try {
            const res = await fetch(`/share/${share.slug}/seats?q=${encodeURIComponent(seatQuery.trim())}`);
            const data: SeatMatch[] = await res.json();
            setSeatMatches(data);
        } finally {
            setSeatSearching(false);
        }
    }

    const singleMatch = seatMatches && seatMatches.length === 1 ? seatMatches[0] : null;
    const highlightTable = singleMatch?.table_name ?? null;

    async function loadPhotos() {
        const res = await fetch(`/share/${share.slug}/photos`);
        const data = await res.json();
        setPhotos(data);
        setPhotosLoaded(true);
    }

    async function handleUpload(e: React.FormEvent) {
        e.preventDefault();
        if (!files.length) return;

        setUploading(true);
        setSuccessCount(null);
        let done = 0;

        for (const file of files) {
            const fd = new FormData();
            fd.append('file', file);
            if (uploaderName) fd.append('uploader_name', uploaderName);

            await fetch(`/share/${share.slug}/upload`, {
                method: 'POST',
                headers: { 'X-CSRF-TOKEN': (document.querySelector('meta[name=csrf-token]') as HTMLMetaElement)?.content ?? '' },
                body: fd,
            });
            done++;
            setUploaded(done);
        }

        setUploading(false);
        setSuccessCount(done);
        setFiles([]);
        setUploaded(0);
        if (fileRef.current) fileRef.current.value = '';
    }

    if (!share.is_active) {
        return (
            <div className="atelier-light min-h-screen bg-background flex items-center justify-center px-4">
                <div className="text-center max-w-md">
                    <div className="w-14 h-14 rounded-none border border-border mx-auto mb-7 flex items-center justify-center">
                        <CameraIcon className="w-6 h-6 text-foreground/55" />
                    </div>
                    <p className="text-[10.5px] tracking-[0.34em] uppercase text-primary mb-4 flex items-center gap-3 justify-center">
                        <span className="inline-block w-10 h-px bg-primary" />
                        {t('share.paused')}
                        <span className="inline-block w-10 h-px bg-primary" />
                    </p>
                    <h1 className="font-serif text-[2rem] tracking-[-0.022em] leading-[1.05] mb-3">
                        {share.title ?? t('share.paused_title')}
                    </h1>
                    <p className="text-[14px] text-muted-foreground leading-[1.65]">
                        {t('share.paused_body')}
                    </p>
                </div>
            </div>
        );
    }

    return (
        <div className="atelier-light min-h-screen bg-background flex flex-col">
            {/* Editorial header on ivory */}
            <header className="border-b border-border">
                <div className="max-w-3xl mx-auto px-4 sm:px-6 py-5 flex items-center justify-between">
                    <p className="flex items-baseline gap-2 text-foreground">
                        <span className="font-serif italic text-[1.4rem] leading-none tracking-tight">
                            {wedding.partner_a_name} <span className="text-foreground/35">&amp;</span> {wedding.partner_b_name}
                        </span>
                    </p>
                    <span className="text-[10px] tracking-[0.32em] uppercase text-primary">
                        {t('share.guest_gallery')}
                    </span>
                </div>
            </header>

            <main className="flex-1 max-w-2xl w-full mx-auto px-4 sm:px-6 py-14 sm:py-16">
                <div className="mb-12">
                    <p className="text-[10.5px] tracking-[0.34em] uppercase text-primary mb-4 flex items-center gap-3">
                        <span className="inline-block w-14 h-px bg-primary" />
                        {t('share.share_photos')}
                    </p>
                    <h1 className="font-serif text-[2.4rem] sm:text-[3rem] tracking-[-0.025em] leading-[1.04] mb-4">
                        {share.title ?? t('share.gallery_title')}
                    </h1>
                    {share.message && (
                        <p className="text-[15px] text-muted-foreground leading-[1.7] max-w-xl">{share.message}</p>
                    )}
                </div>

                {/* Seat finder */}
                <section className="vellum p-7 sm:p-8 mb-9">
                    <p className="text-[10.5px] tracking-[0.34em] uppercase text-primary mb-3 flex items-center gap-3">
                        <span className="inline-block w-10 h-px bg-primary" />
                        {t('share.find_seat')}
                    </p>
                    <h2 className="font-serif text-[1.6rem] sm:text-[1.85rem] tracking-[-0.022em] leading-tight mb-5">
                        {t('share.where_sitting')}
                    </h2>
                    <form onSubmit={handleSeatSearch} className="flex gap-2">
                        <input
                            type="text"
                            value={seatQuery}
                            onChange={(e) => setSeatQuery(e.target.value)}
                            placeholder={t('share.name_placeholder')}
                            className="input flex-1"
                        />
                        <button type="submit" disabled={seatSearching} className="btn-gold !px-5">
                            {seatSearching ? t('share.searching') : t('share.search')}
                        </button>
                    </form>

                    {singleMatch && (
                        <div className="mt-6 border border-primary/40 bg-primary/[0.06] p-5 rounded-sm">
                            <p className="text-[10px] tracking-[0.3em] uppercase text-primary mb-2 flex items-center gap-2">
                                <span className="inline-block w-8 h-px bg-primary" />
                                {t('share.welcome_name', { name: singleMatch.person_name.split(' ')[0] })}
                            </p>
                            <p className="font-serif text-[1.5rem] sm:text-[1.8rem] tracking-[-0.022em] leading-tight">
                                {t('share.youre_at')} <span className="italic text-primary">{singleMatch.table_name ?? '—'}</span>
                            </p>
                            {!singleMatch.table_name && (
                                <p className="text-[12.5px] text-muted-foreground mt-2">
                                    {t('share.no_table')}
                                </p>
                            )}
                        </div>
                    )}

                    {seatMatches && seatMatches.length > 1 && (
                        <div className="mt-6 space-y-1.5">
                            <p className="text-[10px] tracking-[0.3em] uppercase text-muted-foreground mb-2">{t('share.multiple_matches')}</p>
                            {seatMatches.map((m) => (
                                <button
                                    key={m.person_name}
                                    onClick={() => { setSeatQuery(m.person_name); setSeatMatches([m]); }}
                                    className="w-full text-left border border-border bg-card hover:border-primary/40 px-3 py-2.5 text-[13.5px] transition-colors rounded-sm"
                                >
                                    <span className="font-medium">{m.person_name}</span>
                                    {m.table_name && <span className="text-muted-foreground"> · {m.table_name}</span>}
                                </button>
                            ))}
                        </div>
                    )}

                    {seatMatches && seatMatches.length === 0 && (
                        <p className="mt-5 text-[13px] text-muted-foreground">
                            {t('share.not_found')}
                        </p>
                    )}

                    {floorPlan && (
                        <div className="mt-7">
                            <FloorPlanView
                                plan={floorPlan}
                                highlightTable={highlightTable}
                                accent="var(--color-primary)"
                            />
                            {highlightTable && (
                                <p className="text-[11.5px] text-muted-foreground mt-3 text-center tracking-wide">
                                    {t('share.table_highlighted')}
                                </p>
                            )}
                        </div>
                    )}
                </section>

                {/* Upload form */}
                <form onSubmit={handleUpload} className="vellum p-7 sm:p-8 space-y-5">
                    <p className="text-[10.5px] tracking-[0.34em] uppercase text-primary mb-2 flex items-center gap-3">
                        <span className="inline-block w-10 h-px bg-primary" />
                        {t('share.add_to_gallery')}
                    </p>
                    <div>
                        <label className="block text-[10px] tracking-[0.28em] uppercase text-muted-foreground mb-2">
                            {t('share.your_name_optional')}
                        </label>
                        <input
                            type="text"
                            value={uploaderName}
                            onChange={(e) => setUploaderName(e.target.value)}
                            className="input"
                            placeholder="Jane Smith"
                        />
                    </div>
                    <div>
                        <label className="block text-[10px] tracking-[0.28em] uppercase text-muted-foreground mb-2">
                            {t('share.photos_videos')}
                        </label>
                        <input
                            ref={fileRef}
                            type="file"
                            multiple
                            accept="image/jpeg,image/png,image/gif,image/webp,video/mp4,video/quicktime"
                            onChange={(e) => setFiles(Array.from(e.target.files ?? []))}
                            className="w-full text-[13.5px] file:mr-3 file:px-3 file:py-2 file:rounded-none file:border file:border-border file:bg-card file:text-foreground file:text-[11px] file:tracking-[0.18em] file:uppercase file:cursor-pointer file:hover:border-primary/40"
                        />
                        {files.length > 0 && (
                            <p className="text-[12px] text-muted-foreground mt-2 tracking-wide">{t('share.files_selected', { count: files.length })}</p>
                        )}
                    </div>
                    <button
                        type="submit"
                        disabled={uploading || files.length === 0}
                        className="w-full btn-gold"
                    >
                        {uploading ? t('share.uploading_progress', { done: uploaded, total: files.length }) : t('share.upload_to_gallery')}
                    </button>

                    {successCount !== null && successCount > 0 && (
                        <div className="border border-primary/30 bg-primary/[0.06] px-4 py-3 text-[13px] text-foreground/85 rounded-sm">
                            <span className="font-medium">{successCount} {successCount !== 1 ? t('share.photo_other') : t('share.photo_one')}</span> {t('share.uploaded_thanks')}
                        </div>
                    )}
                </form>

                <div className="mt-12">
                    {!photosLoaded ? (
                        <button
                            onClick={loadPhotos}
                            className="w-full btn-ghost"
                        >
                            {t('share.view_all_photos')}
                        </button>
                    ) : (
                        <div>
                            <div className="flex items-baseline justify-between mb-6 pb-4 border-b border-border">
                                <p className="text-[10.5px] tracking-[0.34em] uppercase text-primary flex items-center gap-3">
                                    <span className="inline-block w-10 h-px bg-primary" />
                                    {t('share.all_photos')}
                                </p>
                                <span className="text-[11px] tracking-[0.22em] uppercase text-muted-foreground">
                                    {photos.length} {photos.length === 1 ? t('share.frame_one') : t('share.frame_other')}
                                </span>
                            </div>
                            <div className="grid grid-cols-3 gap-2">
                                {photos.map((p) => (
                                    <div
                                        key={p.id}
                                        className="aspect-square bg-muted overflow-hidden border border-border rounded-sm"
                                    >
                                        {p.media_type === 'video' ? (
                                            <div className="w-full h-full flex items-center justify-center">
                                                <svg className="w-6 h-6 text-foreground/55" viewBox="0 0 24 24" fill="currentColor">
                                                    <path d="M8 5v14l11-7z" />
                                                </svg>
                                            </div>
                                        ) : (
                                            <img src={p.file_url} alt="" className="w-full h-full object-cover" />
                                        )}
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}
                </div>
            </main>

            <footer className="border-t border-border py-6">
                <p className="text-center text-[10.5px] tracking-[0.28em] uppercase text-muted-foreground">
                    {t('common.powered_by')} <span className="font-serif italic text-foreground normal-case tracking-tight ml-1">WedFlow</span>
                </p>
            </footer>
        </div>
    );
}

function CameraIcon({ className = '' }: { className?: string }) {
    return (
        <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
            <path d="M4 8h3l2-2h6l2 2h3a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1z" />
            <circle cx="12" cy="13" r="3.5" />
        </svg>
    );
}
