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

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 _regeneratorRuntime from "@babel/runtime/regenerator";
import React, { useCallback, useEffect, useRef, useState } from "react";
import classNames from "classnames";
import { ceil } from "lodash";
import { useDropzone } from "react-dropzone";
import Bolt from "../../../../../ui/Icon/Bolt";
import Plus from "../../../../../ui/Icon/Plus";
import CssFlex from "../../../../../ui/CssFlex";
import CssGrid from "../../../../../ui/CssGrid";
import Skeleton from "../../../../../ui/Skeleton";
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 getClasses from "../styles";
import { getImageDimensions } from "../UploadImagesMenu/image";
import resizeBase64ForMaxWidthAndMaxHeight from "../UploadImagesMenu/resizer";
import CroppDialog from "../CroppDialog";
import AIFeedback from "./AIFeedback";
var mbLimit = 5.12;
var availableMimetypes = ["image/jpg", "image/png", "image/jpeg"];

var ImageSectionBody = function ImageSectionBody(props) {
  var translations = props.translations,
      typeTranslations = props.typeTranslations,
      image = props.image,
      onSelectAssets = props.onSelectAssets,
      openAssetsModal = props.openAssetsModal,
      onUpdateAsset = props.onUpdateAsset;
  var warning = props.warning,
      pressed = props.pressed,
      logo = props.logo,
      landscape = props.landscape,
      video = props.video,
      isLoading = props.isLoading,
      onUploadImage = props.onUploadImage,
      dragAndDrop = props.dragAndDrop,
      type = props.type;

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

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

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

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

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

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

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

  var _useState15 = useState([]),
      _useState16 = _slicedToArray(_useState15, 2),
      allNewFiles = _useState16[0],
      setAllNewFiles = _useState16[1];

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

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

  var idPopover = openPopover ? "simple-popover1" : undefined;
  var refLink = useRef(null);
  var refFile = useRef(null);
  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;
  var classes = getClasses({
    landscape: landscape,
    aspect: image === null || image === void 0 ? void 0 : image.aspect_ratio,
    logo: logo,
    video: video,
    hasImage: !!image
  });
  useEffect(function () {
    if (allNewFiles.length > 0 && fileIndex <= allNewFiles.length - 1 && fileIndex >= 0) {
      handleChangeFile(allNewFiles[fileIndex]);
    }
  }, [fileIndex]);

  var handleThumbClick = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(thumb) {
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              onUpdateAsset(image === null || image === void 0 ? void 0 : image.id, undefined, undefined, undefined, thumb);

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

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

  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 uploadImage = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
      var finalImage, dimensions, successCallback, errorCallback, res;
      return _regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              finalImage = "";
              setIsLoadingUpload(true);
              hideErrorInUpdateDialog();
              _context2.next = 5;
              return getImageDimensions(croppedImage.toDataURL());

            case 5:
              dimensions = _context2.sent;

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

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

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

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

            case 11:
              _context2.next = 14;
              break;

            case 13:
              finalImage = croppedImage.toDataURL();

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

            case 16:
              res = _context2.sent;
              setOpenFile(false);
              setIsLoadingUpload(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 20:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));

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

  var crop = function crop() {
    // image in dataUrl
    setCroppedImage(refFile.current.cropper.getCroppedCanvas());
  };

  var onDrop = useCallback(function (acceptedFiles) {
    // Do something with the files
    acceptedFiles.forEach(function (file) {
      var reader = new FileReader();

      reader.onabort = function () {
        return console.log("file reading was aborted");
      };

      reader.onerror = function () {
        return console.log("file reading has failed");
      };

      reader.onload = function () {
        // Base64 data is available in reader.result
        setAllNewFiles(function (prevState) {
          return [].concat(_toConsumableArray(prevState), [[{
            target: {
              result: reader.result
            }
          }, file]]);
        });
        setFileIndex(0);
      };

      reader.readAsDataURL(file);
    });
  }, []);

  var content = function content() {
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(CssGrid, {
      placeContent: "center",
      "data-warning": !image && !!warning && !!pressed,
      className: classes.stripedBorder
    }, !isLoading && !!image && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("img", {
      src: image.url,
      className: classes.image,
      alt: "logo"
    }), /*#__PURE__*/React.createElement(CssFlex, {
      gap: "sm",
      justifyContent: "space-between",
      sx: {
        padding: logo ? "sm" : "md"
      },
      className: classes.headerButtons
    }, /*#__PURE__*/React.createElement(CssFlex, {
      component: "button",
      onClick: function onClick() {
        return onSelectAssets([image.id], [], type, "unselect");
      },
      justifyContent: "center",
      alignItems: "center",
      className: classes.removeButton
    }, translations.discardButton), image.source === "ai" && /*#__PURE__*/React.createElement(CssFlex, {
      alignItems: "center",
      className: classes.iaButton
    }, /*#__PURE__*/React.createElement(Bolt, {
      color: "inherit"
    }), translations.iaIcon)), image.source === "ai" && typeof image.feedback !== "number" && /*#__PURE__*/React.createElement(AIFeedback, {
      translations: translations,
      feedback: image.feedback,
      handleThumbClick: handleThumbClick,
      showLabel: !logo || landscape
    })), !isLoading && !image && /*#__PURE__*/React.createElement(CssFlex, {
      component: "button",
      onClick: function onClick() {
        return openAssetsModal();
      },
      gap: "sm",
      justifyContent: "center",
      alignItems: "center",
      className: classes.uploadButton
    }, /*#__PURE__*/React.createElement(Plus, {
      color: "inherit"
    }), typeTranslations.noImage), isLoading && /*#__PURE__*/React.createElement(Skeleton, {
      className: classes.loadingContainer
    })), /*#__PURE__*/React.createElement(CroppDialog, {
      modal: true,
      crop: crop,
      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
    }));
  };

  if (!dragAndDrop) return content();

  var _useDropzone = useDropzone({
    onDrop: onDrop,
    noClick: true
  }),
      getRootProps = _useDropzone.getRootProps,
      getInputProps = _useDropzone.getInputProps,
      isDragActive = _useDropzone.isDragActive;

  return /*#__PURE__*/React.createElement("div", _extends({}, getRootProps(), {
    className: classNames(_defineProperty({}, classes.dragActive, isDragActive))
  }), /*#__PURE__*/React.createElement("input", getInputProps()), content());
};

export default ImageSectionBody;