'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useCallback, useRef } from 'react';
import { Paperclip, Trash2, Download, Upload, FileIcon } from 'lucide-react';
import { cn } from '../../../lib/utils.js';
import { Button } from '../../ui/button.js';
import { deleteAttachment } from '../../../app/actions/manage-attachments.js';
function formatFileSize(bytes) {
    if (bytes < 1024)
        return `${String(bytes)} B`;
    if (bytes < 1024 * 1024)
        return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
export function AttachmentList({ workItemId, attachments: initialAttachments, className, }) {
    const [attachments, setAttachments] = useState(initialAttachments);
    const [uploading, setUploading] = useState(false);
    const fileInputRef = useRef(null);
    const handleUpload = useCallback(async (files) => {
        if (!files || files.length === 0)
            return;
        setUploading(true);
        try {
            for (const file of Array.from(files)) {
                const formData = new FormData();
                formData.append('file', file);
                formData.append('workItemId', workItemId);
                const res = await fetch('/api/pm-attachments/upload', {
                    method: 'POST',
                    body: formData,
                });
                if (res.ok) {
                    const data = (await res.json());
                    const newAttachment = {
                        id: data.id,
                        workItemId,
                        filename: data.filename,
                        mimeType: data.mimeType,
                        fileSize: data.fileSize,
                        storagePath: '',
                        createdAt: new Date(data.createdAt),
                        updatedAt: new Date(data.createdAt),
                        deletedAt: undefined,
                    };
                    setAttachments((prev) => [...prev, newAttachment]);
                }
            }
        }
        finally {
            setUploading(false);
            if (fileInputRef.current)
                fileInputRef.current.value = '';
        }
    }, [workItemId]);
    const handleDelete = useCallback(async (attachmentId) => {
        const result = await deleteAttachment(attachmentId);
        if (!result.error) {
            setAttachments((prev) => prev.filter((a) => a.id !== attachmentId));
        }
    }, []);
    const handleDownload = useCallback((attachmentId) => {
        window.open(`/api/pm-attachments/download?id=${attachmentId}`, '_blank');
    }, []);
    return (_jsxs("div", { "data-testid": "attachment-list", className: cn('space-y-3', className), children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("div", { className: "flex items-center gap-1.5", children: [_jsx(Paperclip, { className: "text-muted-foreground h-3.5 w-3.5" }), _jsxs("span", { className: "text-xs font-medium", children: ["Attachments ", attachments.length > 0 ? `(${String(attachments.length)})` : ''] })] }), _jsxs("div", { children: [_jsx("input", { ref: fileInputRef, type: "file", multiple: true, className: "hidden", onChange: (e) => handleUpload(e.target.files), "data-testid": "file-input" }), _jsxs(Button, { variant: "ghost", size: "sm", className: "h-6 gap-1 text-xs", onClick: () => fileInputRef.current?.click(), disabled: uploading, "data-testid": "upload-btn", children: [_jsx(Upload, { className: "h-3 w-3" }), uploading ? 'Uploading...' : 'Upload'] })] })] }), attachments.length === 0 ? (_jsx("p", { className: "text-muted-foreground text-[10px]", children: "No attachments" })) : (_jsx("div", { className: "space-y-1", children: attachments.map((att) => (_jsxs("div", { "data-testid": `attachment-${att.id}`, className: "group hover:bg-accent/50 flex items-center gap-2 rounded-sm px-2 py-1 text-xs", children: [_jsx(FileIcon, { className: "text-muted-foreground h-3.5 w-3.5 shrink-0" }), _jsx("span", { className: "flex-1 truncate", children: att.filename }), _jsx("span", { className: "text-muted-foreground text-[10px]", children: formatFileSize(att.fileSize) }), _jsxs("div", { className: "hidden gap-0.5 group-hover:flex", children: [_jsx(Button, { variant: "ghost", size: "sm", className: "h-5 w-5 p-0", onClick: () => handleDownload(att.id), title: "Download", children: _jsx(Download, { className: "h-3 w-3" }) }), _jsx(Button, { variant: "ghost", size: "sm", className: "text-destructive h-5 w-5 p-0", onClick: () => handleDelete(att.id), title: "Delete", children: _jsx(Trash2, { className: "h-3 w-3" }) })] })] }, att.id))) }))] }));
}
