import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _regeneratorRuntime from "@babel/runtime/regenerator";

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

import React, { useState, useRef, useEffect } from "react";
import FileReaderInput from "react-file-reader-input";
import { ceil } from "lodash";
import Menu from "../../../../../ui/next/Menu";
import MenuItem from "../../../../../ui/next/Menu/MenuItem";
import Plus from "../../../../../ui/Icon/Plus";
import Link from "../../../../../ui/Link";
import Loading from "../../../../../ui/Loading";
import Bolt from "../../../../../ui/Icon/Bolt";
import Upload from "../../../../../ui/Icon/Upload";
import styled from "../../../../../ui/styles/styled";
import { MIN_WIDTH_LANDSCAPE_IMAGE, MIN_WIDTH_SQUARE_LOGO, MIN_WIDTH_SQUARE_IMAGE, MIN_WIDTH_LANDSCAPE_LOGO, MIN_HEIGHT_LANDSCAPE_IMAGE, MIN_HEIGHT_SQUARE_LOGO, MIN_HEIGHT_SQUARE_IMAGE, MIN_HEIGHT_LANDSCAPE_LOGO } from "../../../constants";
import CroppDialog from "../CroppDialog";
import { getImageDimensions } from "./image";
import resizeBase64ForMaxWidthAndMaxHeight from "./resizer";
var availableMimetypes = ["image/jpg", "image/png", "image/jpeg"];

