import React, { useState } from 'react';
import PropTypes from 'prop-types';

// Style
/* istanbul ignore next */
if (typeof window !== 'undefined') require('./style.scss');

const Select = ({ options, ...props }) => {
  const [selectedOption, setSelectedOption] = useState('');
  const { className, isInvalid, onChange, size, ...attrs } = props;
  const changeHandler = e => {
    setSelectedOption(e.target.value);
    /* istanbul ignore else */
    if (typeof onChange === 'function') onChange(e);
  };
  return (
    <div className={`Select ${className || ''}`}>
      <select
        className={`Select-Input ${size && `Select-Input_${size} ${isInvalid && `Select-Input_invalid`}`}`}
        onChange={changeHandler}
        value={selectedOption}
        {...attrs}
      >
        {options.map(o => (
          <option key={o.label} disabled={o.disabled} value={o.value}>
            {o.label}
          </option>
        ))}
      </select>
    </div>
  );
};

const Options = PropTypes.shape({
  disabled: PropTypes.bool,
  label: PropTypes.string,
  value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
});

Select.propTypes = {
  className: PropTypes.string,
  isInvalid: PropTypes.bool,
  onChange: PropTypes.func,
  options: PropTypes.arrayOf(Options),
  size: PropTypes.oneOf(['lg', 'md', 'sm']),
  value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
};

Select.defaultProps = {
  size: 'md',
};

export default Select;
