import React, { useState } from 'react';

import HtmlContent from '@/components/HtmlContent';
import SelectArrowIcon from '@/svgs/SelectArrowIcon';
import { QuizChoiceType } from '@/types';

import styles from './QuizQuestion.module.scss';

export default function QuizQuestion({
  answer = '',
  choices = [],
  incorrect = '',
  question = '',
  title = '',
}: {
  answer?: string;
  choices?: QuizChoiceType[];
  incorrect?: string;
  question?: string;
  title?: string;
}) {
  const [selected, setSelected] = useState<number>(-1);

  const onClickAnswerHead = (index: number) => setSelected(
    (selected) => (selected === index ? -1 : index),
  );

  return (
    <div className={styles.QuizQuestion}>
      {!!title?.length && (<h4>{title}</h4>)}
      {!!question?.length && (
        <div className={styles.question}>
          <HtmlContent content={question} />
        </div>
      )}
      {!!choices?.length && choices?.map(
        ({ text, is_correct }: QuizChoiceType, index: number) => (
          !!text?.length && (
            <div
              key={index}
              className={styles[`answer${index === selected ? '--answered' : ''}`]}
            >
              <button
                className={styles['answer-head']}
                type="button"
                onClick={() => onClickAnswerHead(index)}
              >
                <span className={styles.letter}>
                  {String.fromCharCode(65 + index)}
                </span>
                <HtmlContent content={text} type="small" />
                <span className={styles.arrow}>
                  <SelectArrowIcon />
                </span>
              </button>
              <div className={styles['answer-body']}>
                <HtmlContent content={is_correct ? answer : incorrect} />
              </div>
            </div>
          )
        ),
      )}
    </div>
  );
};
