import React, { useState } from "react";
import Mammoth from "mammoth";
import AudioPlayer from "./AudioPlayer";

const DocImporter = () => {
  const [questions, setQuestions] = useState([]);

  const handleFileChange = async (event) => {
    const file = event.target.files[0];
    if (file) {
      try {
        const arrayBuffer = await file.arrayBuffer();
        const { value } = await Mammoth.extractRawText({ arrayBuffer });
        // const parsedQuestions = parseQuestions(value);
        console.log(value);
        const parsedQuestions = parseQuestionsNew(value);
        setQuestions(parsedQuestions);
      } catch (error) {
        console.error("Error reading .docx file", error);
      }
    }
  };

  const parseQuestionsNew = (text) => {
    const questionsArray = [];
    const questions = text.split("#Question");
    if (questions.length >= 5) {
      questions.forEach((questionText) => {
        if (questionText.trim()) {
          const parts = questionText.trim().split("\n").map(line => line.trim());
  
          const number = parts.findIndex(part => part.startsWith("#Question:"));
          const question = parts.findIndex(part => part.startsWith("Question:"));
          const optionA = parts.findIndex(part => part.startsWith("Option A:"));
          const optionB = parts.findIndex(part => part.startsWith("Option B:"));
          const optionC = parts.findIndex(part => part.startsWith("Option C:"));
          const optionD = parts.findIndex(part => part.startsWith("Option D:"));
          const optionE = parts.findIndex(part => part.startsWith("Option E:"));
          const correct = parts.findIndex(part => part.startsWith("Correct:"));
          const weight = parts.findIndex(part => part.startsWith("Weight:"));
          const imageUrlIndex = parts.findIndex(part => part.startsWith("Image URL:"));
          const audioUrlIndex = parts.findIndex(part => part.startsWith("Audio URL:"));
          const videoUrlIndex = parts.findIndex(part => part.startsWith("Video URL:"));
  
          const questionData = {
            Number: parts[0]?.split(": ")[1],
            Question: question !== -1 ? parts[question].split(": ")[1] || "Tidak ada" : "Tidak ada",
            // Option: [
            //   optionA !== -1 ? parts[optionA].split(": ")[1] || "Tidak ada" : "Tidak ada",
            //   optionB !== -1 ? parts[optionB].split(": ")[1] || "Tidak ada" : "Tidak ada",
            //   optionC !== -1 ? parts[optionC].split(": ")[1] || "Tidak ada" : "Tidak ada",
            //   optionD !== -1 ? parts[optionD].split(": ")[1] || "Tidak ada" : "Tidak ada",
            //   optionE !== -1 ? parts[optionE].split(": ")[1] || "Tidak ada" : "Tidak ada"
            // ],
            OptionA: optionA !== -1 ? parts[optionA].split(": ")[1] || "Tidak ada" : "Tidak ada",
            OptionB: optionB !== -1 ? parts[optionB].split(": ")[1] || "Tidak ada" : "Tidak ada",
            OptionC: optionC !== -1 ? parts[optionC].split(": ")[1] || "Tidak ada" : "Tidak ada",
            OptionD: optionD !== -1 ? parts[optionD].split(": ")[1] || "Tidak ada" : "Tidak ada",
            OptionE: optionE !== -1 ? parts[optionE].split(": ")[1] || "Tidak ada" : "Tidak ada",
            Correct: correct !== -1 ? parts[correct].split(": ")[1] || "Tidak ada" : "Tidak ada",
            Weight: weight !== -1 ? parts[weight].split(": ")[1] || "Tidak ada" : "Tidak ada",
            imageUrl: imageUrlIndex !== -1 ? parts[imageUrlIndex].split(": ")[1] || "Tidak ada" : "Tidak ada",
            audioUrl: audioUrlIndex !== -1 ? parts[audioUrlIndex].split(": ")[1] || "Tidak ada" : "Tidak ada",
            videoUrl: videoUrlIndex !== -1 ? parts[videoUrlIndex].split(": ")[1] || "Tidak ada" : "Tidak ada",
          };
          questionsArray.push(questionData);
        }
      });
    }
    
    // console.info(questionsArray);
    return questionsArray;
  };

  const parseQuestions = (text) => {
    const questionsArray = [];
    const questions = text.split("Nomor");

    questions.forEach((questionText) => {
      if (questionText.trim()) {
        const parts = questionText.trim().split("\n").map(line => line.trim());
        const imageUrlIndex = parts.findIndex(part => part.startsWith("Image URL:"));
        const tipeSoalIndex = parts.findIndex(part => part.startsWith("Tipe Soal:"));

        const cleanChoice = (choice) => choice.replace(/^[A-Z]\. /, '');

        const question = {
          nomor: parts[0]?.split(": ")[1],
          pertanyaan: parts[2]?.split(": ")[1],
          pilihan: [
            cleanChoice(parts[4]) || "Tidak ada",
            cleanChoice(parts[6]) || "Tidak ada",
            cleanChoice(parts[8]) || "Tidak ada",
            cleanChoice(parts[10]) || "Tidak ada"
          ],
          jawabanBenar: parts[12]?.split(": ")[1],
          imageUrl: imageUrlIndex !== -1 ? parts[imageUrlIndex].split(": ")[1] || "Tidak ada" : "Tidak ada",
          tipeSoal: tipeSoalIndex !== -1 ? parts[tipeSoalIndex].split(": ")[1] || "Tidak ada" : "Tidak ada"
        };
        questionsArray.push(question);
      }
    });
    
    console.info(questionsArray);
    return questionsArray;
  };
  

  return (
    <div>
      <h2>Import Soal dari File .docx</h2>
      <input type="file" accept=".docx" onChange={handleFileChange} />
      
      {questions.length > 0 && (
        <div>
          <h3>Soal yang diimpor:</h3>
          <ul>
            {questions.map((data, index) => (
              <li key={index} className="mb-4">
                <h4>Soal {data.Number}</h4>
                <h5>Weight : {data.Weight}</h5>
                {/* <p><strong>Url Gambar</strong> {data.imageUrl}</p> */}
                {data.imageUrl !== "Tidak ada" && (
                  <img src={data.imageUrl} alt={`Image for soal ${data.number}`} style={{ width: '100px', height: 'auto' }} />
                )}

                {data.audioUrl !== "Tidak ada" && (
                  <AudioPlayer audioSrc={data.audioUrl} />
                )}

                {data.videoUrl !== "Tidak ada" && (
                  <video src={data.videoUrl} controls className='w-50'></video>  
                )}
                <p className="mb-1"><strong>Pertanyaan:</strong> {data.Question}</p>
                <p className="mb-1"><strong>Pilihan Jawaban:</strong></p>
                <ol type="A">
                  {/* {data.pilihan.map((choice, i) => (
                    <li key={i}>{choice}</li>
                  ))} */}
                  <li key={0}>{data.OptionA}</li>
                  <li key={1}>{data.OptionB}</li>
                  <li key={2}>{data.OptionC}</li>
                  <li key={3}>{data.OptionD}</li>
                  {data.OptionE !== "Tidak ada" && (
                    <li key={4}>{data.OptionE}</li>
                  )}
                </ol>
                <p className="mb-1"><strong>Jawaban Benar:</strong> {data.Correct}</p>
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
};

export default DocImporter;
