import { jsxs, jsx, Fragment } from "react/jsx-runtime";
import { useRef, useState, useEffect, useCallback, useMemo } from "react";
import default_1 from "../../node_modules/@mui/icons-material/Clear.js";
import { Button } from "../Button/index.js";
import { ProgressBar } from "../ProgressBar/index.js";
import { FILE_TYPE_MIME_MAP, SIZE_CONVENTIONS } from "./FileUpload.types.js";
import { loadFileUploadAssets } from "./fileUploadAssets.loader.js";
/* empty css                       */
function FileUpload({
  fileList,
  onFileListChange,
  disabled = false,
  numberOfFiles: numFiles = 1,
  validFileTypes = [{ fileType: "xlsx", templateDownloader: void 0, typeOverride: false }],
  primaryButtonLabel,
  secondaryButtonLabel,
  onPrimaryButtonClick,
  primaryButtonProps,
  onSecondaryButtonClick,
  secondaryButtonProps,
  onClose,
  customFailedActionButton,
  className,
  "data-testid": dataTestId
}) {
  var _a;
  const wrapperRef = useRef(null);
  const fileUploadRef = useRef(null);
  const hiddenFileUploadRef = useRef(null);
  const containerRef = useRef(null);
  const [isError, setIsError] = useState(false);
  const [isDraggedOver, setIsDraggedOver] = useState(false);
  const [showDownLoadMenu, setShowDownLoadMenu] = useState(false);
  const numberOfFiles = numFiles >= 1 ? Math.floor(numFiles) : 1;
  const [assets, setAssets] = useState(null);
  useEffect(() => {
    void loadFileUploadAssets().then(setAssets);
  }, []);
  const getPreviewIconUrl = useCallback(
    (key, failed) => {
      if (!key || !assets) return void 0;
      if (failed) {
        if (key === "csv") return assets.failedCsvIconUrl;
        if (key === "xls" || key === "xlsx") return assets.failedExcelIconUrl;
        return void 0;
      }
      if (key === "csv") return assets.csvIconUrl;
      if (key === "xls" || key === "xlsx") return assets.excelIconUrl;
      if (key === "text") return assets.textIconUrl;
      return void 0;
    },
    [assets]
  );
  const currentFileType = useMemo(() => {
    return validFileTypes.flatMap((f) => FILE_TYPE_MIME_MAP[f.fileType] ?? []).join(",");
  }, [validFileTypes]);
  const onDragEnter = useCallback(() => {
    var _a2;
    setIsDraggedOver(true);
    (_a2 = wrapperRef.current) == null ? void 0 : _a2.classList.add("ia-fileUpload-dragOver");
  }, []);
  const onDragLeave = useCallback(() => {
    var _a2;
    setIsDraggedOver(false);
    (_a2 = wrapperRef.current) == null ? void 0 : _a2.classList.remove("ia-fileUpload-dragOver");
  }, []);
  const onFileDrop = useCallback(
    (e, isDragEvent = false) => {
      const newFiles = isDragEvent ? e.dataTransfer.files : e.target.files;
      if (!newFiles || newFiles.length === 0) return;
      const filesToAdd = [];
      const maxFilesToAdd = numberOfFiles - fileList.length;
      for (let i = 0; i < Math.min(newFiles.length, maxFilesToAdd); i++) {
        const newFile = newFiles[i];
        if (!newFile) continue;
        const isValid = validFileTypes.some(
          (vft) => vft.typeOverride ? vft.fileType === newFile.type : (FILE_TYPE_MIME_MAP[vft.fileType] ?? []).includes(newFile.type)
        );
        if (!isValid) {
          setIsError(true);
          continue;
        }
        const exists = fileList.some((f) => f.file.name === newFile.name && f.file.size === newFile.size) || filesToAdd.some((f) => f.file.name === newFile.name && f.file.size === newFile.size);
        if (exists) continue;
        filesToAdd.push({
          file: newFile,
          progress: 0,
          isUploadRunning: false,
          failed: false
        });
      }
      if (filesToAdd.length > 0) {
        setIsError(false);
        onFileListChange([...fileList, ...filesToAdd]);
      }
    },
    [fileList, numberOfFiles, validFileTypes, onFileListChange]
  );
  const onDrop = useCallback(
    (e) => {
      var _a2;
      e.preventDefault();
      e.stopPropagation();
      setIsDraggedOver(false);
      (_a2 = wrapperRef.current) == null ? void 0 : _a2.classList.remove("ia-fileUpload-dragOver");
      onFileDrop(e, true);
    },
    [onFileDrop]
  );
  const fileRemove = useCallback(
    (file) => {
      const idx = fileList.indexOf(file);
      if (idx === -1) return;
      const updated = [...fileList];
      updated.splice(idx, 1);
      onFileListChange(updated);
    },
    [fileList, onFileListChange]
  );
  const onUploadClick = useCallback(() => {
    var _a2;
    (_a2 = hiddenFileUploadRef.current) == null ? void 0 : _a2.click();
  }, []);
  const templateDownloader = useMemo(() => {
    if (!Array.isArray(validFileTypes)) return null;
    return validFileTypes.find((vft) => vft.templateDownloader) ?? null;
  }, [validFileTypes]);
  const handleTemplateDownloadMenu = useCallback(() => {
    setShowDownLoadMenu((prev) => !prev);
  }, []);
  const handleClickOutside = useCallback((event) => {
    const target = event.target;
    if (!target.closest(".ia-fileUpload-validFileType-container") && !target.closest(".ia-fileUpload-validFileType-menu-item")) {
      setShowDownLoadMenu(false);
    }
  }, []);
  useEffect(() => {
    if (showDownLoadMenu) {
      document.addEventListener("click", handleClickOutside);
    }
    return () => {
      document.removeEventListener("click", handleClickOutside);
    };
  }, [showDownLoadMenu, handleClickOutside]);
  return /* @__PURE__ */ jsxs(
    "div",
    {
      ref: containerRef,
      className: `ia-fileUpload-container ${className ?? ""}`.trim(),
      "data-testid": dataTestId,
      children: [
        /* @__PURE__ */ jsxs("div", { className: "ia-fileUpload-container-header", children: [
          /* @__PURE__ */ jsxs("div", { className: "ia-fileUpload-container-header-title", children: [
            /* @__PURE__ */ jsx("span", { className: "ia-fileUpload-container-header-title-primary", children: "Upload Your File" }),
            /* @__PURE__ */ jsxs("span", { className: "ia-fileUpload-container-header-title-secondary", children: [
              "You can upload up to ",
              numberOfFiles,
              " file",
              numberOfFiles > 1 ? "s" : ""
            ] })
          ] }),
          /* @__PURE__ */ jsx(
            default_1,
            {
              "aria-label": "Close",
              className: "ia-fileUpload-container-header-closeIcon",
              onClick: onClose
            }
          )
        ] }),
        /* @__PURE__ */ jsx(
          "input",
          {
            ref: hiddenFileUploadRef,
            accept: currentFileType,
            multiple: numberOfFiles > 1,
            style: { display: "none" },
            type: "file",
            value: "",
            onChange: onFileDrop
          }
        ),
        fileList.length >= numberOfFiles ? null : /* @__PURE__ */ jsx(
          "div",
          {
            ref: wrapperRef,
            className: `ia-styles ia-fileUpload ${isError ? "ia-fileUpload-error" : ""} ${disabled ? "ia-fileUpload-disabled" : ""}`,
            role: "button",
            style: {
              backgroundImage: assets && !isDraggedOver ? `url(${isError ? assets.fileUploadErrorBgUrl : assets.fileUploadBgUrl})` : void 0
            },
            tabIndex: 0,
            onClick: (e) => {
              e.preventDefault();
            },
            onDragEnter,
            onDragLeave,
            onDragOver: (e) => {
              e.preventDefault();
            },
            onDrop,
            onKeyDown: (e) => {
              e.preventDefault();
            },
            children: isDraggedOver ? /* @__PURE__ */ jsx("div", { className: "ia-fileUpload-dragOverLabel", children: "File drop in progress..." }) : /* @__PURE__ */ jsxs("div", { className: "ia-fileUpload-label", children: [
              /* @__PURE__ */ jsxs("div", { className: "ia-fileUpload-label-primary", children: [
                isError ? "File type not supported" : /* @__PURE__ */ jsx("p", { className: "ia-fileUpload-label", children: "Drag your files here or" }),
                /* @__PURE__ */ jsx(
                  "input",
                  {
                    ref: fileUploadRef,
                    accept: currentFileType,
                    multiple: numberOfFiles > 1,
                    title: (_a = fileList[0]) == null ? void 0 : _a.file.name,
                    type: "file",
                    value: "",
                    onChange: onFileDrop
                  }
                ),
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    "data-testid": "file-upload-choose-btn",
                    disabled: isDraggedOver,
                    variant: "url",
                    onClick: onUploadClick,
                    onDragEnter,
                    children: "Choose File"
                  }
                )
              ] }),
              /* @__PURE__ */ jsxs("p", { className: "ia-fileUpload-label-secondary", children: [
                "support",
                validFileTypes.length > 1 ? "s" : "",
                " ",
                validFileTypes.map((vft) => `.${vft.fileType}`).join(", ")
              ] })
            ] })
          }
        ),
        templateDownloader ? /* @__PURE__ */ jsxs("div", { className: "ia-fileUpload-validFileType", children: [
          /* @__PURE__ */ jsx("p", { className: "ia-fileUpload-label-secondary", children: "Simplify your upload!" }),
          " ",
          /* @__PURE__ */ jsxs("div", { className: "ia-fileUpload-validFileType-container", children: [
            /* @__PURE__ */ jsxs(
              "div",
              {
                role: "button",
                style: { display: "flex", alignItems: "center", gap: "4px" },
                tabIndex: 0,
                onClick: validFileTypes.length > 1 ? handleTemplateDownloadMenu : templateDownloader.templateDownloader,
                onKeyDown: (e) => {
                  var _a2;
                  if (e.key === "Enter" || e.key === " ") {
                    e.preventDefault();
                    if (validFileTypes.length > 1) {
                      handleTemplateDownloadMenu();
                    } else {
                      (_a2 = templateDownloader.templateDownloader) == null ? void 0 : _a2.call(templateDownloader);
                    }
                  }
                },
                children: [
                  /* @__PURE__ */ jsx(Button, { "data-fileUpload": "templateDownload", variant: "url", children: "Download template" }),
                  assets && /* @__PURE__ */ jsx(
                    "img",
                    {
                      alt: "",
                      className: `ia-fileUpload-validFileType-arrow ${validFileTypes.length > 1 && showDownLoadMenu ? "rotate" : ""}`,
                      src: validFileTypes.length > 1 ? assets.downArrow : assets.uploadDownloadIcon
                    }
                  )
                ]
              }
            ),
            showDownLoadMenu && /* @__PURE__ */ jsx("div", { className: "ia-fileUpload-validFileType-menu", children: validFileTypes.map((vft) => /* @__PURE__ */ jsx(
              "span",
              {
                className: "ia-fileUpload-validFileType-menu-item",
                role: "button",
                tabIndex: 0,
                onClick: () => {
                  var _a2;
                  return (_a2 = vft.templateDownloader) == null ? void 0 : _a2.call(vft);
                },
                onKeyDown: (e) => {
                  var _a2;
                  if (e.key === "Enter" || e.key === " ") {
                    e.preventDefault();
                    (_a2 = vft.templateDownloader) == null ? void 0 : _a2.call(vft);
                  }
                },
                children: `.${vft.fileType}`
              },
              vft.fileType
            )) })
          ] })
        ] }) : null,
        fileList.map((item) => {
          let fileSize = item.file.size;
          let i = 0;
          while (fileSize > 1024) {
            fileSize = fileSize / 1024;
            i += 1;
          }
          const iconKey = Object.keys(FILE_TYPE_MIME_MAP).find(
            (key) => (FILE_TYPE_MIME_MAP[key] ?? []).includes(item.file.type)
          );
          return /* @__PURE__ */ jsxs("div", { className: "ia-fileUpload-previewItem", children: [
            /* @__PURE__ */ jsxs("div", { className: "ia-fileUpload-previewItem-exceptProgress", children: [
              /* @__PURE__ */ jsxs("div", { className: "ia-fileUpload-previewItem-details", children: [
                !item.isUploadRunning && /* @__PURE__ */ jsx(
                  "div",
                  {
                    className: `ia-fileUpload-previewItemIcon ${item.failed ?? item.disabled ? "ia-fileUpload-previewItemIcon-failed" : ""} ${iconKey ?? ""}`,
                    style: {
                      backgroundImage: (() => {
                        const url = getPreviewIconUrl(iconKey, item.failed ?? false);
                        return url ? `url(${url})` : void 0;
                      })()
                    }
                  }
                ),
                /* @__PURE__ */ jsxs("div", { className: "ia-fileUpload-previewItem-info", children: [
                  /* @__PURE__ */ jsx(
                    "span",
                    {
                      className: `ia-fileUpload-previewItem-name ${item.failed ?? item.disabled ? "ia-fileUpload-previewItem-name-failed" : ""}`,
                      children: item.file.name
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    "span",
                    {
                      className: `ia-fileUpload-previewItem-size ${item.failed ? "uploadFailed" : ""} ${item.isUploadRunning ? "uploading" : ""} ${item.disabled ? "disabled" : ""}`,
                      children: item.failed ? item.failedMessage ?? "Upload failed" : `${fileSize.toFixed(0)}${SIZE_CONVENTIONS[i]}`
                    }
                  )
                ] })
              ] }),
              /* @__PURE__ */ jsx(
                "div",
                {
                  className: `ia-fileUpload-previewItem-actions ${item.failed ?? item.disabled ? "ia-fileUpload-previewItem-actions-failed" : ""}`,
                  children: item.failed ? item.failedMessage ? customFailedActionButton : /* @__PURE__ */ jsxs(Fragment, { children: [
                    assets && /* @__PURE__ */ jsx(
                      "img",
                      {
                        alt: "Remove",
                        className: "ia-fileUpload-previewItem-action removeIcon",
                        src: assets.fileUploadDownloadIcon,
                        style: item.disabled ? { opacity: 0.5, pointerEvents: "none" } : void 0,
                        onClick: () => {
                          fileRemove(item);
                        }
                      }
                    ),
                    item.onRetry && assets && /* @__PURE__ */ jsx(
                      "img",
                      {
                        alt: "Retry",
                        className: "ia-fileUpload-previewItem-action",
                        src: assets.fileUploadRetryIcon,
                        style: item.disabled ? { opacity: 0.5, pointerEvents: "none" } : void 0,
                        onClick: item.onRetry
                      }
                    )
                  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
                    item.onPause && assets && /* @__PURE__ */ jsx(
                      "img",
                      {
                        alt: "Pause",
                        className: "ia-fileUpload-previewItem-action",
                        src: assets.uploadPauseIcon,
                        style: item.disabled ? { opacity: 0.5, pointerEvents: "none" } : void 0,
                        onClick: item.onPause
                      }
                    ),
                    assets && /* @__PURE__ */ jsx(
                      "img",
                      {
                        alt: item.isUploadRunning ? "Cancel" : "Remove",
                        className: "ia-fileUpload-previewItem-action removeIcon",
                        src: item.isUploadRunning ? assets.uploadCloseIcon : assets.fileUploadDownloadIcon,
                        style: item.disabled ? { opacity: 0.5, pointerEvents: "none" } : void 0,
                        onClick: () => {
                          fileRemove(item);
                        }
                      }
                    )
                  ] })
                }
              )
            ] }),
            item.isUploadRunning && /* @__PURE__ */ jsx("div", { className: "ia-fileUpload-progress", children: /* @__PURE__ */ jsx(
              ProgressBar,
              {
                showTime: Boolean(item.timeRemaining != null),
                time: item.timeRemaining,
                value: item.progress ?? 0
              }
            ) })
          ] }, `${item.file.name}-${item.file.size}`);
        }),
        /* @__PURE__ */ jsxs("div", { className: "ia-fileUpload-actions", children: [
          secondaryButtonLabel && /* @__PURE__ */ jsx(Button, { variant: "tertiary", onClick: onSecondaryButtonClick, ...secondaryButtonProps, children: secondaryButtonLabel }),
          primaryButtonLabel && /* @__PURE__ */ jsx(
            Button,
            {
              disabled: fileList.length === 0,
              variant: "primary",
              onClick: onPrimaryButtonClick,
              ...primaryButtonProps,
              children: primaryButtonLabel
            }
          )
        ] })
      ]
    }
  );
}
FileUpload.displayName = "FileUpload";
export {
  FILE_TYPE_MIME_MAP,
  FileUpload,
  SIZE_CONVENTIONS
};
