import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { Paperclip } from "lucide-react";
import { CountBadge } from "../../components/ui/badge";
import { useEditContext } from "../../editor/client/editContext";
import { deleteAttachment, getAttachmentDownloadUrl, getAttachments, uploadAttachmentFile, } from "../services/taskService";
import { TaskAttachmentDropZone } from "./TaskAttachmentDropZone";
const sectionHeadingClass = "text-xs font-medium tracking-wider text-neutral-grey-100 ";
export function TaskAttachmentsSection(props) {
    const { task, canEdit, onTaskChanged, onAttachmentsChanged, 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 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 handleAttachmentFilesAdded = useCallback(async (files) => {
        if (!task?.taskId)
            return;
        if (!files || files.length === 0)
            return;
        setUploadingAttachment(true);
        let uploaded = 0;
        try {
            for (const file of 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 (onAttachmentsChanged ?? onTaskChanged)?.();
            }
        }
        finally {
            setUploadingAttachment(false);
        }
    }, [onAttachmentsChanged, onTaskChanged, task?.taskId]);
    const handleDownloadAttachment = useCallback((attachment) => {
        const url = getAttachmentDownloadUrl(attachment.attachmentId);
        window.open(url, "_blank", "noopener,noreferrer");
    }, []);
    const loadAttachmentMarkdown = useCallback(async (attachment) => {
        const res = await fetch(getAttachmentDownloadUrl(attachment.attachmentId), { credentials: "include" });
        if (!res.ok) {
            throw new Error(`Failed to load attachment (${res.status})`);
        }
        return res.text();
    }, []);
    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 (onAttachmentsChanged ?? onTaskChanged)?.();
        }
        finally {
            setDeletingAttachmentId(null);
        }
    }, [editContext, onAttachmentsChanged, 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: [_jsx("div", { className: "flex flex-wrap items-center 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(CountBadge, { children: attachments.length })] }) }), _jsx(TaskAttachmentDropZone, { attachments: attachments, loading: attachmentsLoading, uploading: uploadingAttachment, canUpload: canEdit, deletingAttachmentId: deletingAttachmentId, onFilesAdded: handleAttachmentFilesAdded, onDownload: handleDownloadAttachment, onDelete: canEdit ? handleDeleteAttachment : undefined, onLoadMarkdown: loadAttachmentMarkdown })] }));
}
//# sourceMappingURL=TaskAttachmentsSection.js.map