import _extends from "@babel/runtime/helpers/extends";
// Copyright 1999-2020. Plesk International GmbH. All rights reserved.
import React, { Children, isValidElement, useState, useEffect, useContext, cloneElement } from 'react';
import classNames from 'classnames';
import { CLS_PREFIX } from '../../constants';
import Button from '../Button';
import Dropdown from '../Dropdown';
import Menu from '../Menu';
import ListAction from './ListAction';
import VerticalContext from '../VerticalContext';

/**
 * `ListActions` component is used for performing operations on individual objects in [List](#!/List).
 * @since 3.3.0
 */
const ListActions = ({
  baseClassName = "".concat(CLS_PREFIX, "list-actions"),
  className,
  children,
  locale,
  ...props
}) => {
  const [overlay, setOverlay] = useState(false);
  const vertical = useContext(VerticalContext);
  useEffect(() => {
    const handler = ({
      matches
    }) => {
      setOverlay(!matches);
    };

    const mql = window.matchMedia('(min-width: 768px)');
    handler(mql);
    mql.addListener(handler);
    return () => {
      mql.removeListener(handler);
    };
  }, []);
  const primaryItems = [];
  const secondaryItems = [];
  let secondaryCount = 0;
  Children.toArray(children).forEach((node, index) => {
    if ( /*#__PURE__*/isValidElement(node) && node.type === ListAction) {
      const {
        primary,
        hidden
      } = node.props;
      const key = index.toString();

      if (primary && !vertical) {
        primaryItems.push(hidden ? /*#__PURE__*/React.createElement("div", {
          className: "".concat(baseClassName, "__hidden-action"),
          key: key
        }) : node);
      } else {
        secondaryCount++;

        if (!hidden) {
          secondaryItems.push( /*#__PURE__*/cloneElement(node, {
            primary: false
          }));
        }
      }
    } else {
      secondaryCount++;
      secondaryItems.push(node);
    }
  });
  let secondaryDropdown;

  if (secondaryItems.length > 0) {
    secondaryDropdown = /*#__PURE__*/React.createElement(Dropdown, {
      className: "".concat(baseClassName, "__menu"),
      menu: /*#__PURE__*/React.createElement(Menu, null, secondaryItems),
      menuPlacement: "bottom-end",
      overlay: overlay,
      locale: locale
    }, /*#__PURE__*/React.createElement(Button, {
      ghost: true,
      icon: "kebab"
    }));
  } else if (secondaryCount) {
    secondaryDropdown = /*#__PURE__*/React.createElement("div", {
      className: "".concat(baseClassName, "__menu ").concat(baseClassName, "__hidden-action")
    });
  }

  return /*#__PURE__*/React.createElement("div", _extends({
    className: classNames(baseClassName, className)
  }, props), primaryItems, secondaryDropdown);
};

export default ListActions;