import React from 'react';
import PropTypes from 'prop-types';

import emojis from '@readme/emojis/unicode/index.json';

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

export default class EmojiPicker extends React.Component {
  static propTypes = {
    onClick: PropTypes.func,
    value: PropTypes.string,
  };

  constructor(props) {
    super(props);
    this.state = {
      value: props.value,
    };
  }

  onClick = value => {
    this.setState({ value });
    /* istanbul ignore else */
    if (typeof this.props.onClick === 'function') this.props.onClick(value);
  };

  renderEmoji = () => {
    return emojis.map(emoji => {
      const [name, aliases] = emoji;

      const EmojiClasses = [
        classes['EmojiPicker-Button'],
        name === this.state.value && classes['EmojiPicker-Button_active'],
      ]
        .filter(e => e)
        .join(' ');
      return (
        <button
          key={aliases}
          className={EmojiClasses}
          disabled={name === this.state.value}
          onClick={() => this.onClick(name)}
          type="button"
        >
          <span aria-label={aliases} role="img">
            {name}
          </span>
        </button>
      );
    });
  };

  render() {
    const ButtonClasses = [
      classes['EmojiPicker-Button'],
      classes['EmojiPicker-Button_none'],
      this.state.value === '' && classes['EmojiPicker-Button_active'],
    ]
      .filter(e => e)
      .join(' ');
    return (
      <div className={classes.EmojiPicker}>
        <button
          className={ButtonClasses}
          disabled={this.state.value === ''}
          onClick={() => this.onClick('')}
          type="button"
        >
          None
        </button>
        {this.renderEmoji()}
      </div>
    );
  }
}
