"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Upload, Image as ImageIcon, Trash2, Star } from "lucide-react";
import { Button } from "@open-mercato/ui/primitives/button";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { cn } from "@open-mercato/shared/lib/utils";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { buildAttachmentImageUrl, slugifyAttachmentFileName } from "@open-mercato/core/modules/attachments/lib/imageUrls";
function humanFileSize(size) {
  if (!Number.isFinite(size)) return `${size}`;
  const units = ["B", "KB", "MB", "GB"];
  let idx = 0;
  let value = size;
  while (value >= 1024 && idx < units.length - 1) {
    value /= 1024;
    idx++;
  }
  return `${value.toFixed(idx === 0 ? 0 : 1)} ${units[idx]}`;
}
function ProductMediaManager({
  entityId,
  draftRecordId,
  items,
  defaultMediaId,
  onItemsChange,
  onDefaultChange
}) {
  const t = useT();
  const fileInputRef = React.useRef(null);
  const [error, setError] = React.useState(null);
  const [isUploading, setUploading] = React.useState(false);
  const [isDragOver, setDragOver] = React.useState(false);
  const acceptFiles = React.useCallback(
    async (files) => {
      if (!files || !files.length || !draftRecordId) return;
      setError(null);
      setUploading(true);
      let nextItems = items;
      let defaultId = defaultMediaId;
      try {
        for (const file of Array.from(files)) {
          if (!file.type.startsWith("image/")) {
            setError(t("catalog.products.media.errors.imagesOnly", "Only image files are supported."));
            continue;
          }
          const fd = new FormData();
          fd.set("entityId", entityId);
          fd.set("recordId", draftRecordId);
          fd.set("file", file);
          const call = await apiCall(
            "/api/attachments",
            { method: "POST", body: fd },
            { fallback: null }
          );
          if (!call.ok || !call.result?.item) {
            const message = call.result?.error ?? t("catalog.products.media.errors.uploadFailed", "Upload failed.");
            setError(message);
            break;
          }
          const existingIds = new Set(nextItems.map((entry) => entry.id));
          if (existingIds.has(call.result.item.id)) continue;
          const slug = slugifyAttachmentFileName(call.result.item.fileName);
          const uploaded = {
            ...call.result.item,
            thumbnailUrl: call.result.item.thumbnailUrl ?? buildAttachmentImageUrl(call.result.item.id, { width: 360, height: 360, slug })
          };
          nextItems = [...nextItems, uploaded];
          if (!defaultId) {
            defaultId = uploaded.id;
          }
        }
        if (nextItems !== items) {
          onItemsChange(nextItems);
        }
        if (!defaultMediaId && defaultId) {
          onDefaultChange(defaultId);
        }
      } finally {
        setUploading(false);
        if (fileInputRef.current) {
          fileInputRef.current.value = "";
        }
      }
    },
    [defaultMediaId, draftRecordId, entityId, items, onDefaultChange, onItemsChange, t]
  );
  const handleRemove = React.useCallback(
    async (attachmentId) => {
      setError(null);
      const call = await apiCall(
        `/api/attachments?id=${encodeURIComponent(attachmentId)}`,
        { method: "DELETE" },
        { fallback: null }
      );
      if (!call.ok) {
        setError(call.result?.error ?? t("catalog.products.media.errors.deleteFailed", "Failed to delete media."));
        return;
      }
      const next = items.filter((item) => item.id !== attachmentId);
      onItemsChange(next);
      if (defaultMediaId === attachmentId) {
        onDefaultChange(next[0]?.id ?? null);
      }
    },
    [defaultMediaId, items, onDefaultChange, onItemsChange, t]
  );
  const onDrop = React.useCallback(
    (event) => {
      event.preventDefault();
      event.stopPropagation();
      setDragOver(false);
      void acceptFiles(event.dataTransfer?.files ?? null);
    },
    [acceptFiles]
  );
  const onDragOver = React.useCallback((event) => {
    event.preventDefault();
    event.stopPropagation();
    setDragOver(true);
  }, []);
  const onDragLeave = React.useCallback((event) => {
    event.preventDefault();
    event.stopPropagation();
    setDragOver(false);
  }, []);
  const pickFiles = React.useCallback(() => {
    fileInputRef.current?.click();
  }, []);
  return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsx("label", { className: "text-sm font-medium", children: t("catalog.products.media.label", "Media") }),
    /* @__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,
        onDragOver,
        onDragLeave,
        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("catalog.products.media.dropHint", "Drag and drop images here or click to upload.") }),
          /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", className: "mt-4", onClick: pickFiles, disabled: isUploading, children: isUploading ? t("catalog.products.media.uploading", "Uploading\u2026") : t("catalog.products.media.choose", "Choose files") }),
          /* @__PURE__ */ jsx(
            "input",
            {
              ref: fileInputRef,
              type: "file",
              accept: "image/*",
              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,
    items.length ? /* @__PURE__ */ jsx("div", { className: "grid grid-cols-2 gap-3 sm:grid-cols-3", children: items.map((item) => {
      const isDefault = defaultMediaId === item.id;
      const slug = slugifyAttachmentFileName(item.fileName);
      const thumbnail = item.thumbnailUrl || buildAttachmentImageUrl(item.id, { width: 360, height: 360, slug });
      return /* @__PURE__ */ jsxs("div", { className: "flex flex-col rounded-md border bg-card", children: [
        /* @__PURE__ */ jsxs("div", { className: "relative aspect-square overflow-hidden rounded-t-md bg-muted", children: [
          thumbnail ? /* @__PURE__ */ jsx("img", { src: thumbnail, alt: item.fileName, className: "h-full w-full object-cover" }) : /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center text-muted-foreground", children: /* @__PURE__ */ jsx(ImageIcon, { className: "h-8 w-8" }) }),
          /* @__PURE__ */ jsxs("div", { className: "absolute right-1 top-1 flex gap-1", children: [
            /* @__PURE__ */ jsx(
              Button,
              {
                type: "button",
                variant: isDefault ? "default" : "secondary",
                size: "icon",
                className: cn("h-7 w-7", isDefault ? "" : "opacity-80"),
                onClick: () => onDefaultChange(item.id),
                children: /* @__PURE__ */ jsx(Star, { className: "h-3.5 w-3.5" })
              }
            ),
            /* @__PURE__ */ jsx(Button, { type: "button", variant: "secondary", size: "icon", className: "h-7 w-7", onClick: () => void handleRemove(item.id), children: /* @__PURE__ */ jsx(Trash2, { className: "h-3.5 w-3.5" }) })
          ] })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "p-2", children: [
          /* @__PURE__ */ jsx("p", { className: "line-clamp-1 text-sm font-medium", children: item.fileName }),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: humanFileSize(item.fileSize) }),
          isDefault ? /* @__PURE__ */ jsx("p", { className: "text-xs font-semibold text-primary", children: t("catalog.products.media.default", "Default preview") }) : null
        ] })
      ] }, item.id);
    }) }) : /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("catalog.products.media.empty", "No media uploaded yet.") })
  ] });
}
export {
  ProductMediaManager
};
//# sourceMappingURL=ProductMediaManager.js.map
