import _defineProperty from "@babel/runtime/helpers/defineProperty";
// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

import { Component, Children, cloneElement, isValidElement } from 'react';
import classNames from 'classnames';
import { CLS_PREFIX } from '../../constants';
import Grid from '../Grid';
import GridCol from '../GridCol';
import { safeInvoke } from '../utils';
import { jsx as _jsx } from "react/jsx-runtime";
const getNextSelectedValue = (value, prevValue, toggleable) => {
  if (Array.isArray(prevValue)) {
    if (prevValue.indexOf(value) !== -1) {
      if (toggleable) {
        return prevValue.filter(v => v !== value);
      }
      return prevValue;
    }
    return [...prevValue, value];
  }
  if (toggleable && prevValue === value) {
    return null;
  }
  return value;
};
/**
 * `ItemList` component is used for displaying list of [Items](#!/Item)
 * according to [Grid](#!/Grid) principle.
 * @since 0.0.48
 */
class ItemList extends Component {
  constructor(_props) {
    super(_props);
    // eslint-disable-next-line react/state-in-constructor
    _defineProperty(this, "createItemProps", item => {
      const {
        baseClassName,
        selectable,
        onSelect,
        reorderable,
        hoverable
      } = this.props;
      const classNameList = [`${baseClassName}__item`];
      const props = {};
      if (selectable && item.props.value !== undefined) {
        const {
          value
        } = this.state;
        const itemValue = item.props.value;
        if (Array.isArray(value) && value.indexOf(itemValue) !== -1) {
          classNameList.push(`${baseClassName}__item--selected`);
        } else if (value === itemValue) {
          classNameList.push(`${baseClassName}__item--selected`);
        }
        props.onClick = e => {
          safeInvoke(item.props.onClick, e);
          const nextValue = getNextSelectedValue(itemValue, value, selectable === 'toggleable' || selectable === 'multiple');
          this.setState({
            value: nextValue
          });
          safeInvoke(onSelect, nextValue);
        };
      }

      // Extends hoverable behavior from the ItemList in case if its child doesn't have its own
      if (item.props.hoverable === undefined) {
        props.hoverable = hoverable && this.canManageHoverableState();
      }
      if (reorderable) {
        classNameList.push(`${baseClassName}__item--reorderable`);
      }
      classNameList.push(item.props.className);
      props.className = classNames(...classNameList);
      return props;
    });
    this.state = {
      ReorderableGrid: null,
      ReorderableGridCol: null,
      value: typeof _props.defaultValue === 'undefined' ? null : _props.defaultValue
    };
  }
  static getDerivedStateFromProps(_ref, state) {
    let {
      selectable,
      value: propValue
    } = _ref;
    if (selectable) {
      const multiple = selectable === 'multiple';
      const safeValue = multiple ? [] : null;
      const value = typeof propValue === 'undefined' ? state.value : propValue;
      if (multiple && !Array.isArray(value)) {
        if (value) {
          return {
            value: [value]
          };
        }
        return {
          value: safeValue
        };
      } else if (!multiple && Array.isArray(value)) {
        if (value[0]) {
          return {
            value: value[0]
          };
        }
        return {
          value: safeValue
        };
      }
      return {
        value
      };
    }
    return null;
  }
  componentDidMount() {
    const {
      reorderable
    } = this.props;
    if (reorderable) {
      // @ts-ignore
      import( /* webpackChunkName: "react-sortable-hoc" */'react-sortable-hoc').then(_ref2 => {
        let {
          sortableContainer,
          sortableElement
        } = _ref2;
        this.setState({
          ReorderableGrid: sortableContainer(Grid),
          ReorderableGridCol: sortableElement(GridCol)
        });
      });
    }
  }
  renderNormal(_ref3) {
    let {
      baseClassName,
      children,
      ...props
    } = _ref3;
    return /*#__PURE__*/_jsx(Grid, {
      ...props,
      children: Children.map(children, child => {
        if ( /*#__PURE__*/isValidElement(child)) {
          return /*#__PURE__*/_jsx(GridCol, {
            className: classNames(`${baseClassName}__col`),
            children: /*#__PURE__*/cloneElement(child, this.createItemProps(child))
          });
        }
        return null;
      })
    });
  }
  someChild(predicate) {
    let result = false;
    Children.forEach(this.props.children, child => {
      if (child && predicate(child)) {
        result = true;
      }
    });
    return result;
  }

  /**
   * There are some states where we can't manage hoverable state
   */
  canManageHoverableState() {
    const {
      reorderable,
      selectable
    } = this.props;
    return !reorderable && !selectable;
  }
  isHoverable() {
    if (!this.canManageHoverableState()) {
      return false;
    }
    return this.props.hoverable || this.hasHoverableCard();
  }
  hasViewCard() {
    return this.someChild(child => child.props && child.props.view === 'card');
  }
  hasHoverableCard() {
    return this.someChild(child => child.props && !!child.props.hoverable);
  }
  renderReorderable(_ref4) {
    let {
      baseClassName,
      onReorderEnd,
      children,
      ...props
    } = _ref4;
    const {
      ReorderableGrid,
      ReorderableGridCol
    } = this.state;
    if (!ReorderableGrid) {
      return null;
    }
    const helperClass = classNames({
      [`${baseClassName}__col--gap-xs`]: props.gap === 'xs',
      [`${baseClassName}__col--gap-sm`]: props.gap === 'sm',
      [`${baseClassName}__col--gap-md`]: props.gap === 'md',
      [`${baseClassName}__col--gap-lg`]: props.gap === 'lg',
      [`${baseClassName}__col--gap-xl`]: props.gap === 'xl'
    });
    return /*#__PURE__*/_jsx(ReorderableGrid, {
      axis: "xy",
      helperClass: helperClass,
      onSortEnd: onReorderEnd,
      ...props,
      children: Children.map(children, (child, index) => {
        if ( /*#__PURE__*/isValidElement(child)) {
          const {
            disabled
          } = child.props;
          return /*#__PURE__*/_jsx(ReorderableGridCol, {
            index: index,
            className: classNames(`${baseClassName}__col`),
            disabled: disabled,
            children: /*#__PURE__*/cloneElement(child, this.createItemProps(child))
          });
        }
        return null;
      })
    });
  }
  render() {
    const {
      className,
      reorderable,
      hoverable,
      stretchable,
      selectable,
      onSelect,
      value,
      defaultValue,
      onReorderEnd,
      ...props
    } = this.props;
    return /*#__PURE__*/_jsx("div", {
      className: classNames(this.props.baseClassName, {
        [`${this.props.baseClassName}--hoverable`]: this.isHoverable(),
        [`${this.props.baseClassName}--stretchable`]: stretchable,
        [`${this.props.baseClassName}--selectable`]: selectable,
        [`${this.props.baseClassName}--cards`]: this.hasViewCard()
      }, className),
      children: reorderable ? this.renderReorderable({
        onReorderEnd,
        ...props
      }) : this.renderNormal(props)
    });
  }
}
_defineProperty(ItemList, "defaultProps", {
  hoverable: true,
  stretchable: false,
  reorderable: false,
  selectable: false,
  baseClassName: `${CLS_PREFIX}item-list`
});
export default ItemList;