import React, { Component } from 'react';
import './index.scss'


class Question extends Component {
  state = {
    selectedId: 0,
  }

  componentDidMount() {

  }

  componentDidUpdate(prevProps, prevState) {
    if (prevProps.question.id !== this.props.question.id) {
      this.setSelectedId()
    }
  }

  setSelectedId = () => {
    const {question} = this.props
    if (question.selected) {
      this.setState({
        selectedId: question.selected,
      })
    }
  }


  handleSelect = option => {
    this.props.selectAnswer(this.props.question, option.id)
    this.setState({
      selectedId: option.id,
    })
  }

  render() {
    const {selectedId} = this.state
    const {question} = this.props
    return (
      <div className={'question-container'}>
        <div className="question">{question.ques}</div>
        <ul className={'options'}>
          {
            !!question.options.length && question.options.map((item, index) => {
              return <li key={item.id} className={item.id === selectedId ? 'active' : ''}
                         onClick={this.handleSelect.bind(this, item)}>
                <div className={'letter'}>{String.fromCharCode(65 + index)}</div>
                <div>{item.des}</div>
              </li>
            })
          }
        </ul>
      </div>
    );
  }
}

export default Question;