import React, { useRef, useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import keygen from '~helpers/keygen';
import { closeOtherSelects } from '~helpers/select';
import styles from './custom-select.module.scss';

const CustomSelect = ({
  items = [],
  onClick,
  itemsValue = 'field',
  itemsLabel = 'name',
  activeItem,
}) => {
  const [options, setOptions] = useState(items);
  const [selectedOption, setSelectedOption] = useState(activeItem || items[0]);
  useEffect(() => {
    setOptions([...items]);
  }, [selectedOption, items]);

  const defBtn = useRef(null);
  const selectList = useRef(null);

  function showDropdown() {
    closeOtherSelects(selectList.current);
    selectList.current.classList.toggle(styles.show);
    defBtn.current.classList.toggle(styles.flip);
  }

  return (
    <div className={styles.customSelectContainer || ''}>
      <button
        ref={defBtn}
        className={`${styles.select || ''} custom-select-gtm btn-cta`}
        type="button"
        onClick={showDropdown}
        data-id="select-button"
      >
        {selectedOption && selectedOption[itemsLabel]}
      </button>
      <ol ref={selectList} className={styles.list || ''} data-id="select-list">
        {options &&
          options.map((item) => {
            if (item[itemsValue] === selectedOption[itemsValue]) return null;
            const currentItem = item;
            if (currentItem[itemsValue] === undefined) {
              currentItem[itemsValue] = 'id';
            }
            if (currentItem.type === undefined) {
              currentItem.type = 'type';
            }
            return (
              <li
                className={styles.selectListItem || ''}
                key={keygen()}
                data-value={currentItem[itemsValue]}
                data-type={currentItem.type}
              >
                <button
                  type="button"
                  className="custom-select-gtm btn-cta"
                  onClick={() => {
                    onClick(currentItem[itemsValue], currentItem[itemsLabel], currentItem.type);
                    setSelectedOption(currentItem);
                    showDropdown();
                  }}
                >
                  {currentItem[itemsLabel]}
                </button>
              </li>
            );
          })}
      </ol>
    </div>
  );
};

CustomSelect.propTypes = {
  items: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
  onClick: PropTypes.func.isRequired,
  itemsValue: PropTypes.string,
  itemsLabel: PropTypes.string,
  activeItem: PropTypes.shape({}),
};

export default CustomSelect;
