import { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Option from './option';
import { createReview } from '../../redux/actions/review';
import { CORRECT_COLOR, DONT_KNOW_COLOR, WRONG_COLOR } from './utils';
import { updateStudentCardRate } from '../../redux/actions/student-card';

class OptionContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedOptionId: null,
      options: [...props.options, { id: 0, text: 'نمی دانم', isCorrect: false }]
    };
  }

  handleSelect = async optionId => {
    if (this.state.selectedOptionId !== null) return null;
    this.setState({ selectedOptionId: optionId });
    if (optionId !== 0) this.setState({ options: [...this.props.options] });
    const { payload: review } = await this.props.createReview(this.props.cardId, optionId);
    if (this.props.rateUpdated) {
      await this.props.updateStudentCardRate(review.studentCard.id, this.props.rate);
    }
    this.setState({ selectedOptionId: optionId });
    this.props.setColor(
      optionId ? (review.status === 1 ? CORRECT_COLOR : WRONG_COLOR) : DONT_KNOW_COLOR
    );
  };

  render() {
    return (
      <div id='options' className='space-y-3 px-4'>
        {this.state.options.map((option, index) => (
          <Option
            key={option.id}
            option={option}
            index={index}
            isAnyOptionSelected={this.state.selectedOptionId !== null}
            isSelectedOption={this.state.selectedOptionId === option.id}
            onSelect={this.handleSelect}
          />
        ))}
      </div>
    );
  }
}

OptionContainer.propTypes = {
  cardId: PropTypes.number.isRequired,
  options: PropTypes.arrayOf(PropTypes.object).isRequired,
  setColor: PropTypes.func.isRequired,
  createReview: PropTypes.func.isRequired,
  rate: PropTypes.number,
  rateUpdated: PropTypes.bool.isRequired,
  updateStudentCardRate: PropTypes.func.isRequired
};

export default connect(null, { createReview, updateStudentCardRate })(OptionContainer);
