import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _isEqual from "lodash/isEqual";
import React, { useCallback, useState } from 'react';
import { connect } from "../../../redux";
import Draggable from "../../../components/Draggable";
import { getPlugins } from "../../../../plugins";
import { useHandler } from "../../../../hooks/useHandler";
import { usePageBuilder } from "../../../../hooks/usePageBuilder";
import * as Styled from "./StyledComponents";
import { List } from '@webiny/ui/List';
import { createElement, createBlockElements, deleteFormSettingsInBlockElement } from "../../../utils";
import { getContent, getParentElementWithChildren, getActivePlugins } from "../../../selectors";
import { getElementGroupTitle } from "../../../../utils/util"; // @ts-ignore

var containerMap = {
  'pb-editor-page-element-form': 'pb-editor-block-form',
  'pb-editor-page-element-block': 'pb-editor-block-empty'
};

var AddElement = function AddElement(props) {
  var groups = props.groups,
      isBlock = props.isBlock,
      updateElement = props.updateElement,
      dropElement = props.dropElement,
      dragStart = props.dragStart,
      deactivatePlugin = props.deactivatePlugin,
      dragEnd = props.dragEnd;
  var getGroups = useCallback(function () {
    return getPlugins('pb-editor-page-element-group');
  }, []);
  var getGroupElements = useCallback(function (group) {
    var elements = getPlugins('pb-editor-page-element').filter(function (el) {
      if (el.toolbar && el.toolbar.group === group) {
        if (el.elementType === 'placeholder') {
          return isBlock;
        }

        return true;
      }

      return false;
    });
    return elements;
  }, [isBlock]);
  var getPluginGroupTitle = useCallback(function () {
    var pluginGroupTitle = {};
    groups.forEach(function (group) {
      pluginGroupTitle[group] = getElementGroupTitle(group);
    });
    return pluginGroupTitle;
  }, []);

  var _useState = useState(getGroups()[0].name),
      _useState2 = _slicedToArray(_useState, 2),
      group = _useState2[0],
      setGroup = _useState2[1];

  var _usePageBuilder = usePageBuilder(),
      theme = _usePageBuilder.theme;

  var enableDragOverlay = useCallback(function () {
    var el = document.querySelector('.pb-editor');

    if (el) {
      el.classList.add('pb-editor-dragging');
    }
  }, []);
  var disableDragOverlay = useCallback(function () {
    var el = document.querySelector('.pb-editor');

    if (el) {
      el.classList.remove('pb-editor-dragging');
    }
  }, []);
  var renderDraggable = useCallback(function (element, plugin) {
    var elementType = plugin.elementType;
    return /*#__PURE__*/React.createElement(Draggable, {
      key: plugin.name,
      target: plugin.target,
      beginDrag: function beginDrag(props) {
        return {
          type: elementType,
          target: props.target
        };
      }
    }, function (_ref) {
      var drag = _ref.drag;
      return /*#__PURE__*/React.createElement("div", {
        ref: drag
      }, element);
    });
  }, [dragStart, deactivatePlugin, dragEnd]);
  var handleAddContainer = useHandler(props, function (_ref2) {
    var content = _ref2.content,
        buildMode = _ref2.buildMode;
    return function (plugin) {
      var _content$elements = content.elements,
          elements = _content$elements === void 0 ? [] : _content$elements;
      var config = {};

      if (plugin.name.includes('form')) {
        if (buildMode !== 'PC') {
          config = {
            className: 'pl-4 pr-4',
            formSettings: {
              layout: 'vertical',
              labelWidth: null,
              labelAlign: null
            }
          };
        }
      }

      var targetElement = createBlockElements(containerMap[plugin.name], {
        data: config,
        elements: []
      });
      elements.push(targetElement);

      var docElement = _objectSpread(_objectSpread({}, content), {}, {
        elements: elements
      });

      updateElement({
        element: docElement
      });
    };
  });
  var handleClickAdd = useHandler(props, function (_ref3) {
    var content = _ref3.content,
        formGroups = _ref3.formGroups,
        formId = _ref3.formId,
        formType = _ref3.formType,
        buildMode = _ref3.buildMode;
    return function (plugin) {
      // 容器组件，直接并行添加
      if (Object.keys(containerMap).includes(plugin.name)) {
        handleAddContainer(plugin);
        return;
      }

      var ifFormEle = formGroups.includes(plugin.toolbar.group);

      if (formType === 'form') {
        ifFormEle = true;
      } // 如果没有容器，则创建容器


      if (!formId) {
        var elementType = plugin.elementType;
        var ele = createElement(elementType);

        if (!ifFormEle) {
          // 普通容器内的元素，删除data.formSettings
          ele = deleteFormSettingsInBlockElement(ele);
        }

        var config = {};

        if (ifFormEle) {
          if (buildMode !== 'PC') {
            config = {
              className: 'pl-4 pr-4',
              formSettings: {
                layout: 'vertical',
                labelWidth: null,
                labelAlign: null
              }
            };
          }
        }

        var docElement = _objectSpread(_objectSpread({}, content), {}, {
          elements: [createBlockElements("pb-editor-block-".concat(ifFormEle ? 'form' : 'empty'), {
            data: config,
            elements: [ele]
          })]
        });

        updateElement({
          element: docElement
        });
      } else {
        // 直接追加
        var target = {
          id: formId,
          type: formType
        };
        var source = {
          type: plugin.elementType,
          target: plugin.target
        };
        dropElement({
          source: source,
          target: target
        });
      }
    };
  });
  return /*#__PURE__*/React.createElement(Styled.Flex, null, /*#__PURE__*/React.createElement(List, {
    className: 'page-builder-categories-list'
  }, getGroups().map(function (plugin) {
    var isState = Object.keys(getPluginGroupTitle()).includes(plugin.name);

    if (isState && getGroupElements(plugin.name).length > 0) {
      return /*#__PURE__*/React.createElement("div", {
        key: plugin.name,
        className: 'page-builder-toolbar-group-item'
      }, group && getGroupElements(plugin.name).map(function (plugin) {
        return renderDraggable( /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Styled.ElementBox, {
          className: "relative"
        }, /*#__PURE__*/React.createElement("div", {
          className: 'flex flex-col text-sm itemsCenter page-builder-toolbar-menu-item',
          onClick: function onClick() {
            return handleClickAdd(plugin);
          }
        }, /*#__PURE__*/React.createElement("div", {
          className: 'page-builder-toolbar-menu-icon'
        }, plugin.toolbar.preview({
          theme: theme
        })), /*#__PURE__*/React.createElement("div", null, plugin.toolbar.title)))), plugin);
      })) // </div>
      ;
    }

    return null;
  })));
};

