import React, { useCallback, useEffect, useMemo } from "react";
import classNames from "classnames";
import { StyledOptionGroup, StyledOptionGroupHeader, StyledOptionGroupOption, StyledOptionGroupLi, StyledOptionGroupHeaderName } from "./Styles";
import { Checkbox } from "../../Checkbox/Checkbox";
export const OptionGroup = _ref => {
  let {
    id,
    name,
    options,
    type,
    hover,
    checked,
    onChange,
    setHover,
    optionGroupClassName,
    mixedOptions = []
  } = _ref;
  useEffect(() => {
    if (hover === id && type !== "single") {
      var _document$getElementB;
      (_document$getElementB = document.getElementById("" + id)) == null || _document$getElementB.focus();
    }
  }, [hover, type, id]);
  const isAllOptionsChecked = useMemo(() => options.every(option => checked.includes(option.id)), [options, checked]);
  const handleHover = useCallback(() => {
    if (setHover) {
      setHover(type === "single" ? undefined : id);
    }
  }, [setHover, type, id]);
  const allOptionValues = useMemo(() => options.map(option => option.id), [options]);
  const isMixed = useMemo(() => {
    return (options.some(option => checked.includes(option.id)) || mixedOptions.some(item => allOptionValues.includes(item))) && !isAllOptionsChecked;
  }, [allOptionValues, checked, isAllOptionsChecked, mixedOptions, options]);
  const handleClick = useCallback(e => {
    e.stopPropagation();
    e.preventDefault();
    if (onChange) {
      if (isAllOptionsChecked) {
        onChange(checked.filter(i => allOptionValues.includes(i) === false));
      } else {
        const values = [...checked, ...allOptionValues];
        const unique = values.filter((item, pos) => {
          return values.indexOf(item) === pos;
        });
        onChange(unique);
      }
    }
  }, [allOptionValues, checked, isAllOptionsChecked, onChange]);
  return /*#__PURE__*/React.createElement(StyledOptionGroupLi, {
    key: id,
    className: classNames("c-option-group", optionGroupClassName),
    onClick: handleClick
  }, /*#__PURE__*/React.createElement(StyledOptionGroup, {
    key: id
  }, /*#__PURE__*/React.createElement(StyledOptionGroupOption, {
    onMouseEnter: handleHover,
    hover: hover === id && type === "multiple"
  }, /*#__PURE__*/React.createElement(StyledOptionGroupHeader, null, /*#__PURE__*/React.createElement(StyledOptionGroupHeaderName, {
    weight: "bold"
  }, name), type === "multiple" && /*#__PURE__*/React.createElement(Checkbox, {
    id: "" + id,
    checked: isAllOptionsChecked,
    mixed: isMixed,
    onChange: handleClick,
    type: "checkbox"
  })))));
};
OptionGroup.displayName = "OptionGroup";
//# sourceMappingURL=OptionGroup.js.map