import React, { useState, useEffect } from 'react';
import { Modal } from 'antd';

interface Question {
  questionId: string;
  questionText: string;
  correctAnswer: string;
  options: string[];
}

interface Quiz {
  quizId: string;
  quizName: string;
  internalMarks: string;
  attendance: string;
  attendQuestion: string;
  totalQuestion: string;
  questions: Question[];
}

interface Module {
  moduleId: string;
  type: string;
  moduleName: string;
  quizzes: Quiz[];
}
interface QuestionList {
  questionId: string;
  questionText: string;
  correctAnswer: string;
  options: string[];
  moduleId: string;
}
interface ModuleList {
  moduleId: string;
}

export default function Index() {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedQuiz, setSelectedQuiz] = useState<Quiz | null>(null);
  const [quizModuleData, setQuizModuleData] = useState<Module[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  const [questionList, setQuestionList] = useState<QuestionList[]>([]);
const [moduleList, setModuleList] = useState<ModuleList[]>([]);

useEffect(() => {
  fetch(`https://api.teachertrainingkolkata.in/api/question-list`)
    .then((res) => {
      if (!res.ok) {
        throw new Error('Network Response not ok');
      }
      return res.json();
    })
    .then((questionData) => {
      setQuestionList(questionData);
      console.log('Question List', questionData);
    })
    .catch((error) => {
      console.error('Error fetching question list:', error);
    });
}, []);

useEffect(() => {
  if (questionList.length > 0) {
    const fetchModuleList = async () => {
      try {
        const moduleData = await Promise.all(
          questionList.map((question) =>
            fetch(`https://api.teachertrainingkolkata.in/api/quiz-module-list?module_id=${question.moduleId}`)
              .then((res) => {
                if (!res.ok) {
                  throw new Error('Network Response not ok');
                }
                return res.json();
              })
          )
        );
        setModuleList(moduleData.flat());
        console.log('Module List', moduleData.flat());
      } catch (error) {
        console.error('Error fetching module list:', error);
      }
    };

    fetchModuleList();
  }
}, [questionList]);


  



  useEffect(() => {
    fetch('https://api.teachertrainingkolkata.in/api/quiz-module')
      .then((res) => {
        if (!res.ok) {
          throw new Error('Network response was not ok');
        }
        return res.json();
      })
      .then((data) => {
        // console.log('Fetched data:', data);
        // Extract the modules array from the response
        if (data && Array.isArray(data.modules)) {
          setQuizModuleData(data.modules);
        } else {
          setError(new Error('Fetched data is not an array'));
        }
        setLoading(false);
      })
      .catch((error) => {
        console.error('Error fetching data:', error);
        setError(error);
        setLoading(false);
      });
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  const showModal = (quiz: Quiz) => {
    setSelectedQuiz(quiz);
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
    setSelectedQuiz(null);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
    setSelectedQuiz(null);
  };

  return (
    <section className="">
      <div className="flex flex-col">
        {quizModuleData.length > 0 ? (
          quizModuleData.map((moduleData) => (
            <div key={moduleData.moduleId}>
              <div className="p-6">
                <p className="text-[16px] font-[700] text-[#EF7A0C]">{moduleData.type}</p>
                <p className="text-[22px] font-[700]">{moduleData.moduleName}</p>
                <p className="text-[14px] font-[600]">3/8 Quizzes Completed </p>
              </div>
              <div className="flex flex-col">
                {moduleData.quizzes.map((quizData) => (
                  <div onClick={() => showModal(quizData)} className="flex flex-row justify-between place-items-center hover:bg-[#FFF4EA] duration-500 border-b-[1px] border-b-[#CFCFCF] p-6 cursor-pointer" key={quizData.quizId}>
                    <div className="flex flex-col space-y-2">
                      <h3 className="text-[20px] font-[700]">
                        #{quizData.quizId} {quizData.quizName}
                      </h3>
                      <p className="text-[16px] font-[700] text-[#6E6E6E]">
                        <span>Internal Marks: {quizData.internalMarks}</span>
                        &nbsp;&#8226; &nbsp;
                        <span>Attendance: {quizData.attendance}</span>
                      </p>
                    </div>
                    <div className="flex flex-row space-x-4">
                      <p className="bg-[#FFE2C7] p-2 rounded-[8px]">
                        <span className="text-[32px] font-[700] text-[#EF7A0C]">{quizData.attendQuestion}</span>/
                        <span className="text-[16px] font-[700] ">{quizData.totalQuestion}</span>
                      </p>
                      <img src="/assets/right-arrow.svg" alt="" />
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ))
        ) : (
          <div>No quiz modules available.</div>
        )}
      </div>
      {selectedQuiz && (
        <Modal title={selectedQuiz.quizName} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} width={1000}>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 border-b-[1px] border-b-[#CFCFCF]">
            <div className="flex justify-center place-items-center border-r-[1px] border-[#CFCFCF] my-3">
              <div className="flex flex-row space-x-2">
                <div className="w-[53px] h-[53px] bg-[#FFF1E3] rounded-full flex justify-center place-items-center">
                  <img className=" " src="../../assets/calendar.svg" alt="" />
                </div>
                <div className="flex flex-col">
                  <p className="text-[20px] font-[800]">18/10</p>
                  <p className="text-[14px] font-[600] text-[#414141]">Attendance</p>
                </div>
              </div>
            </div>

            <div className="flex justify-center place-items-center border-r-[1px] border-[#CFCFCF] my-3">
              <div className="flex flex-row space-x-2">
                <div className="w-[53px] h-[53px] bg-[#FFF1E3] rounded-full flex justify-center place-items-center">
                  <img className=" " src="../../assets/note.svg" alt="" />
                </div>
                <div className="flex flex-col">
                  <p className="text-[20px] font-[800]">
                    12 <span className="text-[14px] font-[500]">Questions</span>
                  </p>
                  <p className="text-[14px] font-[600] text-[#414141]">Attempted</p>
                </div>
              </div>
            </div>

            <div className="flex justify-center place-items-center my-3">
              <div className="flex flex-row space-x-2">
                <div className="w-[53px] h-[53px] bg-[#FFF1E3] rounded-full flex justify-center place-items-center">
                  <img className=" " src="../../assets/note.svg" alt="" />
                </div>
                <div className="flex flex-col">
                  <p className="text-[20px] font-[800]">
                    12 <span className="text-[14px] font-[500]">Correct</span>
                  </p>
                  <p className="text-[14px] font-[600] text-[#414141]">Attempts</p>
                </div>
              </div>
            </div>
          </div>
          {questionList.map((questionData) => (
            <div key={questionData.questionId} className="mb-4 px-10 flex flex-col space-y-2">
              <p className="text-[20px] font-[700]">
                Q{questionData.questionId}: {questionData.questionText}
              </p>
              <p className="text-[16px] font-[600] text-[#EF7A0C]">Your Answer</p>
              <p className="text-[20px] font-[500]">{questionData.correctAnswer}</p>
              <div className="inline-flex place-items-center space-x-4 w-full border-[1px] border-[#218B32] rounded-[10px] p-3">
                <p className="text-[14px] font-[700] text-[#218B32] inline-flex place-items-center">
                  <img src="../../assets/green-tick.svg" alt="" /> &nbsp;Correct
                </p>
                <p className="text-[14px] font-[400]"> {questionData.correctAnswer}</p>
              </div>
              <ul>
                {/* {questionData.options.map((option, index) => (
                  <li key={index}>{option}</li>
                ))} */}
              </ul>
            </div>
          ))}
        </Modal>
      )}
    </section>
  );
}
