// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

import { 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';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
/**
 * `ListActions` component is used for performing operations on individual objects in [List](#!/List).
 * @since 3.3.0
 */
const ListActions = _ref => {
  let {
    baseClassName = `${CLS_PREFIX}list-actions`,
    className,
    children,
    locale,
    ...props
  } = _ref;
  const [overlay, setOverlay] = useState(false);
  const vertical = useContext(VerticalContext);
  useEffect(() => {
    const handler = _ref2 => {
      let {
        matches
      } = _ref2;
      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__*/_jsx("div", {
          className: `${baseClassName}__hidden-action`
        }, 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__*/_jsx(Dropdown, {
      className: `${baseClassName}__menu`,
      menu: /*#__PURE__*/_jsx(Menu, {
        children: secondaryItems
      }),
      menuPlacement: "bottom-end",
      overlay: overlay,
      locale: locale,
      children: /*#__PURE__*/_jsx(Button, {
        ghost: true,
        icon: "kebab"
      })
    });
  } else if (secondaryCount) {
    secondaryDropdown = /*#__PURE__*/_jsx("div", {
      className: `${baseClassName}__menu ${baseClassName}__hidden-action`
    });
  }
  return /*#__PURE__*/_jsxs("div", {
    className: classNames(baseClassName, className),
    ...props,
    children: [primaryItems, secondaryDropdown]
  });
};
export default ListActions;