import React from 'react';
import MediaViewer from './MediaViewer';
import { MEDIA_URL } from '../../../../../utils/Constant';

const MultipleChoiceQuestion = ({ question, studentAnswer, index }) => {
  const savedAnswer = studentAnswer !== null ? studentAnswer : null;
  const options = question.multipleChoices[0];

  const mediaUrls = [];
  const mediaPath = `${MEDIA_URL}/exercise`;

  if (question.IMAGE) mediaUrls.push(`${mediaPath}/image/${question.IMAGE}`);
  if (question.AUDIO) mediaUrls.push(`${mediaPath}/audio/${question.AUDIO}`);
  if (question.VIDEO) mediaUrls.push(question.VIDEO);

  function getOptionLetter(option) {
    const match = option.match(/OPTION_(\w)/);
    return match ? match[1] : null;
  }

  return (
    <div>

      <div className={`correction-label ${question.IS_CORRECT === 1 ? `correct`  : `incorrect` }`}>
        <i className={`me-2 bi ${question.IS_CORRECT === 1 ? `bi-check-circle-fill`  : `bi-x-circle-fill` }`}></i>
        Your answer is {question.IS_CORRECT === 1 ? `correct`  : `incorrect` }.
      </div>

      {mediaUrls.length > 0 && <MediaViewer mediaUrls={mediaUrls} />}

      <p>{question.QUESTION.split('\n').map((line, index) => (
          <React.Fragment key={index}>
              {line}
              <br />
          </React.Fragment>
      ))}</p>
      
      <div className="options">
        {['OPTION_A', 'OPTION_B', 'OPTION_C', 'OPTION_D', 'OPTION_E'].map(
          (optionKey) => {
            if (options[optionKey]) {
              return (
                <div 
                  key={optionKey}
                  className={`p-0 mb-3 form-check ${savedAnswer === getOptionLetter(optionKey) ? 'selected-answer' : ''}`}
                  style={{ display: 'flex', alignItems: 'center'}}
                >
                  <span className="option-label">{getOptionLetter(optionKey)}</span>
                  <span className="ms-2 option-text">{options[optionKey]}</span>
                </div>
              );
            }
            return null;
          }
        )}
      </div>
    </div>
  );
};

export default MultipleChoiceQuestion;
