"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.fileUploadVariants = exports.fileUploadTypes = exports.FileUploader = exports.FileUpload = void 0;
var _styled = _interopRequireDefault(require("@emotion/styled"));
var _react = require("react");
var _Button = require("../Buttons/Button.cjs");
var _Field = require("../Field.cjs");
var _i18n = require("../i18n.generated/i18n.cjs");
var _index = require("../icons.generated/index.cjs");
var _OdysseyDesignTokensContext = require("../OdysseyDesignTokensContext.cjs");
var _Typography = require("../Typography.cjs");
var _FileUploadIllustration = require("./FileUploadIllustration.cjs");
var _FileUploadPreview = require("./FileUploadPreview.cjs");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/*!
 * Copyright (c) 2022-present, Okta, Inc. and/or its affiliates. All rights reserved.
 * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
 *
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and limitations under the License.
 */

const fileUploadTypes = exports.fileUploadTypes = ["single", "multiple"];
const fileUploadVariants = exports.fileUploadVariants = ["button", "dragAndDrop", "dragAndDropWithIcon"];
const BaseInputWrapper = _styled.default.div({
  position: "relative",
  alignSelf: "flex-start",
  input: {
    position: "absolute",
    width: "100%",
    height: "100%",
    opacity: 0
  }
});
const InputContainer = (0, _styled.default)(BaseInputWrapper)({
  display: "flex",
  alignSelf: "unset",
  alignItems: "center",
  justifyContent: "center",
  "&:has(input:focus)": {
    borderStyle: "solid"
  }
}, ({
  hasError,
  odysseyDesignTokens
}) => ({
  padding: `${odysseyDesignTokens.Spacing6} ${odysseyDesignTokens.Spacing3}`,
  border: hasError ? `1px solid ${odysseyDesignTokens.PaletteDangerMain}` : `1px dashed ${odysseyDesignTokens.HueNeutral300}`,
  borderRadius: odysseyDesignTokens.BorderRadiusMain,
  transition: `border-color ${odysseyDesignTokens.TransitionTimingMain}, box-shadow ${odysseyDesignTokens.TransitionTimingMain}`,
  "&:hover": {
    borderColor: odysseyDesignTokens.HueNeutral700
  },
  "&:has(input:focus)": {
    borderColor: odysseyDesignTokens.FocusOutlineColorPrimary,
    boxShadow: `0 0 0 1px ${odysseyDesignTokens.FocusOutlineColorPrimary}`,
    outline: `${odysseyDesignTokens.FocusOutlineWidthMain} ${odysseyDesignTokens.FocusOutlineStyle} transparent`,
    outlineOffset: odysseyDesignTokens.FocusOutlineOffsetTight
  },
  "&:has(input:disabled)": {
    backgroundColor: odysseyDesignTokens.HueNeutral50,
    border: `1px solid ${odysseyDesignTokens.BorderColorDisabled}`,
    color: odysseyDesignTokens.TypographyColorDisabled,
    "&:hover": {
      borderColor: odysseyDesignTokens.BorderColorDisabled
    }
  }
}));
const ButtonAndInfoContainer = _styled.default.div({
  display: "flex",
  flexDirection: "column",
  alignItems: "center",
  justifyContent: "center"
});
const CenterAlignedSupportText = _styled.default.div({
  textAlign: "center"
});
const FileUploader = ({
  acceptedFileTypes,
  errorMessage,
  id,
  isDisabled = false,
  isFullWidth,
  isOptional,
  hint,
  HintLinkComponent,
  label,
  onChange,
  type,
  variant
}) => {
  const odysseyDesignTokens = (0, _OdysseyDesignTokensContext.useOdysseyDesignTokens)();
  const {
    t
  } = (0, _i18n.useTranslation)();
  const inputRef = (0, _react.useRef)(null);
  const [filesToUpload, setFilesToUpload] = (0, _react.useState)([]);
  (0, _react.useEffect)(() => {
    onChange(filesToUpload);
  }, [filesToUpload, onChange]);
  const updateFilesToUpload = (0, _react.useCallback)(event => {
    const {
      files
    } = event.target;
    if (files && files.length > 0) {
      const mergedFiles = type === "multiple" ? filesToUpload.concat(Array.from(files)) : Array.from(files).slice();
      setFilesToUpload(mergedFiles);
    }
    event.target.value = "";
  }, [type, filesToUpload]);
  const triggerFileInputClick = (0, _react.useCallback)(() => {
    inputRef.current?.click();
  }, [inputRef]);
  const removeFileFromFilesToUploadList = (0, _react.useCallback)(name => {
    const deletedFileFilteredOut = filesToUpload.filter(file => file.name !== name);
    setFilesToUpload(deletedFileFilteredOut);
  }, [filesToUpload]);
  const renderFileInput = (0, _react.useCallback)(({
    ariaDescribedBy,
    errorMessageElementId,
    id,
    labelElementId
  }) => {
    const acceptedFileTypesAsString = acceptedFileTypes?.join(",");
    const Input = () => (0, _jsxRuntime.jsx)("input", {
      accept: acceptedFileTypesAsString,
      "aria-describedby": ariaDescribedBy,
      "aria-errormessage": errorMessageElementId,
      "aria-labelledby": labelElementId,
      disabled: isDisabled,
      id: id,
      multiple: type === "multiple",
      onChange: updateFilesToUpload,
      ref: inputRef,
      title: "",
      type: "file"
    });
    if (variant === "button") {
      return (0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
        children: (0, _jsxRuntime.jsxs)(BaseInputWrapper, {
          children: [(0, _jsxRuntime.jsx)(Input, {}), (0, _jsxRuntime.jsx)(_Button.Button, {
            isDisabled: isDisabled,
            label: t("fileupload.button.text"),
            onClick: triggerFileInputClick,
            startIcon: (0, _jsxRuntime.jsx)(_index.UploadIcon, {}),
            variant: "secondary"
          })]
        })
      });
    }
    return (0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
      children: (0, _jsxRuntime.jsxs)(InputContainer, {
        hasError: Boolean(errorMessage),
        odysseyDesignTokens: odysseyDesignTokens,
        children: [(0, _jsxRuntime.jsx)(Input, {}), (0, _jsxRuntime.jsxs)(ButtonAndInfoContainer, {
          children: [variant === "dragAndDropWithIcon" && (0, _jsxRuntime.jsx)(_FileUploadIllustration.FileUploadIllustration, {}), (0, _jsxRuntime.jsx)(CenterAlignedSupportText, {
            children: (0, _jsxRuntime.jsx)(_Typography.Support, {
              color: "textSecondary",
              children: t("fileupload.prompt.text")
            })
          }), (0, _jsxRuntime.jsx)(_Button.Button, {
            isDisabled: isDisabled,
            label: t("fileupload.button.text"),
            onClick: triggerFileInputClick,
            startIcon: (0, _jsxRuntime.jsx)(_index.UploadIcon, {}),
            variant: "secondary"
          })]
        })]
      })
    });
  }, [acceptedFileTypes, errorMessage, isDisabled, inputRef, odysseyDesignTokens, triggerFileInputClick, t, type, updateFilesToUpload, variant]);
  return (0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
    children: [(0, _jsxRuntime.jsx)(_Field.Field, {
      errorMessage: errorMessage,
      fieldType: "single",
      hasVisibleLabel: true,
      hint: hint,
      HintLinkComponent: HintLinkComponent,
      id: id,
      isDisabled: isDisabled,
      isFullWidth: isFullWidth && variant !== "button",
      isOptional: isOptional,
      label: label,
      renderFieldComponent: renderFileInput
    }), filesToUpload.length > 0 && (0, _jsxRuntime.jsx)(_FileUploadPreview.FileUploadPreview, {
      fileNames: filesToUpload.map(file => file.name),
      isDisabled: isDisabled,
      onFileRemove: removeFileFromFilesToUploadList
    })]
  });
};
const MemoizedFileUploader = exports.FileUploader = exports.FileUpload = (0, _react.memo)(FileUploader);
MemoizedFileUploader.displayName = "FileUploader";
//# sourceMappingURL=FileUploader.cjs.map