import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
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; }

/* eslint-disable no-nested-ternary */
import React, { useState, useEffect } from "react";
import CssFlex from "../../../ui/CssFlex";
import Typography from "../../../ui/Typography";
import Link from "../../../ui/Link";
import getClasses from "./styles";
import Checkbox from "../../../ui/next/Checkbox";
import Dialog from "../../../ui/lab/Dialog";
import Bolt from "../../../ui/Icon/Bolt";
import Divider from "../../../ui/Divider";
import Snackbar from "../../../ui/Snackbar";

function TextAISelectors(_ref) {
  var texts = _ref.texts,
      title = _ref.title,
      selectedTexts = _ref.selectedTexts,
      _onChange = _ref.onChange;
  return /*#__PURE__*/React.createElement(CssFlex, {
    direction: "column",
    gap: "12px"
  }, /*#__PURE__*/React.createElement(Typography, {
    variant: "inputText",
    color: "neutral",
    shade: 800,
    dangerouslySetInnerHTML: {
      __html: title
    }
  }), /*#__PURE__*/React.createElement(CssFlex, {
    alignItems: "center",
    gap: "md",
    width: "100%",
    flexWrap: "wrap"
  }, texts.length !== 0 && texts.map(function (text) {
    return /*#__PURE__*/React.createElement(CssFlex, {
      key: "headline-".concat(text.id, "-assets"),
      gap: "sm",
      alignItems: "center",
      flexWrap: "wrap"
    }, /*#__PURE__*/React.createElement(Checkbox, {
      checked: selectedTexts.includes(text.text),
      onChange: function onChange() {
        return _onChange(text.text);
      }
    }, /*#__PURE__*/React.createElement(Typography, {
      component: "span",
      variant: "inputText",
      shade: selectedTexts.includes(text.text) ? 800 : 400
    }, text.text)));
  })));
}

