import * as React from 'react'

import * as Styled from './index.style'

interface Props {
  value?: string;
  onChange?: (value: string) => void;
  options: string[];
  type: 'radio' | 'checkbox';
}

const OPTIONS_MAP = {
  '0': 'A',
  '1': 'B',
  '2': 'C',
  '3': 'D'
}

class Select extends React.Component<Props> {
  state = {
    value: this.props.value?.split('|') || []
  }

  handleClick = (item: string) => {
    const {
      value
    } = this.state
    const {
      onChange
    } = this.props
    let next: string[]
    if (this.props.type === 'radio') {
      next = value.includes(item) ? [] : [item]
    } else {
      next = [...value]
      if (next.includes(item)) {
        next.splice(next.indexOf(item), 1)
      } else {
        next.push(item)
      }
    }
    this.setState({
      value: next
    })
    onChange?.(next.join('|'))
  }

  public render() {
    const {
      value
    } = this.state
    const {
      options
    } = this.props
    return (
      <>
        {
          options.map((item, index) => (
            <Styled.SelectOptionsItem
              key={item}
              selected={value.includes(item)}
              onClick={this.handleClick.bind(this, item)}
            >
              {String.fromCharCode(index + 65)}.
              {item}
            </Styled.SelectOptionsItem>
          ))
        }
      </>
    )
  }
}

export default React.memo(Select)
