"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useRef, useCallback } from "react";
import { useTranslations } from "next-intl";
import { UploadCloudIcon, LoaderIcon, XCircleIcon, AlertTriangleIcon } from "lucide-react";
import { Button } from "../ui/button.js";
import { Progress } from "../ui/progress.js";
import { Alert, AlertDescription } from "../ui/alert.js";
import { cn } from "../../lib/utils/index.js";
import { sel } from "../../lib/selectors/index.js";
import { useMediaUpload } from "../../hooks/useMediaUpload.js";
import { useToast } from "../../hooks/useToast.js";
function MediaUploadZone({
  onUploadComplete,
  maxSizeMB = 10,
  acceptedTypes = ["image/*", "video/*"],
  className
}) {
  const t = useTranslations("media");
  const { toast } = useToast();
  const [isDragging, setIsDragging] = useState(false);
  const [isChecking, setIsChecking] = useState(false);
  const [pendingFiles, setPendingFiles] = useState(null);
  const [duplicates, setDuplicates] = useState([]);
  const fileInputRef = useRef(null);
  const dragCounterRef = useRef(0);
  const uploadMutation = useMediaUpload();
  const checkForDuplicates = async (files) => {
    var _a;
    try {
      const res = await fetch("/api/v1/media/check-duplicates", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          files: files.map((f) => ({ filename: f.name, fileSize: f.size }))
        })
      });
      if (!res.ok) return [];
      const json = await res.json();
      return ((_a = json.data) == null ? void 0 : _a.duplicates) || [];
    } catch {
      return [];
    }
  };
  const doUpload = async (files) => {
    try {
      const result = await uploadMutation.mutateAsync(files);
      toast({
        title: t("upload.success"),
        description: files.length === 1 ? t("upload.success") : t("upload.successMultiple", { count: files.length })
      });
      onUploadComplete == null ? void 0 : onUploadComplete(result.media || []);
    } catch (error) {
      toast({
        title: t("upload.error"),
        description: error instanceof Error ? error.message : t("upload.error"),
        variant: "destructive"
      });
    }
  };
  const handleFiles = async (files) => {
    if (!files || files.length === 0) return;
    const fileArray = Array.from(files);
    const maxSizeBytes = maxSizeMB * 1024 * 1024;
    const oversizedFiles = fileArray.filter((f) => f.size > maxSizeBytes);
    if (oversizedFiles.length > 0) {
      toast({
        title: t("upload.error"),
        description: t("upload.tooLarge"),
        variant: "destructive"
      });
      return;
    }
    setIsChecking(true);
    const dupes = await checkForDuplicates(fileArray);
    setIsChecking(false);
    if (dupes.length > 0) {
      setDuplicates(dupes);
      setPendingFiles(fileArray);
      return;
    }
    await doUpload(fileArray);
  };
  const handleUploadAll = async () => {
    if (!pendingFiles) return;
    setDuplicates([]);
    const files = pendingFiles;
    setPendingFiles(null);
    await doUpload(files);
  };
  const handleSkipDuplicates = async () => {
    if (!pendingFiles) return;
    const dupeNames = new Set(duplicates.map((d) => `${d.filename}:${d.fileSize}`));
    const nonDuplicates = pendingFiles.filter((f) => !dupeNames.has(`${f.name}:${f.size}`));
    setDuplicates([]);
    setPendingFiles(null);
    if (nonDuplicates.length > 0) {
      await doUpload(nonDuplicates);
    } else {
      toast({ title: t("upload.error"), description: t("upload.duplicateFound", { count: duplicates.length }) });
    }
  };
  const handleDismissDuplicates = () => {
    setDuplicates([]);
    setPendingFiles(null);
  };
  const handleDragEnter = useCallback((e) => {
    e.preventDefault();
    e.stopPropagation();
    dragCounterRef.current++;
    if (dragCounterRef.current === 1) {
      setIsDragging(true);
    }
  }, []);
  const handleDragOver = useCallback((e) => {
    e.preventDefault();
    e.stopPropagation();
  }, []);
  const handleDragLeave = useCallback((e) => {
    e.preventDefault();
    e.stopPropagation();
    dragCounterRef.current--;
    if (dragCounterRef.current === 0) {
      setIsDragging(false);
    }
  }, []);
  const handleDrop = async (e) => {
    e.preventDefault();
    e.stopPropagation();
    dragCounterRef.current = 0;
    setIsDragging(false);
    await handleFiles(e.dataTransfer.files);
  };
  const handleFileInputChange = (e) => {
    handleFiles(e.target.files);
  };
  const handleBrowseClick = () => {
    var _a;
    (_a = fileInputRef.current) == null ? void 0 : _a.click();
  };
  const isBusy = uploadMutation.isPending || isChecking;
  return /* @__PURE__ */ jsxs("div", { className: cn("w-full space-y-3", className), children: [
    duplicates.length > 0 && /* @__PURE__ */ jsxs(Alert, { variant: "destructive", className: "border-amber-500/50 bg-amber-50 text-amber-900 dark:bg-amber-950/30 dark:text-amber-200 [&>svg]:text-amber-600", children: [
      /* @__PURE__ */ jsx(AlertTriangleIcon, { className: "h-4 w-4" }),
      /* @__PURE__ */ jsxs(AlertDescription, { className: "flex items-center justify-between gap-4", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("p", { className: "font-medium", children: t("upload.duplicateFound", { count: duplicates.length }) }),
          /* @__PURE__ */ jsx("p", { className: "text-xs mt-0.5 opacity-80", children: duplicates.map((d) => d.filename).join(", ") })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 shrink-0", children: [
          /* @__PURE__ */ jsx(
            Button,
            {
              size: "sm",
              variant: "outline",
              className: "border-amber-500/50 hover:bg-amber-100 dark:hover:bg-amber-900/30",
              onClick: handleSkipDuplicates,
              children: t("upload.duplicateSkip")
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              size: "sm",
              onClick: handleUploadAll,
              children: t("upload.duplicateUploadAll")
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              size: "sm",
              variant: "ghost",
              onClick: handleDismissDuplicates,
              children: /* @__PURE__ */ jsx(XCircleIcon, { className: "h-4 w-4" })
            }
          )
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsxs(
      "div",
      {
        "data-cy": sel("media.upload.dropzone"),
        className: cn(
          "border-2 border-dashed rounded-lg p-8 text-center transition-all duration-200",
          isDragging ? "border-primary bg-primary/5 scale-[1.01]" : "border-muted-foreground/25 hover:border-muted-foreground/50",
          isBusy && "opacity-50 pointer-events-none"
        ),
        onDragEnter: handleDragEnter,
        onDragOver: handleDragOver,
        onDragLeave: handleDragLeave,
        onDrop: handleDrop,
        children: [
          uploadMutation.isPending || isChecking ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-4", children: [
            /* @__PURE__ */ jsx(LoaderIcon, { className: "h-12 w-12 animate-spin text-primary" }),
            /* @__PURE__ */ jsxs("div", { className: "w-full max-w-xs", children: [
              /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground mb-2", children: t("upload.uploading") }),
              /* @__PURE__ */ jsx(
                Progress,
                {
                  "data-cy": sel("media.upload.progressBar"),
                  value: void 0,
                  className: "w-full"
                }
              )
            ] })
          ] }) : /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-4", children: [
            /* @__PURE__ */ jsx(UploadCloudIcon, { className: "h-12 w-12 text-muted-foreground" }),
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsxs("p", { className: "text-sm text-muted-foreground", children: [
                t("upload.dragDrop"),
                " ",
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    type: "button",
                    variant: "link",
                    className: "p-0 h-auto text-primary",
                    onClick: handleBrowseClick,
                    children: t("upload.browse")
                  }
                )
              ] }),
              /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-1", children: t("upload.maxSize", { maxSize: maxSizeMB }) })
            ] })
          ] }),
          /* @__PURE__ */ jsx(
            "input",
            {
              "data-cy": sel("media.upload.fileInput"),
              ref: fileInputRef,
              type: "file",
              multiple: true,
              accept: acceptedTypes.join(","),
              onChange: handleFileInputChange,
              className: "hidden",
              "aria-label": t("toolbar.upload")
            }
          )
        ]
      }
    )
  ] });
}
export {
  MediaUploadZone
};
