import { clsx } from 'clsx';
import { useState, useRef, useEffect } from 'react';
import { useIntl } from 'react-intl';
import Button from '../button/src/Button.mjs';
import '../common/theme.mjs';
import '../common/direction.mjs';
import { Priority, ControlType } from '../common/propsValues/control.mjs';
import '../common/propsValues/breakpoint.mjs';
import '../common/propsValues/size.mjs';
import '../common/propsValues/typography.mjs';
import '../common/propsValues/width.mjs';
import '../common/propsValues/type.mjs';
import '../common/propsValues/dateMode.mjs';
import '../common/propsValues/monthFormat.mjs';
import '../common/propsValues/position.mjs';
import '../common/propsValues/layouts.mjs';
import { Status } from '../common/propsValues/status.mjs';
import '../common/propsValues/sentiment.mjs';
import '../common/propsValues/profileType.mjs';
import '../common/propsValues/variant.mjs';
import '../common/propsValues/scroll.mjs';
import '../common/propsValues/markdownNodeType.mjs';
import '../common/fileType.mjs';
import '@transferwise/icons';
import '../common/closeButton/CloseButton.messages.mjs';
import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
import { useInputAttributes } from '../inputs/contexts.mjs';
import Modal from '../modal/Modal.mjs';
import { isSizeValid } from '../upload/utils/isSizeValid/isSizeValid.mjs';
import { isTypeValid } from '../upload/utils/isTypeValid/isTypeValid.mjs';
import MESSAGES from './UploadInput.messages.mjs';
import UploadButton from './uploadButton/UploadButton.mjs';
import { imageFileTypes, DEFAULT_SIZE_LIMIT } from './uploadButton/defaults.mjs';
import UploadItem from './uploadItem/UploadItem.mjs';

function generateFileId(file) {
  const {
    name,
    size
  } = file;
  const uploadTimeStamp = new Date().getTime();
  return `${name}_${size}_${uploadTimeStamp}`;
}
/**
 * The component allows users to upload files, manage the list of uploaded files,
 * and handle file validation and deletion.
 *
 * @param {UploadInputProps} props - The properties for the UploadInput component.
 *
 * @see {@link UploadInput} for further information.
 * @see {@link https://storybook.wise.design/?path=/docs/forms-uploadinput--docs|Storybook Wise Design}
 */
