import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { useTranslation } from '@/hooks/use-translation';
import { cn } from '@/lib/utils';
import { Link } from '@inertiajs/react';
import { ImageOff, ImageUp, Images } from 'lucide-react';
import { useState } from 'react';
import { NS, fill } from '../format';
import ImagesCarousel, { PHOTO_FALLBACK_URL, onPhotoError } from '../images-carousel';

/** Emplacement des vignettes (moitié droite, 2 × 2) selon leur nombre. */
const THUMB_SPANS: Record<number, string[]> = {
    1: ['col-span-2 row-span-2'],
    2: ['col-span-2', 'col-span-2'],
    3: ['', '', 'col-span-2'],
    4: ['', '', '', ''],
};

interface Props {
    photos: string[];
    name: string;
    /** Lien vers l'étape « Photos » de l'assistant ; null sans droit de modification. */
    manageHref: string | null;
}

export function PhotoStrip({ photos, name, manageHref }: Props) {
    const { t } = useTranslation();
    const [open, setOpen] = useState(false);
    const [startIndex, setStartIndex] = useState(0);

    const manageButton = manageHref && (
        <Button asChild variant="outline" size="sm" className="bg-background/90">
            <Link href={manageHref}>
                <ImageUp className="h-4 w-4" />
                {t(NS, 'photos_manage')}
            </Link>
        </Button>
    );

    if (photos.length === 0) {
        return (
            <Card>
                <CardContent className="flex flex-col items-center gap-3 py-6 text-center">
                    <ImageOff className="text-muted-foreground h-8 w-8" />
                    <p className="text-muted-foreground text-sm">{t(NS, 'photos_empty')}</p>
                    {manageButton}
                </CardContent>
            </Card>
        );
    }

    const thumbs = photos.slice(1, 5);
    const viewAll = photos.length === 1 ? t(NS, 'photos_view_all_one') : fill(t(NS, 'photos_view_all_other'), { count: photos.length });
    const openAt = (index: number) => {
        setStartIndex(index);
        setOpen(true);
    };

    return (
        <div className="relative">
            <div className="grid h-56 grid-cols-4 grid-rows-2 gap-1.5 overflow-hidden rounded-xl sm:h-72">
                <PhotoButton
                    src={photos[0]}
                    alt={name}
                    onClick={() => openAt(0)}
                    className={thumbs.length > 0 ? 'col-span-4 row-span-2 sm:col-span-2' : 'col-span-4 row-span-2'}
                />
                {thumbs.map((src, index) => (
                    <PhotoButton
                        key={`${index}-${src}`}
                        src={src}
                        alt={`${name} (${index + 2}/${photos.length})`}
                        onClick={() => openAt(index + 1)}
                        className={cn('hidden sm:block', THUMB_SPANS[thumbs.length][index])}
                    />
                ))}
            </div>

            <div className="absolute right-3 bottom-3 flex flex-wrap justify-end gap-2">
                {manageButton}
                <Button variant="outline" size="sm" className="bg-background/90" onClick={() => openAt(0)}>
                    <Images className="h-4 w-4" />
                    {viewAll}
                </Button>
            </div>

            <Dialog open={open} onOpenChange={setOpen}>
                <DialogContent className="sm:max-w-4xl">
                    <DialogHeader>
                        <DialogTitle>{name}</DialogTitle>
                        <DialogDescription>
                            {photos.length === 1 ? t(NS, 'photos_count_one') : fill(t(NS, 'photos_count_other'), { count: photos.length })}
                        </DialogDescription>
                    </DialogHeader>
                    {/* Remonté à chaque ouverture : la galerie démarre sur la photo cliquée. */}
                    {open && <ImagesCarousel key={startIndex} images={photos} name={name} startIndex={startIndex} />}
                </DialogContent>
            </Dialog>
        </div>
    );
}

function PhotoButton({ src, alt, onClick, className }: { src: string; alt: string; onClick: () => void; className?: string }) {
    return (
        <button type="button" onClick={onClick} className={cn('bg-muted group relative min-h-0 cursor-zoom-in overflow-hidden', className)}>
            <img
                src={src || PHOTO_FALLBACK_URL}
                alt={alt}
                loading="lazy"
                className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-[1.03]"
                onError={onPhotoError}
            />
        </button>
    );
}
