"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { z } from "zod";
import { Button } from "../../primitives/button.js";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@open-mercato/ui/primitives/dialog";
import { Input } from "@open-mercato/ui/primitives/input";
import { TagsInput } from "@open-mercato/ui/backend/inputs/TagsInput";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { collectCustomFieldValues } from "@open-mercato/ui/backend/utils/customFieldValues";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { cn } from "@open-mercato/shared/lib/utils";
import { Copy, Download, Trash2 } from "lucide-react";
import { AttachmentContentPreview } from "@open-mercato/core/modules/attachments/components/AttachmentContentPreview";
import { buildAttachmentFileUrl, buildAttachmentImageUrl, slugifyAttachmentFileName } from "@open-mercato/core/modules/attachments/lib/imageUrls";
import { E } from "@open-mercato/core/generated-shims/entities.ids.generated";
function formatFileSize(value) {
  if (!Number.isFinite(value)) return "\u2014";
  if (value <= 0) return "0 B";
  const units = ["B", "KB", "MB", "GB", "TB"];
  let idx = 0;
  let current = value;
  while (current >= 1024 && idx < units.length - 1) {
    current /= 1024;
    idx += 1;
  }
  return `${current.toFixed(idx === 0 ? 0 : 1)} ${units[idx]}`;
}
const ENV_APP_URL = (process.env.NEXT_PUBLIC_APP_URL || "").replace(/\/$/, "");
function resolveAbsoluteUrl(path) {
  if (!path) return path;
  if (/^https?:\/\//i.test(path)) return path;
  const base = ENV_APP_URL || (typeof window !== "undefined" && window.location?.origin ? window.location.origin : "");
  if (!base) return path;
  const normalizedBase = base.replace(/\/$/, "");
  return `${normalizedBase}${path.startsWith("/") ? path : `/${path}`}`;
}
function normalizeCustomFieldSubmitValue(value) {
  if (Array.isArray(value)) {
    return value.filter((entry) => entry !== void 0);
  }
  if (value === void 0) return null;
  return value;
}
function prepareAssignmentsForForm(assignments) {
  return (assignments ?? []).map((assignment) => ({
    type: assignment.type,
    id: assignment.id,
    href: assignment.href ?? "",
    label: assignment.label ?? ""
  }));
}
function prefixCustomFieldValues(values) {
  if (!values) return {};
  const prefixed = {};
  Object.entries(values).forEach(([key, value]) => {
    if (!key) return;
    if (key.startsWith("cf_")) {
      prefixed[key] = value;
    } else if (key.startsWith("cf:")) {
      const normalized = key.slice(3);
      if (normalized) prefixed[`cf_${normalized}`] = value;
    } else {
      prefixed[`cf_${key}`] = value;
    }
  });
  return prefixed;
}
function AssignmentInputRow({
  value,
  onChange,
  labels,
  disabled,
  onRemove
}) {
  return /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-2 rounded-md border border-border/70 bg-background p-3 sm:grid-cols-2 lg:grid-cols-[1.2fr_1.2fr_1.6fr_1fr_auto]", children: [
    /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
      /* @__PURE__ */ jsx("label", { className: "text-xs font-medium", children: labels.type }),
      /* @__PURE__ */ jsx(
        Input,
        {
          value: value.type,
          onChange: (event) => onChange({ ...value, type: event.target.value }),
          placeholder: "catalog.product",
          disabled
        }
      )
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
      /* @__PURE__ */ jsx("label", { className: "text-xs font-medium", children: labels.id }),
      /* @__PURE__ */ jsx(
        Input,
        {
          value: value.id,
          onChange: (event) => onChange({ ...value, id: event.target.value }),
          placeholder: "Record ID",
          disabled
        }
      )
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
      /* @__PURE__ */ jsx("label", { className: "text-xs font-medium", children: labels.href }),
      /* @__PURE__ */ jsx(
        Input,
        {
          value: value.href ?? "",
          onChange: (event) => onChange({ ...value, href: event.target.value }),
          placeholder: "https://",
          disabled
        }
      )
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
      /* @__PURE__ */ jsx("label", { className: "text-xs font-medium", children: labels.label }),
      /* @__PURE__ */ jsx(
        Input,
        {
          value: value.label ?? "",
          onChange: (event) => onChange({ ...value, label: event.target.value }),
          placeholder: "Optional label",
          disabled
        }
      )
    ] }),
    /* @__PURE__ */ jsx("div", { className: "flex items-end", children: /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", size: "icon", onClick: onRemove, disabled, children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" }) }) })
  ] });
}
function AttachmentAssignmentsEditor({
  value,
  onChange,
  labels,
  disabled
}) {
  const handleAdd = React.useCallback(() => {
    onChange([...value, { type: "", id: "", href: "", label: "" }]);
  }, [onChange, value]);
  const handleChange = React.useCallback(
    (index, next) => {
      const draft = [...value];
      draft[index] = next;
      onChange(draft);
    },
    [onChange, value]
  );
  const handleRemove = React.useCallback(
    (index) => {
      const next = value.filter((_, idx) => idx !== index);
      onChange(next);
    },
    [onChange, value]
  );
  return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
    /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
      /* @__PURE__ */ jsx("div", { className: "text-sm font-medium", children: labels.title }),
      /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: labels.description })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "space-y-2", children: value.length ? value.map((entry, idx) => /* @__PURE__ */ jsx(
      AssignmentInputRow,
      {
        value: entry,
        labels,
        disabled,
        onChange: (next) => handleChange(idx, next),
        onRemove: () => handleRemove(idx)
      },
      `${entry.type}-${entry.id}-${idx}`
    )) : /* @__PURE__ */ jsx("div", { className: "rounded-md border border-dashed border-border/70 px-3 py-4 text-xs text-muted-foreground", children: labels.description }) }),
    /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: handleAdd, disabled, children: labels.add })
  ] });
}
function AttachmentMetadataDialog({ open, onOpenChange, item, availableTags, onSave }) {
  const t = useT();
  const [sizeWidth, setSizeWidth] = React.useState("");
  const [sizeHeight, setSizeHeight] = React.useState("");
  const [imageTab, setImageTab] = React.useState("preview");
  const [initialValues, setInitialValues] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [loadError, setLoadError] = React.useState(null);
  const [extractedContent, setExtractedContent] = React.useState(null);
  React.useEffect(() => {
    if (!open || !item) {
      setInitialValues(null);
      setLoadError(null);
      setLoading(false);
      setImageTab("preview");
      setExtractedContent(null);
      return;
    }
    let cancelled = false;
    setLoading(true);
    setLoadError(null);
    setSizeWidth("");
    setSizeHeight("");
    setImageTab("preview");
    setInitialValues({
      id: item.id,
      tags: item.tags ?? [],
      assignments: prepareAssignmentsForForm(item.assignments)
    });
    setExtractedContent(item.content && item.content.trim() ? item.content : null);
    const loadDetails = async () => {
      try {
        const call = await apiCall(`/api/attachments/library/${encodeURIComponent(item.id)}`);
        if (!call.ok || !call.result?.item) {
          const message = call.result?.error || t("attachments.library.metadata.error", "Failed to update metadata.");
          throw new Error(message);
        }
        const payload = call.result.item;
        const prefixedCustom = prefixCustomFieldValues(payload.customFields);
        if (!cancelled) {
          setInitialValues({
            id: payload.id,
            tags: Array.isArray(payload.tags) ? payload.tags : [],
            assignments: prepareAssignmentsForForm(payload.assignments ?? item.assignments),
            ...prefixedCustom
          });
          const nextContent = typeof payload.content === "string" && payload.content.trim() ? payload.content : null;
          setExtractedContent(nextContent);
        }
      } catch (err) {
        if (!cancelled) {
          const message = err?.message || t("attachments.library.metadata.loadError", "Failed to load attachment metadata.");
          setLoadError(message);
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    };
    void loadDetails();
    return () => {
      cancelled = true;
    };
  }, [item, open, t]);
  const isImage = React.useMemo(() => Boolean(item?.mimeType?.toLowerCase().startsWith("image/")), [item]);
  const previewUrl = React.useMemo(() => {
    if (!item) return null;
    return item.thumbnailUrl ?? buildAttachmentImageUrl(item.id, {
      width: 320,
      height: 320,
      slug: slugifyAttachmentFileName(item.fileName)
    });
  }, [item]);
  const downloadUrl = React.useMemo(() => {
    if (!item) return null;
    const original = buildAttachmentFileUrl(item.id, { download: true });
    return resolveAbsoluteUrl(original);
  }, [item]);
  const assignmentLabels = React.useMemo(
    () => ({
      title: t("attachments.library.metadata.assignments.title", "Assignments"),
      description: t(
        "attachments.library.metadata.assignments.description",
        "Add the records this attachment belongs to with optional links."
      ),
      type: t("attachments.library.metadata.assignments.type", "Type"),
      id: t("attachments.library.metadata.assignments.id", "Record ID"),
      href: t("attachments.library.metadata.assignments.href", "Link"),
      label: t("attachments.library.metadata.assignments.label", "Label"),
      add: t("attachments.library.metadata.assignments.add", "Add assignment"),
      remove: t("attachments.library.metadata.assignments.remove", "Remove")
    }),
    [t]
  );
  const metadataFields = React.useMemo(() => {
    return [
      {
        id: "tags",
        label: t("attachments.library.table.tags", "Tags"),
        type: "custom",
        component: ({ value, setValue, disabled }) => /* @__PURE__ */ jsx(
          TagsInput,
          {
            value: Array.isArray(value) ? value : [],
            onChange: (next) => setValue(next),
            suggestions: availableTags,
            placeholder: t("attachments.library.metadata.tagsPlaceholder", "Add tags"),
            disabled: Boolean(disabled) || loading
          }
        )
      },
      {
        id: "assignments",
        label: "",
        type: "custom",
        component: ({ value, setValue, disabled }) => /* @__PURE__ */ jsx(
          AttachmentAssignmentsEditor,
          {
            value: Array.isArray(value) ? value : [],
            onChange: (next) => setValue(next),
            labels: assignmentLabels,
            disabled: Boolean(disabled) || loading
          }
        )
      }
    ];
  }, [assignmentLabels, availableTags, loading, t]);
  const metadataGroups = React.useMemo(() => {
    return [
      {
        id: "details",
        title: t("attachments.library.metadata.details", "Details"),
        column: 1,
        fields: ["tags", "assignments"]
      },
      {
        id: "customFields",
        title: t("entities.customFields.title", "Custom attributes"),
        column: 2,
        kind: "customFields"
      }
    ];
  }, [t]);
  const metadataSchema = React.useMemo(
    () => z.object({
      id: z.string().min(1),
      tags: z.array(z.string()).optional(),
      assignments: z.array(
        z.object({
          type: z.string().min(1),
          id: z.string().min(1),
          href: z.string().optional(),
          label: z.string().optional()
        })
      ).optional()
    }).passthrough(),
    []
  );
  const handleSubmit = React.useCallback(
    async (values) => {
      if (!item) return;
      const tags = Array.isArray(values.tags) ? values.tags.map((tag) => typeof tag === "string" ? tag.trim() : "").filter((tag) => tag.length > 0) : [];
      const assignments = Array.isArray(values.assignments) ? values.assignments.map((assignment) => ({
        type: assignment.type?.trim() ?? "",
        id: assignment.id?.trim() ?? "",
        href: assignment.href?.trim() || void 0,
        label: assignment.label?.trim() || void 0
      })).filter((assignment) => assignment.type && assignment.id) : [];
      const customFields = collectCustomFieldValues(values, {
        transform: (value) => normalizeCustomFieldSubmitValue(value)
      });
      const payload = {
        tags,
        assignments
      };
      if (Object.keys(customFields).length) {
        payload.customFields = customFields;
      }
      await onSave(item.id, payload);
    },
    [item, onSave]
  );
  const handleKeyDown = React.useCallback(
    (event) => {
      if (event.key === "Escape") {
        event.preventDefault();
        onOpenChange(false);
      }
    },
    [onOpenChange]
  );
  const handleCopyResizedUrl = React.useCallback(async () => {
    if (!item) return;
    const width = sizeWidth ? Number(sizeWidth) : void 0;
    const height = sizeHeight ? Number(sizeHeight) : void 0;
    if (!width && !height) {
      flash(
        t("attachments.library.metadata.resizeTool.missing", "Enter width or height to generate the URL."),
        "error"
      );
      return;
    }
    const url = buildAttachmentImageUrl(item.id, {
      width: width && width > 0 ? width : void 0,
      height: height && height > 0 ? height : void 0,
      slug: slugifyAttachmentFileName(item.fileName)
    });
    const absolute = resolveAbsoluteUrl(url);
    try {
      await navigator.clipboard.writeText(absolute);
      flash(
        t("attachments.library.metadata.resizeTool.copied", "Image URL copied."),
        "success"
      );
    } catch {
      flash(
        t("attachments.library.metadata.resizeTool.copyError", "Unable to copy URL."),
        "error"
      );
    }
  }, [item, sizeHeight, sizeWidth, t]);
  const loadMessage = t("attachments.library.metadata.loading", "Loading attachment details\u2026");
  return /* @__PURE__ */ jsx(Dialog, { open, onOpenChange, children: /* @__PURE__ */ jsxs(DialogContent, { className: "sm:max-w-2xl", onKeyDown: handleKeyDown, children: [
    /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: t("attachments.library.metadata.title", "Edit attachment metadata") }) }),
    item ? /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-3", children: [
        /* @__PURE__ */ jsxs("div", { className: "space-y-1 min-w-0", children: [
          /* @__PURE__ */ jsx("div", { className: "truncate text-sm font-medium", title: item.fileName, children: item.fileName }),
          /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground", children: [
            formatFileSize(item.fileSize),
            " ",
            "\u2022",
            " ",
            item.partitionTitle ?? item.partitionCode
          ] })
        ] }),
        downloadUrl ? /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", asChild: true, className: "shrink-0", children: /* @__PURE__ */ jsxs("a", { href: downloadUrl, download: true, children: [
          /* @__PURE__ */ jsx(Download, { className: "mr-2 h-4 w-4" }),
          t("attachments.library.metadata.download", "Download")
        ] }) }) : null
      ] }),
      isImage ? /* @__PURE__ */ jsxs("div", { className: "rounded border", children: [
        /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-4 border-b px-3 py-2 text-sm font-medium", role: "tablist", children: ["preview", "resize"].map((tab) => /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            variant: "ghost",
            size: "sm",
            role: "tab",
            "aria-selected": imageTab === tab,
            onClick: () => setImageTab(tab),
            className: cn(
              "h-auto -mb-px rounded-none border-b-2 border-transparent px-0 py-1",
              imageTab === tab ? "border-primary text-foreground" : "text-muted-foreground hover:text-foreground"
            ),
            children: tab === "preview" ? t("attachments.library.metadata.preview", "Preview") : t("attachments.library.metadata.resizeTool.title", "Generate resized URL")
          },
          tab
        )) }),
        /* @__PURE__ */ jsx("div", { className: "space-y-3 p-3", children: imageTab === "preview" ? previewUrl ? /* @__PURE__ */ jsx(
          "img",
          {
            src: previewUrl,
            alt: item.fileName,
            className: "h-48 w-full rounded-md bg-muted object-contain"
          }
        ) : /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: t("attachments.library.metadata.previewUnavailable", "Preview unavailable.") }) : /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxs("div", { className: "grid gap-2 sm:grid-cols-2", children: [
            /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
              /* @__PURE__ */ jsx("label", { className: "text-xs font-medium", htmlFor: "resize-width", children: t("attachments.library.metadata.resizeTool.width", "Width (px)") }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  id: "resize-width",
                  type: "number",
                  min: 0,
                  value: sizeWidth,
                  onChange: (event) => setSizeWidth(event.target.value),
                  disabled: loading
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
              /* @__PURE__ */ jsx("label", { className: "text-xs font-medium", htmlFor: "resize-height", children: t("attachments.library.metadata.resizeTool.height", "Height (px)") }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  id: "resize-height",
                  type: "number",
                  min: 0,
                  value: sizeHeight,
                  onChange: (event) => setSizeHeight(event.target.value),
                  disabled: loading
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "outline",
              size: "sm",
              className: "inline-flex items-center gap-2",
              onClick: () => void handleCopyResizedUrl(),
              disabled: loading,
              children: [
                /* @__PURE__ */ jsx(Copy, { className: "h-4 w-4" }),
                t("attachments.library.metadata.resizeTool.copy", "Copy URL")
              ]
            }
          )
        ] }) })
      ] }) : null,
      loadError ? /* @__PURE__ */ jsx("div", { className: "rounded border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive", children: loadError }) : null,
      /* @__PURE__ */ jsxs("div", { className: "rounded border border-border/70 bg-muted/30 px-3 py-2", children: [
        /* @__PURE__ */ jsx("div", { className: "text-xs font-semibold text-muted-foreground", children: t("attachments.library.metadata.extractedTitle", "Extracted text") }),
        /* @__PURE__ */ jsx(
          AttachmentContentPreview,
          {
            content: extractedContent,
            emptyLabel: t("attachments.library.metadata.noContent", "No text extracted"),
            showMoreLabel: t("attachments.library.metadata.showMore", "Show more"),
            showLessLabel: t("attachments.library.metadata.showLess", "Show less")
          }
        )
      ] }),
      /* @__PURE__ */ jsx(
        CrudForm,
        {
          embedded: true,
          schema: metadataSchema,
          entityId: E.attachments.attachment,
          fields: metadataFields,
          groups: metadataGroups,
          initialValues: initialValues ?? void 0,
          isLoading: !initialValues || loading,
          loadingMessage: loadMessage,
          submitLabel: t("attachments.library.metadata.save", "Save"),
          extraActions: /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: () => onOpenChange(false), children: t("attachments.library.metadata.cancel", "Cancel") }),
          onSubmit: handleSubmit
        }
      )
    ] }) : /* @__PURE__ */ jsx("div", { className: "py-8 text-center text-sm text-muted-foreground", children: t("attachments.library.metadata.noSelection", "Select an attachment to edit.") })
  ] }) });
}
export {
  AttachmentMetadataDialog
};
//# sourceMappingURL=AttachmentMetadataDialog.js.map
