import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useRef, useState, } from "react";
import { toast } from "sonner";
import { Download, Loader2, Paperclip, Plus, RefreshCw } from "lucide-react";
import { Button } from "../../components/ui/button";
import { DeleteIcon } from "../../components/ui/delete-icon";
import { useEditContext } from "../../editor/client/editContext";
import { deleteAttachment, getAttachmentDownloadUrl, getAttachments, uploadAttachmentFile, } from "../services/taskService";
function formatFileSize(bytes) {
    if (!Number.isFinite(bytes) || bytes <= 0)
        return "0 B";
    const units = ["B", "KB", "MB", "GB"];
    let size = bytes;
    let unit = 0;
    while (size >= 1024 && unit < units.length - 1) {
        size /= 1024;
        unit++;
    }
    const fixed = size >= 100 || unit === 0 ? 0 : 1;
    return `${size.toFixed(fixed)} ${units[unit]}`;
}
const sectionHeadingClass = "text-xs font-bold tracking-wider text-neutral-grey-50 ";
export function TaskAttachmentsSection(props) {
    const { task, canEdit, onTaskChanged, className } = props;
    const editContext = useEditContext();
    const [attachmentRefreshKey, setAttachmentRefreshKey] = useState(0);
    const [attachments, setAttachments] = useState([]);
    const [attachmentsLoading, setAttachmentsLoading] = useState(false);
    const [uploadingAttachment, setUploadingAttachment] = useState(false);
    const [deletingAttachmentId, setDeletingAttachmentId] = useState(null);
    const attachmentInputRef = useRef(null);
    const refreshAttachments = useCallback(async () => {
        if (!task?.taskId) {
            setAttachments([]);
            return;
        }
        setAttachmentsLoading(true);
        try {
            const result = await getAttachments(task.taskId);
            if (result.type === "success") {
                setAttachments(result.data || []);
            }
            else if (result.type !== "unauthorized") {
                toast.error(result.summary || "Failed to load attachments");
            }
        }
        finally {
            setAttachmentsLoading(false);
        }
    }, [task?.taskId]);
    useEffect(() => {
        void refreshAttachments();
    }, [refreshAttachments, attachmentRefreshKey]);
    const openAttachmentPicker = useCallback(() => {
        attachmentInputRef.current?.click();
    }, []);
    const handleAttachmentFilesSelected = useCallback(async (event) => {
        if (!task?.taskId)
            return;
        const files = event.target.files;
        if (!files || files.length === 0)
            return;
        setUploadingAttachment(true);
        let uploaded = 0;
        try {
            for (const file of Array.from(files)) {
                const result = await uploadAttachmentFile(task.taskId, file);
                if (result.type === "success") {
                    uploaded += 1;
                    continue;
                }
                toast.error(result.summary || `Failed to upload "${file.name}"`, result.details ? { description: result.details } : undefined);
            }
            if (uploaded > 0) {
                toast.success(uploaded === 1
                    ? "Attachment uploaded"
                    : `${uploaded} attachments uploaded`);
                setAttachmentRefreshKey((key) => key + 1);
                await onTaskChanged?.();
            }
        }
        finally {
            setUploadingAttachment(false);
            if (event.target) {
                event.target.value = "";
            }
        }
    }, [onTaskChanged, task?.taskId]);
    const handleDownloadAttachment = useCallback((attachmentId) => {
        const url = getAttachmentDownloadUrl(attachmentId);
        window.open(url, "_blank", "noopener,noreferrer");
    }, []);
    const handleDeleteAttachment = useCallback(async (attachment) => {
        if (!task)
            return;
        const confirmed = await new Promise((resolve) => {
            if (!editContext) {
                resolve(window.confirm(`Delete "${attachment.fileName}"? This action cannot be undone.`));
                return;
            }
            editContext.confirm({
                header: "Delete attachment",
                message: `Delete "${attachment.fileName}"? This action cannot be undone.`,
                acceptLabel: "Delete",
                showCancel: true,
                accept: () => resolve(true),
                reject: () => resolve(false),
            });
        });
        if (!confirmed)
            return;
        setDeletingAttachmentId(attachment.attachmentId);
        try {
            const result = await deleteAttachment(attachment.attachmentId);
            if (result.type !== "success") {
                toast.error(result.summary || "Failed to delete attachment");
                return;
            }
            setAttachments((prev) => prev.filter((item) => item.attachmentId !== attachment.attachmentId));
            toast.success("Attachment deleted");
            await onTaskChanged?.();
        }
        finally {
            setDeletingAttachmentId(null);
        }
    }, [editContext, onTaskChanged, task]);
    if (!task) {
        return null;
    }
    return (_jsxs("div", { className: [
            "border-border-default/60 grid gap-4 border-t pt-6",
            className,
        ]
            .filter(Boolean)
            .join(" "), children: [_jsxs("div", { className: "flex flex-wrap items-center justify-between gap-2", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Paperclip, { className: "text-neutral-grey-50 h-4 w-4" }), _jsx("span", { className: sectionHeadingClass, children: "Attachments" }), _jsx("span", { className: "rounded-badge badge-pad-sm text-2xs border-border-default text-neutral-grey-50 border bg-white font-semibold", children: attachments.length })] }), _jsxs("div", { className: "flex items-center gap-1", children: [_jsxs(Button, { type: "button", size: "sm", variant: "ghost", onClick: () => setAttachmentRefreshKey((key) => key + 1), disabled: attachmentsLoading, className: "text-neutral-grey-50 hover:text-neutral-grey-50 h-7 px-2 text-xs", children: [_jsx(RefreshCw, { className: `h-3 w-3 ${attachmentsLoading ? "animate-spin" : ""}` }), "Refresh"] }), canEdit ? (_jsxs(Button, { type: "button", size: "sm", onClick: openAttachmentPicker, disabled: uploadingAttachment, className: "h-7 px-3 text-xs", children: [uploadingAttachment ? (_jsx(Loader2, { className: "h-3 w-3 animate-spin" })) : (_jsx(Plus, { className: "h-3 w-3" })), "Upload"] })) : null] })] }), _jsx("input", { ref: attachmentInputRef, type: "file", multiple: true, className: "hidden", onChange: (event) => void handleAttachmentFilesSelected(event) }), attachments.length === 0 ? (_jsx("div", { className: "border-border-default text-neutral-grey-50 rounded-xl border border-dashed bg-white/70 px-4 py-6 text-center text-xs italic", children: attachmentsLoading
                    ? "Loading attachments..."
                    : "No attachments yet." })) : (_jsx("div", { className: "grid gap-2", children: attachments.map((attachment) => (_jsxs("div", { className: "border-border-default flex items-center justify-between gap-3 rounded-lg border bg-white p-3 shadow-sm", children: [_jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("button", { type: "button", onClick: () => handleDownloadAttachment(attachment.attachmentId), className: "text-neutral-grey-100 hover:text-feedback-blue truncate text-left text-sm font-semibold transition-colors", children: attachment.fileName }), _jsxs("div", { className: "text-neutral-grey-50 mt-0.5 text-[11px]", children: [formatFileSize(attachment.fileSize), " |", " ", new Date(attachment.uploadedAt).toLocaleString(undefined, {
                                            dateStyle: "medium",
                                            timeStyle: "short",
                                        }), " ", "| ", attachment.uploadedBy] })] }), _jsxs("div", { className: "flex items-center gap-1", children: [_jsxs(Button, { type: "button", size: "sm", variant: "ghost", onClick: () => handleDownloadAttachment(attachment.attachmentId), className: "text-neutral-grey-50 hover:text-neutral-grey-100 h-7 px-2 text-xs", children: [_jsx(Download, { className: "mr-1 h-3 w-3" }), "Download"] }), canEdit ? (_jsxs(Button, { type: "button", size: "sm", variant: "ghost", onClick: () => void handleDeleteAttachment(attachment), disabled: deletingAttachmentId === attachment.attachmentId, className: "text-neutral-grey-50 hover:bg-neutral-grey-5 hover:text-neutral-grey-50 h-7 px-2 text-xs", children: [_jsx(DeleteIcon, { size: "sm", className: "mr-1" }), "Delete"] })) : null] })] }, attachment.attachmentId))) }))] }));
}
//# sourceMappingURL=TaskAttachmentsSection.js.map