import { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import OptionContainer from './option-container';
import Question from './question';
import Answer from './answer';
import Reviews from './reviews';
import Header from './header';
import Footer from './footer';
import { CORRECT_COLOR, DEFAULT_COLOR } from './utils';
import { updateStudentCardRate } from '../../redux/actions/student-card';

function Card(props) {
  const { card } = props;
  const [color, setColor] = useState(DEFAULT_COLOR);
  const initialRate = props.card.studentCard?.rate || 0;
  const [rate, setRate] = useState(initialRate);

  useEffect(async () => {
    if (rate !== initialRate && card.studentCard) {
      await props.updateStudentCardRate(card.studentCard.id, rate);
    }
  }, [rate]);

  return (
    <div className='mb-20'>
      <Header chapter={props.chapter} lessonName={props.card.lesson.name} />
      <Question
        cardId={card.id}
        question={card.question}
        color={color}
        rate={rate}
        setRate={setRate}
      />
      <OptionContainer
        cardId={card.id}
        options={card.options}
        setColor={setColor}
        rate={rate}
        rateUpdated={rate !== initialRate}
      />
      {color !== DEFAULT_COLOR && <Reviews color={color} />}
      {color !== DEFAULT_COLOR && <Answer answer={card.answer} color={color} />}
      <Footer isAnyOptionSelected={color !== DEFAULT_COLOR} showArchive={color === CORRECT_COLOR} />
    </div>
  );
}

Card.propTypes = {
  card: PropTypes.object.isRequired,
  chapter: PropTypes.object.isRequired,
  updateStudentCardRate: PropTypes.func.isRequired
};

export default connect(null, { updateStudentCardRate })(Card);
