import { router } from '@inertiajs/react';
import { Download, FileText, ImageOff, Maximize2, Trash2 } from 'lucide-react';
import { useState } from 'react';
import { AttachmentViewer } from '@/components/crm/attachment-viewer';
import { cn } from '@/lib/utils';
import type { TicketAttachment } from '@/types';

/**
 * The photos, screenshots and documents on a ticket.
 *
 * Clicking one opens it in the viewer over the page rather than in a new tab,
 * so a fault code can be read while the reply is being written. Images show as
 * thumbnails; anything the browser cannot render - a PDF, or the HEIC an iPhone
 * produces - keeps its icon and its name, with the download beside it.
 */
export function TicketAttachmentGallery({
    attachments,
    canDelete = false,
}: {
    attachments: TicketAttachment[];
    canDelete?: boolean;
}) {
    const [openIndex, setOpenIndex] = useState<number | null>(null);

    if (attachments.length === 0) {
        return null;
    }

    const remove = (attachment: TicketAttachment) => {
        if (
            window.confirm(
                `Remove ${attachment.name} from this ticket? The file is deleted.`,
            )
        ) {
            router.delete(attachment.delete_url, { preserveScroll: true });
        }
    };

    return (
        <>
            <ul className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
                {attachments.map((attachment, index) => (
                    <li
                        key={attachment.id}
                        className="group overflow-hidden rounded-lg border border-hairline bg-card"
                    >
                        <button
                            type="button"
                            onClick={() => setOpenIndex(index)}
                            className="relative block w-full bg-muted/40"
                            aria-label={`View ${attachment.name}`}
                            data-test="open-attachment"
                        >
                            {attachment.is_image ? (
                                <img
                                    src={attachment.url}
                                    alt={attachment.name}
                                    loading="lazy"
                                    className="h-36 w-full object-cover transition-opacity group-hover:opacity-90"
                                />
                            ) : (
                                <span className="flex h-36 w-full flex-col items-center justify-center gap-2 text-muted-foreground">
                                    {attachment.mime_type ===
                                    'application/pdf' ? (
                                        <FileText
                                            className="size-8"
                                            aria-hidden
                                        />
                                    ) : (
                                        <ImageOff
                                            className="size-8"
                                            aria-hidden
                                        />
                                    )}
                                    <span className="text-[11px] uppercase">
                                        {attachment.human_size}
                                    </span>
                                </span>
                            )}

                            <span className="absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 transition-opacity group-hover:opacity-100">
                                <Maximize2
                                    className="size-5 text-white"
                                    aria-hidden
                                />
                            </span>
                        </button>

                        <div className="flex items-start gap-2 px-3 py-2">
                            <div className="min-w-0 flex-1">
                                <p className="truncate text-xs font-medium">
                                    {attachment.name}
                                </p>
                                <p className="truncate text-[11px] text-muted-foreground">
                                    {attachment.human_size}
                                    {attachment.uploaded_by
                                        ? ` · ${attachment.uploaded_by}`
                                        : ''}
                                </p>
                            </div>

                            <a
                                href={attachment.download_url}
                                className={cn(
                                    'flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground',
                                    'hover:bg-accent hover:text-foreground',
                                )}
                                aria-label={`Download ${attachment.name}`}
                                title="Download"
                            >
                                <Download className="size-3.5" aria-hidden />
                            </a>

                            {canDelete ? (
                                <button
                                    type="button"
                                    onClick={() => remove(attachment)}
                                    aria-label={`Remove ${attachment.name}`}
                                    title="Remove"
                                    className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-destructive/10 hover:text-destructive"
                                >
                                    <Trash2 className="size-3.5" aria-hidden />
                                </button>
                            ) : null}
                        </div>
                    </li>
                ))}
            </ul>

            <AttachmentViewer
                attachments={attachments}
                startIndex={openIndex ?? 0}
                open={openIndex !== null}
                onOpenChange={(next) =>
                    setOpenIndex(next ? (openIndex ?? 0) : null)
                }
            />
        </>
    );
}