var AIModal = function AIModal(props) {
  var translations = props.translations,
      allImages = props.allImages,
      allTexts = props.allTexts,
      maxToSelect = props.maxToSelect,
      minRequired = props.minRequired,
      section = props.section;
  var openModal = props.openModal,
      onClose = props.onClose,
      fromSnackbar = props.fromSnackbar,
      tab = props.tab,
      updateAutoCampaign = props.updateAutoCampaign;
  var classes = getClasses();

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      selectedAll = _useState2[0],
      setSelectedAll = _useState2[1];

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

  var _useState5 = useState(""),
      _useState6 = _slicedToArray(_useState5, 2),
      snackbarText = _useState6[0],
      setSnackbarText = _useState6[1];

  var descriptionText = fromSnackbar ? "description_general" : tab === "texts" ? "description_texts" : "description_visuals";
  var logos = allImages.filter(function (asset) {
    return asset.logo && (asset.aspect_ratio === 1 || asset.aspect_ratio === 4);
  });
  var squareLogos = allImages.filter(function (asset) {
    return asset.logo && asset.aspect_ratio === 1;
  });
  var landscapeLogos = allImages.filter(function (asset) {
    return asset.logo && asset.aspect_ratio === 4;
  });
  var images = allImages.filter(function (asset) {
    return !asset.logo && (asset.aspect_ratio === 1 || asset.aspect_ratio === 1.91);
  });
  var squareImages = allImages.filter(function (asset) {
    return !asset.logo && asset.aspect_ratio === 1;
  });
  var landscapeImages = allImages.filter(function (asset) {
    return !asset.logo && asset.aspect_ratio === 1.91;
  });
  var headlines = allTexts.filter(function (asset) {
    return asset.type === "headline";
  });
  var descriptions = allTexts.filter(function (asset) {
    return asset.type === "description";
  });
  var longHeadlines = allTexts.filter(function (asset) {
    return asset.type === "long_headline";
  });

  var _useState7 = useState({
    squareLogo: [],
    landscapeLogo: [],
    squareImages: [],
    landscapeImages: []
  }),
      _useState8 = _slicedToArray(_useState7, 2),
      selectedImages = _useState8[0],
      setSelectedImages = _useState8[1];

  var _useState9 = useState({
    headlines: [],
    descriptions: [],
    longHeadlines: []
  }),
      _useState10 = _slicedToArray(_useState9, 2),
      selectedTexts = _useState10[0],
      setSelectedTexts = _useState10[1];

  var _useState11 = useState(0),
      _useState12 = _slicedToArray(_useState11, 2),
      totalSelected = _useState12[0],
      setTotalSelected = _useState12[1];

  var setInitialState = function setInitialState() {
    setSelectedImages({
      squareLogo: [],
      landscapeLogo: [],
      squareImages: [],
      landscapeImages: []
    });
    setSelectedTexts({
      headlines: [],
      descriptions: [],
      longHeadlines: []
    });
    setSelectedAll(false);
  }; // Select an image from the especified type:


  var handleSelectImage = function handleSelectImage(id, type) {
    var newSelected = _objectSpread({}, selectedImages);

    var selectedType = newSelected[type];

    var updateSelectedImages = function updateSelectedImages(selected) {
      newSelected[type] = selected;
      setSelectedImages(newSelected);
    };

    var addImage = function addImage() {
      var totalImages = newSelected.landscapeImages.length + newSelected.squareImages.length;
      var otherType = type.includes("square") ? "landscapeImages" : "squareImages";
      var maxImages = maxToSelect[type] + (newSelected[otherType].length >= minRequired[otherType] ? minRequired[otherType] : 0);

      if (totalImages < maxImages) {
        updateSelectedImages([].concat(_toConsumableArray(selectedType), [id]));
      } else {
        setSnackbarText(translations.header.ai.modal.snackbar["".concat(type, "_limit_reached")]);
        setOpenSnackbar(true);
      }
    };

    if (selectedType.includes(id)) {
      updateSelectedImages(selectedType.filter(function (asset) {
        return asset !== id;
      }));
    } else if (maxToSelect[type] > selectedType.length) {
      if (type.includes("Logo")) {
        updateSelectedImages([id]);
      } else {
        addImage();
      }
    } else if (maxToSelect[type] === 1 && selectedType.length === 1) {
      updateSelectedImages([id]);
    } else {
      setSnackbarText(translations.header.ai.modal.snackbar["".concat(type, "_limit_reached")]);
      setOpenSnackbar(true);
    }
  }; // Select a text from the especified type. If the text is a headline or a description and the minRequired is > 0,
  // the text will be selected if is the last text to select and the other texts are not short texts:


  var handleSelectText = function handleSelectText(text, type) {
    var newSelected = _objectSpread({}, selectedTexts);

    var selectedType = newSelected[type];

    var updateSelectedTexts = function updateSelectedTexts(texts) {
      newSelected[type] = texts;
      setSelectedTexts(newSelected);
    };

    var addText = function addText(replace) {
      var minLength = type === "headlines" ? 15 : 60; // Solo para headlines y descriptions

      var needMinLength = minRequired[type] > 0;
      var isLastSelection = needMinLength && newSelected[type].length + 1 === maxToSelect[type];
      var isShortText = text.length <= minLength;
      var hasShortText = newSelected[type].some(function (t) {
        return t.length <= minLength;
      });

      if (!replace && (!isLastSelection || hasShortText || isLastSelection && !hasShortText && isShortText)) {
        updateSelectedTexts([].concat(_toConsumableArray(selectedType), [text]));
      } else if (replace && (!needMinLength || isShortText && needMinLength)) {
        updateSelectedTexts([text]);
      } else {
        if (!hasShortText && isLastSelection) {
          setSnackbarText(translations.header.ai.modal.snackbar["minimum_".concat(type.substring(0, type.length - 1), "_required")]);
        } else {
          setSnackbarText(translations.header.ai.modal.snackbar.limit_reached);
        }

        setOpenSnackbar(true);
      }
    };

    if (selectedType.includes(text)) {
      updateSelectedTexts(selectedType.filter(function (asset) {
        return asset !== text;
      }));
    } else if (maxToSelect[type] === 1 && selectedType.length === 1) {
      addText(true);
    } else if (maxToSelect[type] > selectedType.length) {
      addText(false);
    } else {
      setSnackbarText(translations.header.ai.modal.snackbar["".concat(type, "_limit_reached")]);
      setOpenSnackbar(true);
    }
  }; // Complete all assets sections:


  var handleSelectAll = function handleSelectAll() {
    if (!selectedAll) {
      // Complete all images:
      if (fromSnackbar || tab === "visuals") {
        var newSelectedImages = _objectSpread({}, selectedImages);

        var selectImages = function selectImages(sectionName, type, filterImages, selectLimit) {
          if (!section || section === sectionName) {
            newSelectedImages[type] = filterImages.filter(function (_, index) {
              return index < selectLimit;
            }).map(function (asset) {
              return asset.id;
            });
          }
        };

        var selectLogos = function selectLogos(sectionName, type, filterLogos, selectLimit) {
          if (newSelectedImages[type].length === 0) {
            selectImages(sectionName, type, filterLogos, selectLimit);
          }
        };

        if (section) {
          selectImages("square_images", "squareImages", squareImages, maxToSelect.squareImages);
          selectImages("landscape_images", "landscapeImages", landscapeImages, maxToSelect.landscapeImages);
        } else {
          var squareImageSet = new Set(newSelectedImages.squareImages);
          var landscapeImageSet = new Set(newSelectedImages.landscapeImages);
          var minSquareImages = minRequired.squareImages;
          var minLandscapeImages = minRequired.landscapeImages;
          var maxSquareImages = maxToSelect.squareImages;
          var maxLandscapeImages = maxToSelect.landscapeImages;
          var totalImages = landscapeImageSet.size + squareImageSet.size;
          images.forEach(function (image) {
            totalImages = landscapeImageSet.size + squareImageSet.size;
            maxSquareImages = maxToSelect.squareImages + (landscapeImageSet.size >= minLandscapeImages ? minLandscapeImages : 0);
            maxLandscapeImages = maxToSelect.landscapeImages + (squareImageSet.size >= minSquareImages ? minSquareImages : 0);

            if (image.aspect_ratio === 1 && totalImages < maxSquareImages) {
              squareImageSet.add(image.id);
            } else if (image.aspect_ratio === 1.91 && totalImages < maxLandscapeImages) {
              landscapeImageSet.add(image.id);
            }

            newSelectedImages.squareImages = Array.from(squareImageSet);
            newSelectedImages.landscapeImages = Array.from(landscapeImageSet);
          });
        }

        selectLogos("square_logo_images", "squareLogo", squareLogos, maxToSelect.squareLogo);
        selectLogos("landscape_logo_images", "landscapeLogo", landscapeLogos, maxToSelect.landscapeLogo);
        setSelectedImages(newSelectedImages);
      } // Complete all texts:


      if (fromSnackbar || tab === "texts") {
        var newSelectedTexts = {
          headlines: new Set(selectedTexts.headlines),
          descriptions: new Set(selectedTexts.descriptions),
          longHeadlines: new Set(selectedTexts.longHeadlines)
        };

        var addText = function addText(type, textList, maxCount, minLength) {
          var hasShortText = Array.from(newSelectedTexts[type]).some(function (text) {
            return text.length <= minLength;
          });
          textList.forEach(function (text) {
            if (newSelectedTexts[type].size < maxCount) {
              if (minRequired[type] > 0 && newSelectedTexts[type].size + 1 === maxCount && !hasShortText) {
                if (text.text.length <= minLength) {
                  newSelectedTexts[type].add(text.text);
                }
              } else {
                newSelectedTexts[type].add(text.text);
              }
            }
          });
        };

        addText("headlines", headlines, maxToSelect.headlines, 15);
        addText("descriptions", descriptions, maxToSelect.descriptions, 60);
        addText("longHeadlines", longHeadlines, maxToSelect.longHeadlines, Infinity);
        setSelectedTexts({
          headlines: Array.from(newSelectedTexts.headlines),
          descriptions: Array.from(newSelectedTexts.descriptions),
          longHeadlines: Array.from(newSelectedTexts.longHeadlines)
        });
      }

      setSelectedAll(true);
    } else {
      setInitialState();
    }
  }; // Manage the close action, if confirm, update the campaign with the selected images and texts:


  var handleCloseModal = function handleCloseModal(confirm) {
    if (confirm) updateAutoCampaign({
      images: selectedImages,
      texts: selectedTexts
    });
    setInitialState();
    onClose();
  }; // Manage the value of the confirm button:


  useEffect(function () {
    setTotalSelected(selectedImages.squareLogo.length + selectedImages.landscapeLogo.length + selectedImages.squareImages.length + selectedImages.landscapeImages.length + selectedTexts.headlines.length + selectedTexts.descriptions.length + selectedTexts.longHeadlines.length);
  }, [selectedImages, selectedTexts]);
  return /*#__PURE__*/React.createElement(Dialog, {
    open: openModal,
    onClose: function onClose() {
      return handleCloseModal(false);
    }
  }, /*#__PURE__*/React.createElement(Dialog.Title, null, /*#__PURE__*/React.createElement(CssFlex, {
    width: "100%",
    gap: "sm",
    alignItems: "center"
  }, /*#__PURE__*/React.createElement(Bolt, {
    size: 24,
    color: "blue"
  }), /*#__PURE__*/React.createElement(Typography, {
    variant: "title2",
    weight: "semibold",
    shade: 800
  }, translations.header.ai.modal.title), /*#__PURE__*/React.createElement(Snackbar, {
    anchorOrigin: {
      vertical: "top",
      horizontal: "center"
    },
    open: openSnackbar,
    onClose: function onClose() {
      return setOpenSnackbar(false);
    },
    autoHideDuration: 3000,
    color: "danger",
    showActionButton: true,
    text: snackbarText
  }))), /*#__PURE__*/React.createElement(Dialog.Body, null, /*#__PURE__*/React.createElement(CssFlex, {
    direction: "column",
    gap: "md",
    width: "95%",
    style: {
      paddingLeft: "32px"
    }
  }, /*#__PURE__*/React.createElement(CssFlex, {
    direction: "column",
    gap: "xl"
  }, /*#__PURE__*/React.createElement(Typography, {
    variant: "paragraph",
    weight: "normal",
    shade: 800,
    dangerouslySetInnerHTML: {
      __html: translations.header.ai.modal[descriptionText].replace("{number}", (fromSnackbar || tab === "texts" ? allTexts.length : 0) + ((fromSnackbar || tab === "visuals") && !section ? images.length + logos.length : !section ? 0 : section.includes("logo") ? section.includes("square") ? squareLogos.length : landscapeLogos.length : section.includes("square") ? squareImages.length : landscapeImages.length))
    }
  }), /*#__PURE__*/React.createElement(CssFlex, {
    justifyContent: "center"
  }, /*#__PURE__*/React.createElement(Link, {
    alignItems: "center",
    onClick: function onClick() {
      return handleSelectAll();
    }
  }, translations.header.ai.modal.allButton))), /*#__PURE__*/React.createElement(Divider, null), /*#__PURE__*/React.createElement(CssFlex, {
    direction: "column",
    gap: "xl"
  }, (fromSnackbar || tab === "visuals") && /*#__PURE__*/React.createElement(React.Fragment, null, (!section || section.includes("logo")) && /*#__PURE__*/React.createElement(CssFlex, {
    direction: "column",
    gap: "12px"
  }, /*#__PURE__*/React.createElement(Typography, {
    variant: "inputText",
    color: "neutral",
    shade: 800,
    dangerouslySetInnerHTML: {
      __html: translations.header.ai.modal.logos.replace("{number}", !section ? logos.length : section.includes("square") ? squareLogos.length : landscapeLogos.length)
    }
  }), /*#__PURE__*/React.createElement(CssFlex, {
    gap: "md",
    wrap: "wrap",
    flexGrow: "1",
    maxWidth: "100%"
  }, logos.length !== 0 && logos.map(function (image) {
    return /*#__PURE__*/React.createElement(React.Fragment, null, (!section || section === "square_logo_images") && image.aspect_ratio === 1 && /*#__PURE__*/React.createElement("button", {
      type: "button",
      key: "image-".concat(image.id, "-square-logo"),
      onClick: function onClick() {
        return handleSelectImage(image.id, "squareLogo");
      },
      "data-selected": selectedImages.squareLogo.includes(image.id),
      className: classes.squareImageContainer
    }, /*#__PURE__*/React.createElement("img", {
      src: image.url,
      alt: "square logo",
      "data-selected": selectedImages.squareLogo.includes(image.id),
      className: classes.squareImage,
      width: "48",
      height: "48"
    })), (!section || section === "landscape_logo_images") && image.aspect_ratio === 4 && /*#__PURE__*/React.createElement("button", {
      type: "button",
      key: "image-".concat(image.id, "-landscape-logo"),
      onClick: function onClick() {
        return handleSelectImage(image.id, "landscapeLogo");
      },
      "data-selected": selectedImages.landscapeLogo.includes(image.id),
      className: classes.landscapeImageContainer
    }, /*#__PURE__*/React.createElement("img", {
      src: image.url,
      alt: "landscape logo",
      "data-selected": selectedImages.landscapeLogo.includes(image.id),
      className: classes.landscapeImage,
      width: "85",
      height: "48"
    })));
  }))), (!section || !section.includes("logo")) && /*#__PURE__*/React.createElement(CssFlex, {
    direction: "column",
    gap: "12px"
  }, /*#__PURE__*/React.createElement(Typography, {
    variant: "inputText",
    color: "neutral",
    shade: 800,
    dangerouslySetInnerHTML: {
      __html: translations.header.ai.modal.images.replace("{number}", !section ? images.length : section.includes("square") ? squareImages.length : landscapeImages.length)
    }
  }), /*#__PURE__*/React.createElement(CssFlex, {
    gap: "md",
    wrap: "wrap",
    flexGrow: "1",
    maxWidth: "100%"
  }, images.length !== 0 && images.map(function (image) {
    return /*#__PURE__*/React.createElement(React.Fragment, null, (!section || section === "square_images") && image.aspect_ratio === 1 && /*#__PURE__*/React.createElement("button", {
      type: "button",
      key: "image-".concat(image.id, "-square"),
      onClick: function onClick() {
        return handleSelectImage(image.id, "squareImages");
      },
      "data-selected": selectedImages.squareImages.includes(image.id),
      className: classes.squareImageContainer
    }, /*#__PURE__*/React.createElement("img", {
      src: image.url,
      alt: "square",
      "data-selected": selectedImages.squareImages.includes(image.id),
      className: classes.squareImage,
      width: "48",
      height: "48"
    })), (!section || section === "landscape_images") && image.aspect_ratio === 1.91 && /*#__PURE__*/React.createElement("button", {
      type: "button",
      key: "image-".concat(image.id, "-landscape"),
      onClick: function onClick() {
        return handleSelectImage(image.id, "landscapeImages");
      },
      "data-selected": selectedImages.landscapeImages.includes(image.id),
      className: classes.landscapeImageContainer
    }, /*#__PURE__*/React.createElement("img", {
      src: image.url,
      alt: "landscape",
      "data-selected": selectedImages.landscapeImages.includes(image.id),
      className: classes.landscapeImage,
      width: "85",
      height: "48"
    })));
  })))), (fromSnackbar || tab === "texts") && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(TextAISelectors, {
    title: translations.header.ai.modal.headlines.replace("{number}", headlines.length),
    texts: headlines,
    selectedTexts: selectedTexts.headlines,
    onChange: function onChange(text) {
      return handleSelectText(text, "headlines");
    }
  }), /*#__PURE__*/React.createElement(TextAISelectors, {
    title: translations.header.ai.modal.longHeadlines.replace("{number}", longHeadlines.length),
    texts: longHeadlines,
    selectedTexts: selectedTexts.longHeadlines,
    onChange: function onChange(text) {
      return handleSelectText(text, "longHeadlines");
    }
  }), /*#__PURE__*/React.createElement(TextAISelectors, {
    title: translations.header.ai.modal.descriptions.replace("{number}", descriptions.length),
    texts: descriptions,
    selectedTexts: selectedTexts.descriptions,
    onChange: function onChange(text) {
      return handleSelectText(text, "descriptions");
    }
  }))))), /*#__PURE__*/React.createElement(Dialog.Footer, null, /*#__PURE__*/React.createElement(Dialog.FooterButton, {
    variant: "terciary",
    onClick: function onClick() {
      return handleCloseModal(false);
    }
  }, translations.header.ai.modal.cancelButton), /*#__PURE__*/React.createElement(Dialog.FooterButton, {
    variant: "primary",
    disabled: totalSelected === 0,
    onClick: function onClick() {
      return handleCloseModal(true);
    }
  }, translations.header.ai.modal.confirmButton.replace("{number}", totalSelected))));
};

export default AIModal;