"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { FieldRegistry } from "@open-mercato/ui/backend/fields/registry";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Upload } from "lucide-react";
function humanSize(n) {
  if (!Number.isFinite(n)) return String(n);
  const units = ["B", "KB", "MB", "GB"];
  let i = 0;
  let x = n;
  while (x >= 1024 && i < units.length - 1) {
    x /= 1024;
    i++;
  }
  return `${x.toFixed(i === 0 ? 0 : 1)} ${units[i]}`;
}
function buildAcceptAttribute(def) {
  if (!Array.isArray(def?.acceptExtensions) || def.acceptExtensions.length === 0) return void 0;
  const values = def.acceptExtensions.map((entry) => String(entry ?? "").trim().replace(/^\./, "")).filter((entry) => entry.length > 0);
  if (values.length === 0) return void 0;
  return values.map((entry) => `.${entry}`).join(",");
}
const AttachmentInput = ({
  entityId,
  recordId,
  def,
  disabled
}) => {
  const t = useT();
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [uploading, setUploading] = React.useState(false);
  const fileInputRef = React.useRef(null);
  const accept = React.useMemo(() => buildAcceptAttribute(def), [def]);
  const load = React.useCallback(async () => {
    if (!entityId || !recordId) return;
    try {
      setLoading(true);
      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 j = call.result ?? { items: [] };
      setItems(Array.isArray(j.items) ? j.items : []);
    } catch (error2) {
      setError(error2 instanceof Error ? error2.message : t("attachments.library.errors.load", "Failed to load attachments."));
    } finally {
      setLoading(false);
    }
  }, [entityId, recordId, t]);
  React.useEffect(() => {
    load();
  }, [load]);
  const onUpload = async (files) => {
    if (!files || !entityId || !recordId) return;
    setError(null);
    setUploading(true);
    try {
      for (const file of Array.from(files)) {
        const ext = (file.name || "").split(".").pop()?.toLowerCase() || "";
        const acceptExtensions = Array.isArray(def?.acceptExtensions) ? def.acceptExtensions : [];
        if (acceptExtensions.length > 0) {
          const allowed = new Set(acceptExtensions.map((entry) => String(entry).toLowerCase().replace(/^\./, "")));
          if (!allowed.has(ext)) {
            setError("File type not allowed");
            continue;
          }
        }
        const maxAttachmentSizeMb = typeof def?.maxAttachmentSizeMb === "number" ? def.maxAttachmentSizeMb : void 0;
        if (typeof maxAttachmentSizeMb === "number" && maxAttachmentSizeMb > 0) {
          const maxBytes = Math.floor(maxAttachmentSizeMb * 1024 * 1024);
          if (file.size > maxBytes) {
            setError(`File exceeds ${maxAttachmentSizeMb} MB limit`);
            continue;
          }
        }
        const fd = new FormData();
        fd.set("entityId", entityId);
        fd.set("recordId", recordId);
        if (def?.key) fd.set("fieldKey", String(def.key));
        fd.set("file", file);
        const call = await apiCall(
          "/api/attachments",
          { method: "POST", body: fd },
          { fallback: null }
        );
        if (!call.ok) {
          setError(call.result?.error || t("attachments.library.upload.failed", "Upload failed."));
          break;
        }
      }
      await load();
    } finally {
      setUploading(false);
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    }
  };
  return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
    !entityId || !recordId ? /* @__PURE__ */ jsx("div", { className: "rounded-md border border-dashed border-border/70 px-3 py-4 text-sm text-muted-foreground", children: t("attachments.library.upload.saveFirst", "Save the record before uploading files.") }) : /* @__PURE__ */ jsxs("div", { className: "rounded-md border border-dashed border-border/70 bg-muted/30 px-4 py-4", children: [
      /* @__PURE__ */ jsx("div", { className: "flex flex-wrap items-center gap-3", children: /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "outline",
          size: "sm",
          onClick: () => fileInputRef.current?.click(),
          disabled: disabled || uploading,
          children: [
            /* @__PURE__ */ jsx(Upload, { className: "h-4 w-4" }),
            uploading ? 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",
          accept,
          disabled: disabled || uploading,
          onChange: (event) => {
            void onUpload(event.target.files);
          }
        }
      )
    ] }),
    error ? /* @__PURE__ */ jsx("div", { className: "text-xs text-red-600", children: error }) : null,
    /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
      loading ? /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: t("attachments.library.loading", "Loading attachments\u2026") }) : null,
      items.map((it) => /* @__PURE__ */ jsxs("div", { className: "text-sm", children: [
        /* @__PURE__ */ jsx("a", { className: "underline", href: it.url, target: "_blank", rel: "noreferrer", children: it.fileName }),
        /* @__PURE__ */ jsxs("span", { className: "text-xs text-muted-foreground", children: [
          " \u2022 ",
          humanSize(it.fileSize)
        ] })
      ] }, it.id)),
      !loading && items.length === 0 ? /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: t("attachments.library.table.empty", "No attachments found.") }) : null
    ] })
  ] });
};
function AttachmentDefEditor({ def, onChange }) {
  const cfg = def?.configJson || {};
  const [maxMb, setMaxMb] = React.useState(typeof cfg.maxAttachmentSizeMb === "number" ? cfg.maxAttachmentSizeMb : "");
  const [exts, setExts] = React.useState((Array.isArray(cfg.acceptExtensions) ? cfg.acceptExtensions : []).join(", "));
  const [partition, setPartition] = React.useState(typeof cfg.partitionCode === "string" ? cfg.partitionCode : "");
  return /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-3 md:grid-cols-2", children: [
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx("label", { className: "text-xs font-medium", children: "Max file size (MB)" }),
      /* @__PURE__ */ jsx(
        Input,
        {
          type: "number",
          min: 0,
          placeholder: "e.g., 10",
          value: maxMb,
          onChange: (e) => setMaxMb(e.target.value === "" ? "" : Number(e.target.value)),
          onBlur: () => onChange({ maxAttachmentSizeMb: maxMb === "" ? void 0 : Number(maxMb) })
        }
      )
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx("label", { className: "text-xs font-medium", children: "Accepted extensions" }),
      /* @__PURE__ */ jsx(
        Input,
        {
          placeholder: "e.g., pdf, jpg, png",
          value: exts,
          onChange: (e) => setExts(e.target.value),
          onBlur: () => onChange({ acceptExtensions: exts.split(",").map((s) => s.trim()).filter(Boolean) })
        }
      ),
      /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: "Leave blank to allow any." })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx("label", { className: "text-xs font-medium", children: "Partition code" }),
      /* @__PURE__ */ jsx(
        Input,
        {
          placeholder: "e.g., productsMedia",
          value: partition,
          onChange: (e) => setPartition(e.target.value),
          onBlur: () => onChange({ partitionCode: partition.trim() || void 0 })
        }
      ),
      /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: "Configure partitions under Settings \u2192 Attachments. Leave blank for default." })
    ] })
  ] });
}
FieldRegistry.register("attachment", {
  input: (props) => /* @__PURE__ */ jsx(AttachmentInput, { entityId: props.entityId, recordId: props.recordId, def: props.def, disabled: props.disabled }),
  defEditor: (p) => /* @__PURE__ */ jsx(AttachmentDefEditor, { ...p })
});
export {
  AttachmentInput
};
//# sourceMappingURL=attachment.js.map