var UploadImagesMenu = function UploadImagesMenu(props) {
  var modal = props.modal,
      logo = props.logo,
      landscape = props.landscape,
      translations = props.translations,
      typeTranslations = props.typeTranslations;
  var onUploadImage = props.onUploadImage,
      onGetAISuggestions = props.onGetAISuggestions,
      disableAIButton = props.disableAIButton,
      onTrackEvent = props.onTrackEvent;
  var mbLimit = 5.12;

  var _useState = useState({
    logoUrl: ""
  }),
      _useState2 = _slicedToArray(_useState, 2),
      uploadDialog = _useState2[0],
      setUploadDialog = _useState2[1];

  var _useState3 = useState(""),
      _useState4 = _slicedToArray(_useState3, 2),
      croppedImage = _useState4[0],
      setCroppedImage = _useState4[1];

  var _useState5 = useState(false),
      _useState6 = _slicedToArray(_useState5, 2),
      isLoading = _useState6[0],
      setIsLoading = _useState6[1];

  var _useState7 = useState(false),
      _useState8 = _slicedToArray(_useState7, 2),
      openUrl = _useState8[0],
      setOpenUrl = _useState8[1];

  var _useState9 = useState(false),
      _useState10 = _slicedToArray(_useState9, 2),
      openFile = _useState10[0],
      setOpenFile = _useState10[1];

  var _useState11 = useState(false),
      _useState12 = _slicedToArray(_useState11, 2),
      openUploadError = _useState12[0],
      setOpenUploadError = _useState12[1];

  var _useState13 = useState(false),
      _useState14 = _slicedToArray(_useState13, 2),
      openInvalidFileFormat = _useState14[0],
      setOpenInvalidFileFormat = _useState14[1];

  var _useState15 = useState(undefined),
      _useState16 = _slicedToArray(_useState15, 2),
      base64Img = _useState16[0],
      setBase64Img = _useState16[1];

  var _useState17 = useState([]),
      _useState18 = _slicedToArray(_useState17, 2),
      allNewFiles = _useState18[0],
      setAllNewFiles = _useState18[1];

  var _useState19 = useState(-1),
      _useState20 = _slicedToArray(_useState19, 2),
      fileIndex = _useState20[0],
      setFileIndex = _useState20[1];

  var refLink = useRef(null);
  var refFile = useRef(null);

  var _useState21 = useState(false),
      _useState22 = _slicedToArray(_useState21, 2),
      openPopover = _useState22[0],
      setOpenPopover = _useState22[1];

  var type = logo ? landscape ? "landscape_logo_images" : "square_logo_images" : landscape ? "landscape_images" : "square_images";
  var minWidth = logo ? landscape ? MIN_WIDTH_LANDSCAPE_LOGO : MIN_WIDTH_SQUARE_LOGO : landscape ? MIN_WIDTH_LANDSCAPE_IMAGE : MIN_WIDTH_SQUARE_IMAGE;
  var minHeight = logo ? landscape ? MIN_HEIGHT_LANDSCAPE_LOGO : MIN_HEIGHT_SQUARE_LOGO : landscape ? MIN_HEIGHT_LANDSCAPE_IMAGE : MIN_HEIGHT_SQUARE_IMAGE;
  useEffect(function () {
    if (allNewFiles.length > 0 && fileIndex <= allNewFiles.length - 1 && fileIndex >= 0) {
      handleChangeFile(allNewFiles[fileIndex]);
    }
  }, [fileIndex]);

  var handlePopoverClose = function handlePopoverClose() {
    setOpenPopover(!openPopover);
    onGetAISuggestions();
  };

  var hideErrorInUpdateDialog = function hideErrorInUpdateDialog() {
    setOpenInvalidFileFormat(false);
    setUploadDialog(_objectSpread(_objectSpread({}, uploadDialog), {}, {
      hasError: false
    }));
  };

  var handleChangeFile = function handleChangeFile(results) {
    var _results = _slicedToArray(results, 2),
        e = _results[0],
        file = _results[1];

    var base64 = e.target.result;
    var fileSize = 4 * ceil(base64.length / 3);

    if (!!file && !!file.type) {
      if (availableMimetypes.indexOf(file.type) !== -1 && fileSize < mbLimit * 1000000) {
        setUploadDialog({
          logoUrl: ""
        });
        setBase64Img(base64);
        setOpenFile(true);
      } else {
        setUploadDialog(_objectSpread(_objectSpread({}, uploadDialog), {}, {
          logoUrl: "",
          hasError: true
        }));
        setOpenInvalidFileFormat(true);
      }
    }

    setOpenPopover(false);
    return false;
  };

  var crop = function crop() {
    // image in dataUrl
    if (openFile) {
      setCroppedImage(refFile.current.cropper.getCroppedCanvas());
    } else if (openUrl) {
      setCroppedImage(refLink.current.cropper.getCroppedCanvas());
    }
  };

  var uploadImage = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
      var finalImage, dimensions, successCallback, errorCallback, res;
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              finalImage = "";
              setIsLoading(true);
              hideErrorInUpdateDialog();
              _context.next = 5;
              return getImageDimensions(croppedImage.toDataURL());

            case 5:
              dimensions = _context.sent;

              if (!(dimensions.height < minHeight || dimensions.width < minWidth)) {
                _context.next = 13;
                break;
              }

              successCallback = function successCallback(resizedImage) {
                finalImage = resizedImage;
              };

              errorCallback = function errorCallback() {
                setOpenUploadError(true);
              };

              _context.next = 11;
              return resizeBase64ForMaxWidthAndMaxHeight(croppedImage.toDataURL(), minWidth, minHeight, successCallback, errorCallback);

            case 11:
              _context.next = 14;
              break;

            case 13:
              finalImage = croppedImage.toDataURL();

            case 14:
              _context.next = 16;
              return onUploadImage(finalImage, landscape ? logo ? 4 : 1.91 : 1, type, logo);

            case 16:
              res = _context.sent;
              setOpenFile(false);
              setOpenUrl(false);
              setIsLoading(false);

              if (fileIndex === allNewFiles.length - 1) {
                setAllNewFiles([]);
                setFileIndex(-1);
              } else {
                setFileIndex(function (prevState) {
                  return prevState + 1;
                });
              } // if (res.error) { // error during upload
              //   setOpenUploadError(true);
              // } else { // successful upload
              //   setOpenUploadError(false);
              // }


            case 21:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function uploadImage() {
      return _ref.apply(this, arguments);
    };
  }();

  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(StyledMenu, {
    trigger: /*#__PURE__*/React.createElement(StyledLink, {
      onClick: function onClick() {
        return onTrackEvent === null || onTrackEvent === void 0 ? void 0 : onTrackEvent("open_add_image");
      }
    }, /*#__PURE__*/React.createElement(Plus, {
      size: 24,
      color: "blue"
    }), typeTranslations.addImages)
  }, /*#__PURE__*/React.createElement(StyledMenuItem, {
    onSelect: handlePopoverClose,
    disabled: disableAIButton
  }, disableAIButton && /*#__PURE__*/React.createElement(Loading, {
    size: 12,
    color: "neutral"
  }), !disableAIButton && /*#__PURE__*/React.createElement(Bolt, {
    size: 24,
    color: disableAIButton ? "neutral" : "blue"
  }), translations.menu.option1), /*#__PURE__*/React.createElement(FileReaderInput, {
    multiple: true,
    id: "".concat(logo ? "logo" : "", "_").concat(landscape ? "landscape" : "", "_image_uploader"),
    onChange: function onChange(ev, results) {
      results.forEach(function (result) {
        var _result = _slicedToArray(result, 2),
            e = _result[0],
            file = _result[1];

        setAllNewFiles(function (prevState) {
          return [].concat(_toConsumableArray(prevState), [[{
            target: {
              result: e.target.result
            }
          }, file]]);
        });
        setFileIndex(0);
      });
    }
  }, /*#__PURE__*/React.createElement(StyledMenuItem, {
    onSelect: function onSelect(ev) {
      return ev.preventDefault();
    }
  }, /*#__PURE__*/React.createElement(Upload, {
    size: 24,
    color: "blue"
  }), translations.menu.option2))), /*#__PURE__*/React.createElement(CroppDialog, {
    crop: crop,
    modal: modal,
    openFile: openFile,
    onClose: function onClose() {
      setOpenFile(false);
      setFileIndex(-1);
      setAllNewFiles([]);
    },
    refFile: refFile,
    base64Img: base64Img,
    minWidth: minWidth,
    minHeight: minHeight,
    aspect: landscape ? logo ? 4 : 1.91 : 1,
    isLoading: isLoading,
    updateLogo: uploadImage,
    openInvalidFileFormat: openInvalidFileFormat,
    setOpenInvalidFileFormat: setOpenInvalidFileFormat,
    openUploadError: openUploadError,
    setOpenUploadError: setOpenUploadError,
    translations: translations
  }));
};

var StyledLink = styled(Link)(function (_ref2) {
  var theme = _ref2.theme;
  return _objectSpread(_objectSpread({}, theme.typography.variants.inputText), {}, {
    textDecoration: "underline",
    "& > svg": {
      flexShrink: 0
    }
  });
});
var StyledMenu = styled(Menu)(function () {
  return {
    padding: "16px"
  };
});
var StyledMenuItem = styled(MenuItem)(function () {
  return {
    padding: "8px"
  };
});
export default UploadImagesMenu;