import { useState } from 'react';
import { ImagePreviewModal } from '@/components/dialogs';
import type { ImagePreviewItem } from '@/components/dialogs/image-preview-modal';

type ImagePreviewButtonProps = {
    srcs: string[];
    modalSrc?: string;
    modalSrcs?: string[];
    title?: string;
    description?: string;
    alt?: string;
    className?: string;
    items?: ImagePreviewItem[];
    startIndex?: number;
};

export function ImagePreviewButton({
    srcs,
    modalSrc,
    modalSrcs,
    title,
    description,
    alt,
    className = 'h-10 w-10',
    items,
    startIndex = 0,
}: ImagePreviewButtonProps) {
    const [open, setOpen] = useState(false);

    const modalSources = modalSrcs ?? (modalSrc ? [modalSrc] : null);

    return (
        <>
            <button
                type="button"
                onClick={() => setOpen(true)}
                className={`relative block overflow-hidden rounded-md border bg-muted transition-opacity hover:opacity-80 ${className}`}
            >
                <img
                    src={srcs[0]}
                    alt={alt ?? title ?? 'Preview'}
                    className="h-full w-full object-cover"
                />
                {srcs.length > 1 && (
                    <span className="absolute -top-1 -right-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-medium text-primary-foreground">
                        {srcs.length}
                    </span>
                )}
            </button>
            <ImagePreviewModal
                open={open}
                onOpenChange={setOpen}
                src={modalSources?.[0] ?? srcs[0]}
                sources={modalSources ?? srcs}
                title={title}
                description={description}
                items={items}
                startIndex={startIndex}
            />
        </>
    );
}
