import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
// eslint-disable-next-line import/no-duplicates
import * as React from 'react'; // eslint-disable-next-line import/no-duplicates

import { useEffect, useState, useRef } from 'react';
import classNames from 'classnames';
import Icon, { ICON_COLOR } from '../icons/Icon';

// if possible, use Select component instead
var Dropdown = function Dropdown(_ref) {
  var name = _ref.name,
      links = _ref.links,
      initiallyOpened = _ref.initiallyOpened,
      _ref$color = _ref.color,
      color = _ref$color === void 0 ? 'default' : _ref$color,
      fullWidth = _ref.fullWidth,
      onItemSelect = _ref.onItemSelect;

  var _useState = useState(initiallyOpened || false),
      _useState2 = _slicedToArray(_useState, 2),
      open = _useState2[0],
      setOpen = _useState2[1];

  var clickedInside = useRef(false);

  function handleClickInside() {
    setOpen(function (prevOpen) {
      return !prevOpen;
    });
    clickedInside.current = true;
  }

  function handleClickOutside() {
    if (clickedInside.current) {
      clickedInside.current = false;
      return;
    }

    setOpen(false);
  }

  useEffect(function () {
    document.addEventListener('click', handleClickOutside);
    return function () {
      return document.removeEventListener('click', handleClickOutside);
    };
  }, []);
  return /*#__PURE__*/React.createElement("div", {
    className: classNames('sg-dropdown', {
      'sg-dropdown--opened': open,
      'sg-dropdown--white': color === 'white',
      'sg-dropdown--full-width': fullWidth
    }),
    onClick: handleClickInside
  }, /*#__PURE__*/React.createElement("p", null, name), /*#__PURE__*/React.createElement(Icon, {
    type: open ? 'chevron_up' : 'chevron_down',
    size: 24,
    color: ICON_COLOR['icon-gray-70'],
    className: "sg-dropdown__icon"
  }), open && /*#__PURE__*/React.createElement("div", {
    className: "sg-dropdown__items"
  }, links.map(function (link, index) {
    return /*#__PURE__*/React.createElement("a", {
      key: index,
      href: link.url,
      className: "sg-dropdown__item",
      onClick: onItemSelect ? function (e) {
        return onItemSelect(e, link);
      } : undefined
    }, link.label);
  })));
};

export default Dropdown;