var mapDispatchToProps = function mapDispatchToProps(dispatch) {
  return {
    dragStart: function dragStart(payload) {
      dispatch({
        type: 'ui/dragStart',
        payload: payload
      });
    },
    dragEnd: function dragEnd() {
      dispatch({
        type: 'ui/dragEnd'
      });
    },
    deactivatePlugin: function deactivatePlugin(payload) {
      dispatch({
        type: 'ui/deactivatePlugin',
        payload: payload
      });
    },
    dropElement: function dropElement(payload) {
      dispatch({
        type: 'appBuilder/dropElement',
        payload: payload
      });
    },
    dragComponent: function dragComponent(payload) {
      dispatch({
        type: 'ui/dragComponent',
        payload: payload
      });
    },
    updateElement: function updateElement(payload) {
      dispatch({
        type: 'appBuilder/updateAndFlattenElement',
        payload: payload
      });
    }
  };
};

export default connect(function (state) {
  var _formElement, _formElement2;

  var formEl;
  var allElements = state.appBuilder.elements;
  Object.keys(allElements).map(function (v) {
    if (['form', 'block'].includes(allElements[v].type)) {
      formEl = allElements[v];
    }
  });
  var element = formEl;
  var _state$appBuilder$con = state.appBuilder.config,
      config = _state$appBuilder$con === void 0 ? {} : _state$appBuilder$con;
  var formElement;

  if (['form', 'block'].includes(element === null || element === void 0 ? void 0 : element.type)) {
    if (element.elements.length > 0) {
      formElement = getParentElementWithChildren(state, element.elements[0]);
    } else {
      formElement = element;
    }
  }

  return {
    content: getContent(state),
    formId: (_formElement = formElement) === null || _formElement === void 0 ? void 0 : _formElement.id,
    formType: (_formElement2 = formElement) === null || _formElement2 === void 0 ? void 0 : _formElement2.type,
    groups: config.groups || [],
    formGroups: config.formGroups || [],
    activePlugin: getActivePlugins('pb-editor-page-element')(state).map(function (pl) {
      return pl.name;
    }),
    isBlock: config.isBlock,
    buildMode: config.buildMode || 'PC'
  };
}, mapDispatchToProps, null, {
  areStatePropsEqual: _isEqual
})(AddElement);
//# sourceMappingURL=AddElement.js.map