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

// Style
let classes = {};
/* istanbul ignore next */
if (typeof window !== 'undefined' || typeof _COMPILED_ === 'undefined') classes = require('./style.module.scss');

export default function ColorPicker(props) {
  const hexRegex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;
  const [color, setColor] = useState('#ffffff');

  useEffect(() => {
    if (props.color) {
      const validHex = hexRegex.exec(props.color);
      if (validHex) setColor(validHex[0]);
    }
  }, [props.color]);

  const handleChange = event => {
    setColor(event.target.value);
    if (typeof props.onChange === 'function') props.onChange(event);
  };

  return (
    <label className={[classes.ColorPicker, props.className, `Input Input_${props.size}`].join(' ')}>
      <div className={classes['ColorPicker-Wrapper']}>
        <input className={classes['ColorPicker-Input']} onChange={handleChange} type="color" value={color} />
      </div>
      <div className={classes['ColorPicker-Value']}>{color}</div>
    </label>
  );
}

ColorPicker.propTypes = {
  color: PropTypes.string,
  onChange: PropTypes.func,
  size: PropTypes.oneOf(['lg', 'md', 'sm']),
};

ColorPicker.defaultProps = {
  className: '',
  size: 'md',
};
