"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Upload, Trash2 } from "lucide-react";
import { Button } from "../../primitives/button.js";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { cn } from "@open-mercato/shared/lib/utils";
import { AttachmentVisualPreview, formatAttachmentFileSize } from "./AttachmentVisualPreview.js";
import { AttachmentDeleteDialog } from "./AttachmentDeleteDialog.js";
import { AttachmentMetadataDialog } from "./AttachmentMetadataDialog.js";
import { ComponentReplacementHandles } from "@open-mercato/shared/modules/widgets/component-registry";
import { useRegisteredComponent } from "../injection/useRegisteredComponent.js";
function AttachmentsSectionImpl({
  entityId,
  recordId,
  title,
  description,
  className,
  showHeader = true,
  compact = false,
  onChanged
}) {
  const t = useT();
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [isUploading, setIsUploading] = React.useState(false);
  const [isDragOver, setIsDragOver] = React.useState(false);
  const [metadataOpen, setMetadataOpen] = React.useState(false);
  const [selectedItem, setSelectedItem] = React.useState(null);
  const [deleteOpen, setDeleteOpen] = React.useState(false);
  const [deleteTarget, setDeleteTarget] = React.useState(null);
  const fileInputRef = React.useRef(null);
  const load = React.useCallback(async () => {
    if (!recordId) return;
    setLoading(true);
    setError(null);
    try {
      const call = await apiCall(
        `/api/attachments?entityId=${encodeURIComponent(entityId)}&recordId=${encodeURIComponent(recordId)}`,
        void 0,
        { fallback: { items: [] } }
      );
      if (!call.ok) {
        const message = call.result?.error || t("attachments.library.errors.load", "Failed to load attachments.");
        throw new Error(message);
      }
      const payload = call.result ?? { items: [] };
      setItems(Array.isArray(payload.items) ? payload.items : []);
    } catch (err) {
      setError(err?.message || t("attachments.library.errors.load", "Failed to load attachments."));
    } finally {
      setLoading(false);
    }
  }, [entityId, recordId, t]);
  React.useEffect(() => {
    if (recordId) {
      void load();
    } else {
      setItems([]);
      setError(null);
    }
  }, [load, recordId]);
  const acceptFiles = React.useCallback(
    async (files) => {
      if (!files || !files.length || !recordId) return;
      setError(null);
      setIsUploading(true);
      try {
        for (const file of Array.from(files)) {
          const fd = new FormData();
          fd.set("entityId", entityId);
          fd.set("recordId", recordId);
          fd.set("file", file);
          const call = await apiCall(
            "/api/attachments",
            { method: "POST", body: fd },
            { fallback: null }
          );
          if (!call.ok) {
            const message = call.result?.error || t("attachments.library.upload.failed", "Upload failed.");
            throw new Error(message);
          }
        }
        await load();
        onChanged?.();
      } catch (err) {
        setError(err?.message || t("attachments.library.upload.failed", "Upload failed."));
      } finally {
        setIsUploading(false);
        if (fileInputRef.current) {
          fileInputRef.current.value = "";
        }
      }
    },
    [entityId, load, onChanged, recordId, t]
  );
  const handleDrop = React.useCallback(
    (event) => {
      event.preventDefault();
      event.stopPropagation();
      setIsDragOver(false);
      void acceptFiles(event.dataTransfer?.files ?? null);
    },
    [acceptFiles]
  );
  const handleDragOver = React.useCallback((event) => {
    event.preventDefault();
    event.stopPropagation();
    setIsDragOver(true);
  }, []);
  const handleDragLeave = React.useCallback((event) => {
    event.preventDefault();
    event.stopPropagation();
    setIsDragOver(false);
  }, []);
  const openMetadataDialog = React.useCallback((item) => {
    setSelectedItem(item);
    setMetadataOpen(true);
  }, []);
  const openDeleteDialog = React.useCallback((item) => {
    setDeleteTarget(item);
    setDeleteOpen(true);
  }, []);
  const handleDelete = React.useCallback(async () => {
    if (!deleteTarget) return;
    try {
      const call = await apiCall(
        `/api/attachments?id=${encodeURIComponent(deleteTarget.id)}`,
        { method: "DELETE" }
      );
      if (!call.ok) {
        const message = call.result?.error || t("attachments.library.errors.delete", "Failed to delete attachment.");
        throw new Error(message);
      }
      setDeleteOpen(false);
      setDeleteTarget(null);
      await load();
      onChanged?.();
    } catch (err) {
      setError(err?.message || t("attachments.library.errors.delete", "Failed to delete attachment."));
    }
  }, [deleteTarget, load, onChanged, t]);
  const handleMetadataSave = React.useCallback(
    async (id, payload) => {
      const body = {
        tags: payload.tags,
        assignments: payload.assignments
      };
      if (payload.customFields && Object.keys(payload.customFields).length) {
        body.customFields = payload.customFields;
      }
      const call = await apiCall(`/api/attachments/library/${encodeURIComponent(id)}`, {
        method: "PATCH",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(body)
      });
      if (!call.ok) {
        const message = call.result?.error || t("attachments.library.metadata.error", "Failed to update metadata.");
        throw new Error(message);
      }
      setMetadataOpen(false);
      await load();
      onChanged?.();
    },
    [load, onChanged, t]
  );
  const sectionTitle = title ?? t("attachments.library.title", "Attachments");
  const sectionDescription = description ?? t("attachments.library.description", "Browse, tag, and manage every file stored in this workspace.");
  return /* @__PURE__ */ jsxs("div", { className: cn("space-y-4", className), children: [
    showHeader ? /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
      /* @__PURE__ */ jsx("div", { className: "text-base font-medium", children: sectionTitle }),
      /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: sectionDescription })
    ] }) : null,
    !recordId ? /* @__PURE__ */ jsx("div", { className: "rounded-md border border-dashed border-border/70 px-4 py-6 text-sm text-muted-foreground", children: t("attachments.library.upload.saveFirst", "Save the record before uploading files.") }) : /* @__PURE__ */ jsxs(
      "div",
      {
        className: cn(
          "flex flex-col items-center justify-center rounded-lg border border-dashed p-6 text-center transition-colors",
          isDragOver ? "border-primary bg-primary/5" : "border-muted-foreground/30"
        ),
        onDrop: handleDrop,
        onDragOver: handleDragOver,
        onDragLeave: handleDragLeave,
        role: "presentation",
        children: [
          /* @__PURE__ */ jsx(Upload, { className: "mx-auto h-6 w-6 text-muted-foreground" }),
          /* @__PURE__ */ jsx("p", { className: "mt-2 text-sm text-muted-foreground", children: t("attachments.library.upload.dropHint", "Drag and drop files here or click to upload.") }),
          /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", className: "mt-4", onClick: () => fileInputRef.current?.click(), disabled: isUploading, children: isUploading ? t("attachments.library.upload.submitting", "Uploading\u2026") : t("attachments.library.upload.choose", "Choose files") }),
          /* @__PURE__ */ jsx(
            "input",
            {
              ref: fileInputRef,
              type: "file",
              multiple: true,
              className: "hidden",
              onChange: (event) => void acceptFiles(event.target.files)
            }
          )
        ]
      }
    ),
    error ? /* @__PURE__ */ jsx("p", { className: "text-xs font-medium text-red-600", children: error }) : null,
    loading ? /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: t("attachments.library.loading", "Loading attachments\u2026") }) : items.length ? /* @__PURE__ */ jsx("div", { className: cn(
      "grid gap-3",
      compact ? "grid-cols-2 sm:grid-cols-4 lg:grid-cols-5" : "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3"
    ), children: items.map((item) => {
      return /* @__PURE__ */ jsxs(
        "button",
        {
          type: "button",
          onClick: () => openMetadataDialog(item),
          className: "group flex flex-col overflow-hidden rounded-lg border bg-card text-left cursor-pointer transition-shadow hover:shadow-sm",
          children: [
            /* @__PURE__ */ jsx(
              AttachmentVisualPreview,
              {
                fileName: item.fileName,
                mimeType: item.mimeType,
                thumbnailUrl: item.thumbnailUrl,
                className: compact ? "aspect-[2/1]" : "aspect-[4/3]",
                overlay: /* @__PURE__ */ jsx(
                  Button,
                  {
                    type: "button",
                    variant: "ghost",
                    size: "icon",
                    className: "absolute right-2 top-2 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",
                    onClick: (event) => {
                      event.stopPropagation();
                      openDeleteDialog(item);
                    },
                    children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4 text-destructive" })
                  }
                )
              }
            ),
            /* @__PURE__ */ jsxs("div", { className: cn("space-y-1", compact ? "p-2" : "p-3"), children: [
              /* @__PURE__ */ jsx("div", { className: cn("truncate font-medium", compact ? "text-xs" : "text-sm"), title: item.fileName, children: item.fileName }),
              /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: formatAttachmentFileSize(item.fileSize) })
            ] })
          ]
        },
        item.id
      );
    }) }) : /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: t("attachments.library.table.empty", "No attachments found.") }),
    /* @__PURE__ */ jsx(
      AttachmentMetadataDialog,
      {
        open: metadataOpen,
        onOpenChange: setMetadataOpen,
        item: selectedItem,
        availableTags: [],
        onSave: handleMetadataSave
      }
    ),
    /* @__PURE__ */ jsx(
      AttachmentDeleteDialog,
      {
        open: deleteOpen,
        onOpenChange: setDeleteOpen,
        fileName: deleteTarget?.fileName,
        onConfirm: handleDelete,
        isDeleting: false
      }
    )
  ] });
}
function AttachmentsSection(props) {
  const handle = ComponentReplacementHandles.section("ui.detail", "AttachmentsSection");
  const Resolved = useRegisteredComponent(
    handle,
    AttachmentsSectionImpl
  );
  return /* @__PURE__ */ jsx("div", { "data-component-handle": handle, children: /* @__PURE__ */ jsx(Resolved, { ...props }) });
}
export {
  AttachmentsSection
};
//# sourceMappingURL=AttachmentsSection.js.map
