import { useState, useMemo, useEffect, useCallback } from 'react';
import IfActive from "../../../application/IfActive/index.js";
import cx from "../../../../utils/css/cx.js";
import choose from '../choose.module.scss';
import classes from './styles.module.scss';
const cls = cx.merge({
  ...choose,
  ...classes
});
const ButtonSelect = function ButtonSelect(props) {
  const {
    placeholder,
    value,
    options,
    onSelect,
    size,
    shadow
  } = props;
  const [isOpen, setIsOpen] = useState();
  useEffect(() => {
    if (!isOpen) return undefined;
    const handler = () => setIsOpen(false);
    window.document.addEventListener('click', handler);
    return () => window.document.removeEventListener('click', handler);
  }, [isOpen]);
  const selectedValueLabel = useMemo(() => {
    const selectedOption = options.find(o => o.value === value);
    return selectedOption?.label || placeholder || '';
  }, [value]);
  const clickButton = useCallback(e => {
    e.stopPropagation();
    setIsOpen(old => !old);
  }, []);
  const onSelectOption = useCallback(e => {
    const {
      value: targetValue
    } = e.target.dataset;
    onSelect(targetValue);
  }, [onSelect]);
  return <div className={classes.container}>
      <button className={cls('choose', size, `shadow-${shadow}`)} type="button" onClick={clickButton}>
        {selectedValueLabel}
      </button>
      <IfActive active={isOpen}>
        <div className={cls('states')}>
          {options.map(option => <button key={option.value} className={classes.link} type="button" data-value={option.value} onClick={onSelectOption}>
              {option.label}
            </button>)}
        </div>
      </IfActive>
    </div>;
};
export default ButtonSelect;