import { useForm, router } from '@inertiajs/react';
import AppLayout from '@/layouts/AppLayout';
import { useState } from 'react';
import { QRCardDialog } from '@/components/qr-card-dialog';
import { useTranslator } from '@/lib/i18n';

interface Props {
    wedding: { id: string; partner_a_name: string; partner_b_name: string; wedding_date?: string };
    share: { id: string; slug: string; title?: string; message?: string; is_active: boolean };
    photos: { id: string; file_url: string; uploader_name?: string; media_type: string; created_at: string }[];
}

export default function Photos({ wedding, share, photos }: Props) {
    const t = useTranslator();
    const shareUrl = typeof window !== 'undefined' ? `${window.location.origin}/share/${share.slug}` : '';
    const [copied, setCopied] = useState(false);
    const [showQrCard, setShowQrCard] = useState(false);

    const form = useForm({
        title: share.title ?? '',
        message: share.message ?? '',
        is_active: share.is_active,
    });

    function saveShare(e: React.FormEvent) {
        e.preventDefault();
        form.put(`/weddings/${wedding.id}/photos/share`, { preserveScroll: true });
    }

    function copyUrl() {
        navigator.clipboard.writeText(shareUrl);
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
    }

    const eventDate = wedding.wedding_date
        ? new Date(wedding.wedding_date).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })
        : undefined;

    // Unique contributors for the header avatar stack.
    const contributors = Array.from(
        new Map(
            photos
                .map((p) => p.uploader_name)
                .filter((n): n is string => !!n)
                .map((n) => [n, n.split(' ').map((part) => part[0]).join('').slice(0, 2).toUpperCase()]),
        ).entries(),
    );

    return (
        <AppLayout wedding={wedding as any}>
            <div className="max-w-5xl mx-auto px-4 sm:px-6 py-10">
                {/* Editorial header */}
                <div className="mb-10">
                    <p className="text-[11px] font-medium tracking-[0.22em] uppercase text-primary mb-2">
                        Guest gallery
                    </p>
                    <div className="flex items-baseline justify-between flex-wrap gap-4">
                        <h1 className="font-serif text-[2.2rem] sm:text-[2.6rem] tracking-[-0.022em] leading-[1.05]">
                            Photo <em className="italic text-primary">sharing</em>
                        </h1>
                        <div className="flex items-center gap-2.5 text-[12.5px] text-muted-foreground">
                            <span>
                                {photos.length} {photos.length === 1 ? 'photo' : 'photos'}
                                {contributors.length > 0 && (
                                    <> · {contributors.length} {contributors.length === 1 ? 'contributor' : 'contributors'}</>
                                )}
                            </span>
                            {contributors.length > 0 && (
                                <div className="flex -space-x-1.5">
                                    {contributors.slice(0, 4).map(([name, initials]) => (
                                        <span
                                            key={name}
                                            title={name}
                                            className="w-6 h-6 rounded-full bg-primary/15 text-primary text-[9px] font-semibold flex items-center justify-center border border-card"
                                        >
                                            {initials}
                                        </span>
                                    ))}
                                </div>
                            )}
                        </div>
                    </div>
                </div>

                {/* Share settings card */}
                <div className="bg-card border border-border rounded-3xl p-6 sm:p-7 mb-10">
                    <div className="flex items-baseline justify-between mb-5 flex-wrap gap-3">
                        <div>
                            <p className="text-[11px] font-medium tracking-[0.22em] uppercase text-primary mb-1.5">
                                Share settings
                            </p>
                            <h2 className="font-serif text-[1.4rem] tracking-tight">{t('photos.share_page')}</h2>
                        </div>
                        <button
                            onClick={() => setShowQrCard(true)}
                            className="btn-outline !py-2.5 !px-4 !text-[13.5px]"
                        >
                            <QrIcon className="w-4 h-4 mr-1.5" />
                            QR card
                        </button>
                    </div>

                    <form onSubmit={saveShare} className="space-y-4">
                        <div>
                            <label className="block text-[12px] font-medium text-muted-foreground mb-1.5">
                                Share URL
                            </label>
                            <div className="flex gap-2">
                                <input
                                    type="text"
                                    value={shareUrl}
                                    readOnly
                                    className="input flex-1 bg-muted/30 cursor-text"
                                />
                                <button
                                    type="button"
                                    onClick={copyUrl}
                                    className="btn-outline !px-4 !text-[13px]"
                                >
                                    {copied ? 'Copied' : 'Copy'}
                                </button>
                            </div>
                        </div>
                        <div>
                            <label className="block text-[12px] font-medium text-muted-foreground mb-1.5">
                                Title
                            </label>
                            <input
                                type="text"
                                value={form.data.title}
                                onChange={(e) => form.setData('title', e.target.value)}
                                className="input"
                                placeholder={t('photos.share_msg_placeholder')}
                            />
                        </div>
                        <div>
                            <label className="block text-[12px] font-medium text-muted-foreground mb-1.5">
                                Message
                            </label>
                            <textarea
                                value={form.data.message}
                                onChange={(e) => form.setData('message', e.target.value)}
                                className="input"
                                rows={2}
                                placeholder={t('photos.help_placeholder')}
                            />
                        </div>
                        <div className="flex items-center justify-between flex-wrap gap-3 pt-1">
                            <label className="flex items-center gap-2.5 cursor-pointer select-none text-[13.5px]">
                                <input
                                    type="checkbox"
                                    checked={form.data.is_active}
                                    onChange={(e) => form.setData('is_active', e.target.checked)}
                                    className="w-4 h-4 rounded border-border accent-foreground"
                                />
                                Active — guests can upload
                            </label>
                            <button
                                type="submit"
                                disabled={form.processing}
                                className="btn-charcoal !py-2.5 !px-5 !text-[13.5px]"
                            >
                                {form.processing ? 'Saving…' : 'Save settings'}
                            </button>
                        </div>
                    </form>
                </div>

                {/* Photo gallery */}
                <div>
                    <p className="text-[11px] font-medium tracking-[0.22em] uppercase text-muted-foreground mb-4">
                        {t('photos.title')}
                    </p>
                    {photos.length === 0 ? (
                        <div className="text-center py-16 border border-dashed border-border rounded-3xl">
                            <div className="w-14 h-14 rounded-2xl bg-muted border border-border mx-auto mb-4 flex items-center justify-center">
                                <CameraIcon className="w-6 h-6 text-foreground/60" />
                            </div>
                            <p className="font-serif text-[1.4rem] tracking-tight mb-2">{t('photos.no_photos')}</p>
                            <p className="text-[13.5px] text-muted-foreground">
                                Share the link or QR card with your guests and they'll appear here.
                            </p>
                        </div>
                    ) : (
                        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
                            {photos.map((photo) => (
                                <div
                                    key={photo.id}
                                    className="relative group aspect-square bg-muted rounded-xl overflow-hidden border border-border"
                                >
                                    {photo.media_type === 'video' ? (
                                        <div className="w-full h-full flex items-center justify-center">
                                            <svg className="w-10 h-10 text-foreground/40" viewBox="0 0 24 24" fill="currentColor">
                                                <path d="M8 5v14l11-7z" />
                                            </svg>
                                        </div>
                                    ) : (
                                        <img src={photo.file_url} alt="" className="w-full h-full object-cover" />
                                    )}
                                    <div className="absolute inset-0 bg-foreground/55 backdrop-blur-[2px] opacity-0 group-hover:opacity-100 transition-opacity flex flex-col items-center justify-center gap-2.5 px-2">
                                        {photo.uploader_name && (
                                            <p className="text-background text-[11.5px] tracking-wide">{photo.uploader_name}</p>
                                        )}
                                        <button
                                            onClick={() => {
                                                if (confirm('Delete this photo?')) {
                                                    router.delete(`/weddings/${wedding.id}/photos/${photo.id}`, { preserveScroll: true });
                                                }
                                            }}
                                            className="bg-background/90 text-foreground text-[11.5px] font-medium px-3 py-1.5 rounded-full hover:bg-background transition-colors"
                                        >
                                            {t('common.delete')}
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            </div>

            <QRCardDialog
                open={showQrCard}
                onClose={() => setShowQrCard(false)}
                url={shareUrl}
                coupleNames={`${wedding.partner_a_name} & ${wedding.partner_b_name}`}
                eventDate={eventDate}
                cardType="photo"
            />
        </AppLayout>
    );
}

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>
    );
}

function QrIcon({ className = '' }: { className?: string }) {
    return (
        <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
            <rect x="3" y="3" width="7" height="7" rx="1" />
            <rect x="14" y="3" width="7" height="7" rx="1" />
            <rect x="3" y="14" width="7" height="7" rx="1" />
            <path d="M14 14h3v3h-3zM20 14v3M14 20h3M20 20v1" />
        </svg>
    );
}