const UploadInput = ({
  files = [],
  fileInputName = 'file',
  className,
  deleteConfirm,
  disabled,
  multiple = false,
  fileTypes = imageFileTypes,
  sizeLimit = DEFAULT_SIZE_LIMIT,
  description,
  onUploadFile,
  onDeleteFile,
  onValidationError,
  onFilesChange,
  onDownload,
  maxFiles,
  maxFilesErrorMessage,
  id,
  sizeLimitErrorMessage,
  uploadButtonTitle
}) => {
  const inputAttributes = useInputAttributes({
    nonLabelable: true
  });
  const [markedFileForDelete, setMarkedFileForDelete] = useState(null);
  const [mounted, setMounted] = useState(false);
  const {
    formatMessage
  } = useIntl();
  const uploadInputRef = useRef(null);
  let fileRefs = [];
  const PROGRESS_STATUSES = new Set([Status.PENDING, Status.PROCESSING]);
  const [uploadedFiles, setUploadedFiles] = useState(multiple || files.length === 0 ? files : [files[0]]);
  const uploadedFilesListReference = useRef(multiple || files.length === 0 ? files : [files[0]]);
  function updateFileList(updateFn) {
    setUploadedFiles(updateFn);
    uploadedFilesListReference.current = updateFn(uploadedFilesListReference.current);
  }
  function addFileToList(recentUploadedFile) {
    updateFileList(list => [...list, recentUploadedFile]);
  }
  function removeFileFromList(file) {
    updateFileList(list => list.filter(fileInList => file !== fileInList && file.id !== fileInList.id));
    fileRefs = fileRefs.filter(ref => ref && ref.id !== file.id);
  }
  function modifyFileInList(file, updates) {
    updateFileList(list => list.map(fileInList => fileInList === file || fileInList.id === file.id ? {
      ...file,
      ...updates
    } : fileInList));
  }
  const removeFile = async file => {
    const {
      id,
      status
    } = file;
    fileRefs = fileRefs.filter(item => item && item.id !== file.id);
    if (status === Status.FAILED) {
      removeFileFromList(file);
      return Promise.resolve();
    }
    if (onDeleteFile && id) {
      modifyFileInList(file, {
        status: Status.PROCESSING,
        error: undefined
      });
      return onDeleteFile(id).then(() => {
        removeFileFromList(file);
      }).catch(error => {
        modifyFileInList(file, {
          error: error
        });
      });
    }
  };
  function handleFileUploadFailure(file, failureMessage) {
    const {
      name
    } = file;
    const failedUpload = {
      id: generateFileId(file),
      filename: name,
      status: Status.FAILED,
      error: failureMessage
    };
    addFileToList(failedUpload);
    if (onValidationError) {
      onValidationError(failedUpload);
    }
  }
  function getNumberOfFilesUploaded() {
    const uploadInitiatedStatus = new Set([Status.SUCCEEDED, Status.PENDING]);
    const validFiles = uploadedFilesListReference.current.filter(file => file.status && uploadInitiatedStatus.has(file.status));
    return validFiles.length;
  }
  function areMaximumFilesUploadedAlready() {
    if (!maxFiles) {
      return false;
    }
    const numberOfValidFiles = getNumberOfFilesUploaded();
    return numberOfValidFiles >= maxFiles;
  }
  const addFiles = selectedFiles => {
    for (let i = 0; i < selectedFiles.length; i += 1) {
      const file = selectedFiles.item(i);
      const formData = new FormData();
      if (file) {
        const allowedFileTypes = typeof fileTypes === 'string' ? fileTypes : fileTypes.join(',');
        if (!isTypeValid(file, allowedFileTypes)) {
          handleFileUploadFailure(file, formatMessage(MESSAGES.fileTypeNotSupported));
          continue;
        }
        if (!isSizeValid(file, sizeLimit * 1000)) {
          const failureMessage = sizeLimitErrorMessage || formatMessage(MESSAGES.fileIsTooLarge);
          handleFileUploadFailure(file, failureMessage);
          continue;
        }
        if (areMaximumFilesUploadedAlready()) {
          const failureMessage = maxFilesErrorMessage || formatMessage(MESSAGES.maximumFilesAlreadyUploaded, {
            maxFilesAllowed: maxFiles
          });
          handleFileUploadFailure(file, failureMessage);
          continue;
        }
        const existingFile = uploadedFiles.find(f => f.filename === file.name);
        if (existingFile) {
          removeFileFromList(existingFile);
        }
        formData.append(fileInputName, file);
        const pendingFile = {
          id: generateFileId(file),
          filename: file.name,
          status: Status.PENDING
        };
        addFileToList(pendingFile);
        onUploadFile(formData).then(({
          id,
          url,
          error
        }) => {
          modifyFileInList(pendingFile, {
            id,
            url,
            error,
            status: Status.SUCCEEDED
          });
        }).catch(error => {
          modifyFileInList(pendingFile, {
            error: error,
            status: Status.FAILED
          });
        });
        if (!multiple) {
          break;
        }
      }
    }
  };
  useEffect(() => {
    setMounted(true);
  }, []);
  useEffect(() => {
    if (onFilesChange && mounted) {
      onFilesChange([...uploadedFiles]);
    }
  }, [onFilesChange, uploadedFiles]); // eslint-disable-line react-hooks/exhaustive-deps
  const [nextFocusable, setNextFocusable] = useState(uploadInputRef.current);
  const handleFocus = fileId => {
    fileRefs = fileRefs.filter(ref => {
      return ref && ref.id !== markedFileForDelete?.id;
    });
    const filesCount = fileRefs.length;
    let next = uploadInputRef.current;
    if (filesCount > 1) {
      const currentFileIndex = fileRefs.findIndex(file => file?.id === fileId);
      const currentFileId = fileRefs?.[currentFileIndex]?.id;
      const lastFileId = fileRefs?.[filesCount - 1]?.id;
      // if last file, select a previous one
      if (currentFileId === lastFileId) {
        next = fileRefs[filesCount - 2];
      } else {
        next = fileRefs[currentFileIndex + 1];
      }
    }
    setNextFocusable(next);
  };
  const handleRefocus = () => {
    if (nextFocusable && 'focus' in nextFocusable && typeof nextFocusable.focus === 'function') {
      setTimeout(() => {
        nextFocusable.focus();
      }, 0);
    }
  };
  return /*#__PURE__*/jsxs(Fragment, {
    children: [/*#__PURE__*/jsxs("div", {
      role: "group",
      className: clsx('np-upload-input', className, {
        disabled
      }),
      ...inputAttributes,
      children: [/*#__PURE__*/jsx("div", {
        className: "np-upload-input__section",
        "aria-live": "polite",
        "aria-relevant": "all",
        role: "region",
        children: uploadedFiles.map((file, index) => /*#__PURE__*/jsx(UploadItem, {
          ref: el => {
            if (el && el.id !== markedFileForDelete?.id && !fileRefs.some(ref => ref && ref.id === el.id) && el.status !== 'processing') {
              fileRefs.push(el);
            }
          },
          file: file,
          singleFileUpload: !multiple,
          canDelete: (!!onDeleteFile || file.status === Status.FAILED) && (!file.status || !PROGRESS_STATUSES.has(file.status)),
          onDelete: file.status === Status.FAILED ? async () => {
            await removeFile(file);
            handleRefocus();
          } : () => setMarkedFileForDelete(file),
          onDownload: onDownload,
          onFocus: () => handleFocus(file.id)
        }, file.id))
      }), (multiple || !multiple && !uploadedFiles.length) && /*#__PURE__*/jsx("div", {
        className: "np-upload-input__section np-upload-input__section--uploader",
        children: /*#__PURE__*/jsx(UploadButton, {
          ref: uploadInputRef,
          id: id,
          uploadButtonTitle: uploadButtonTitle,
          disabled: areMaximumFilesUploadedAlready() || disabled,
          multiple: multiple,
          fileTypes: fileTypes,
          sizeLimit: sizeLimit,
          description: description,
          maxFiles: maxFiles,
          withEntries: Boolean(uploadedFiles.length),
          onChange: addFiles
        })
      })]
    }), /*#__PURE__*/jsx(Modal, {
      title: deleteConfirm?.title !== undefined ? deleteConfirm.title : formatMessage(MESSAGES.deleteModalTitle),
      body: deleteConfirm?.body !== undefined ? deleteConfirm.body : formatMessage(MESSAGES.deleteModalBody),
      open: !!markedFileForDelete,
      footer: /*#__PURE__*/jsxs(Fragment, {
        children: [/*#__PURE__*/jsx(Button, {
          block: true,
          onClick: () => {
            setMarkedFileForDelete(null);
          },
          children: deleteConfirm?.cancelText || formatMessage(MESSAGES.deleteModalCancelButtonText)
        }), /*#__PURE__*/jsx(Button, {
          block: true,
          priority: Priority.SECONDARY,
          type: ControlType.NEGATIVE,
          tabIndex: markedFileForDelete ? 0 : -1,
          onClick: () => {
            if (markedFileForDelete) {
              void removeFile(markedFileForDelete);
            }
            setMarkedFileForDelete(null);
          },
          children: deleteConfirm?.confirmText || formatMessage(MESSAGES.deleteModalConfirmButtonText)
        })]
      }),
      onUnmount: handleRefocus,
      onClose: () => {
        setMarkedFileForDelete(null);
      }
    })]
  });
};

export { UploadInput as default };
//# sourceMappingURL=UploadInput.mjs.map
