import { cn } from '@/lib/utils';
import { Dialog, DialogPanel } from '@headlessui/react';
import { AnimatePresence, motion } from 'framer-motion';
import { ChevronLeft, ChevronRight, X } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';

type Shot = { thumb: string; large: string };

export default function ScreenshotGallery({ shots, title }: { shots: Shot[]; title: string }) {
    const [index, setIndex] = useState<number | null>(null);
    const open = index !== null;
    const go = useCallback((d: number) => setIndex((i) => (i === null ? i : (i + d + shots.length) % shots.length)), [shots.length]);

    useEffect(() => {
        if (!open) return;
        const onKey = (e: KeyboardEvent) => {
            if (e.key === 'ArrowRight') go(1);
            if (e.key === 'ArrowLeft') go(-1);
        };
        window.addEventListener('keydown', onKey);
        return () => window.removeEventListener('keydown', onKey);
    }, [open, go]);

    return (
        <>
            <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
                {shots.map((s, i) => (
                    <motion.button
                        key={i}
                        onClick={() => setIndex(i)}
                        whileHover={{ scale: 1.015 }}
                        transition={{ duration: 0.2 }}
                        aria-label={`Open screenshot ${i + 1} of ${shots.length}`}
                        className={cn('group relative overflow-hidden rounded-xl border border-border bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring/60', i === 0 ? 'col-span-2 row-span-2 aspect-video sm:aspect-auto' : 'aspect-video')}
                    >
                        <img src={s.thumb} alt={`${title} screenshot ${i + 1}`} loading="lazy" className="size-full object-cover transition duration-500 group-hover:scale-105" />
                        <span className="absolute inset-0 bg-black/0 transition group-hover:bg-black/15" />
                    </motion.button>
                ))}
            </div>

            <Dialog open={open} onClose={() => setIndex(null)} className="relative z-[80]">
                <div className="fixed inset-0 bg-black/90 backdrop-blur-md" aria-hidden />
                <div className="fixed inset-0 flex flex-col">
                    <DialogPanel className="flex h-full flex-col outline-none">
                        <div className="flex items-center justify-between px-4 py-3 text-sm text-white/70">
                            <span aria-live="polite">{(index ?? 0) + 1} / {shots.length}</span>
                            <button onClick={() => setIndex(null)} aria-label="Close gallery" className="rounded-lg p-2 text-white/80 transition hover:bg-white/10 hover:text-white"><X className="size-5" /></button>
                        </div>
                        <div className="relative flex min-h-0 flex-1 items-center justify-center px-4 sm:px-16" onClick={(e) => e.target === e.currentTarget && setIndex(null)}>
                            <AnimatePresence mode="wait" initial={false}>
                                {index !== null && (
                                    <motion.img
                                        key={index}
                                        src={shots[index].large}
                                        alt={`${title} screenshot ${index + 1}`}
                                        initial={{ opacity: 0, scale: 0.97 }}
                                        animate={{ opacity: 1, scale: 1 }}
                                        exit={{ opacity: 0, scale: 0.98 }}
                                        transition={{ duration: 0.2 }}
                                        className="max-h-full max-w-full rounded-lg object-contain shadow-2xl"
                                    />
                                )}
                            </AnimatePresence>
                            {shots.length > 1 && (
                                <>
                                    <button onClick={() => go(-1)} aria-label="Previous screenshot" className="absolute left-2 top-1/2 -translate-y-1/2 rounded-full bg-white/10 p-3 text-white backdrop-blur transition hover:bg-white/20 sm:left-4"><ChevronLeft className="size-5" /></button>
                                    <button onClick={() => go(1)} aria-label="Next screenshot" className="absolute right-2 top-1/2 -translate-y-1/2 rounded-full bg-white/10 p-3 text-white backdrop-blur transition hover:bg-white/20 sm:right-4"><ChevronRight className="size-5" /></button>
                                </>
                            )}
                        </div>
                        <div className="flex justify-center gap-2 overflow-x-auto p-4">
                            {shots.map((s, i) => (
                                <button key={i} onClick={() => setIndex(i)} aria-label={`Go to screenshot ${i + 1}`} aria-current={i === index} className={cn('h-14 w-24 shrink-0 overflow-hidden rounded-md border-2 transition', i === index ? 'border-white' : 'border-transparent opacity-50 hover:opacity-100')}>
                                    <img src={s.thumb} alt="" className="size-full object-cover" />
                                </button>
                            ))}
                        </div>
                    </DialogPanel>
                </div>
            </Dialog>
        </>
    );
}
