import { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import exerciseService from '../services/exerciseService';
import { useSlugContext } from '../../../../utils/SlugContext';
import { unSlugify } from '../../../../utils/Constant';

export const useExercises = (topic, level) => {
  const [questions, setQuestions] = useState([]);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [answers, setAnswers] = useState({});
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [levelId, setLevelId] = useState(null);
  const [learningId, setLearningId] = useState(null);
  const { topicSlugMap } = useSlugContext();
  
  const { section } = useParams();
  const navigate = useNavigate();

  const fetchData = async () => {
    try {
        const getLevelId = await exerciseService.getLevelId(topicSlugMap[topic], unSlugify(level));
        setLevelId(getLevelId);

        const stdLearning = await exerciseService.createStdLearning({ ID_LEVEL: getLevelId });
        setLearningId(stdLearning.payload.ID_STUDENT_LEARNING);

        const data = await exerciseService.fetchExercise(getLevelId);
        setQuestions(data);
        if (localStorage.getItem(stdLearning.payload.ID_STUDENT_LEARNING)) {
            // const savedAnswers = JSON.parse(localStorage.getItem(getLevelId));
            const savedAnswers = JSON.parse(localStorage.getItem(stdLearning.payload.ID_STUDENT_LEARNING));
            setAnswers(savedAnswers);
        }else{
            setAnswers(new Array(data.length).fill(null));
        }
    } catch (error) {
      console.error("something wrong : ", error);
      setError(error);
    }finally{
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [topic, level]);

  const handleAnswer = (index, answer, qId) => {
    const newAnswers = [...answers];
    newAnswers[index] = {
        ID_STUDENT_LEARNING: learningId,
        ID_ADMIN_EXERCISE: qId,
        ANSWER_STUDENT: answer
    };
    setAnswers(newAnswers);
    localStorage.setItem(learningId, JSON.stringify(newAnswers));
  };

  const nextQuestion = () => {
    if (currentQuestionIndex < questions.length - 1) {
      setCurrentQuestionIndex(currentQuestionIndex + 1);
    }
  };

  const prevQuestion = () => {
    if (currentQuestionIndex > 0) {
      setCurrentQuestionIndex(currentQuestionIndex - 1);
    }
  };

  useEffect(() => {
    const handleKeyDown = (event) => {
      if (event.key === 'ArrowLeft') {
        prevQuestion(); 
      } else if (event.key === 'ArrowRight') {
        nextQuestion(); 
      }
    };

    window.addEventListener('keydown', handleKeyDown);

    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [prevQuestion, nextQuestion]);

  const handleSubmit = () => {
    const allAnswered = answers.every((answer) => answer !== null);
    return allAnswered;
  };

  const handleConfirmSubmit = async () => {
    const answer = JSON.parse(localStorage.getItem(learningId));
    try {
      const sendAnswer = await exerciseService.sumbitAnswer({ answers: answer });
    } catch (error) {
      console.error(error);
    }finally{
      navigate(`/learning/module/${section}/${topic}/${level}/result`);
    }
  };

  return {
    questions,
    currentQuestion: questions[currentQuestionIndex],
    currentQuestionIndex,
    setCurrentQuestionIndex, 
    answers,
    isLoading,
    error,
    handleAnswer,
    nextQuestion,
    prevQuestion,
    handleSubmit,
    handleConfirmSubmit,
  };
};
