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

const MultipleChoiceQuestion = ({ question, onAnswer, studentAnswer, index }) => {
  const savedAnswer = studentAnswer !== null ? studentAnswer.ANSWER_STUDENT : 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);

  const handleChange = (value) => {
    onAnswer(index, value, question.ID_ADMIN_EXERCISE);
  };

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

  return (
    <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', cursor: 'pointer' }}
                  onClick={() => handleChange(getOptionLetter(optionKey))}
                >
                  <span className="option-label">{getOptionLetter(optionKey)}</span>
                  <span className="ms-2 option-text">{options[optionKey]}</span>
                </div>
              );
            }
            return null;
          }
        )}
      </div>
    </div>
  );
};

export default MultipleChoiceQuestion;
