import { useState, useEffect } from 'react';
import exerciseService from '../services/reviewService';

export const useReview = (stdLearning) => {
  const [questions, setQuestions] = useState([]);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [answers, setAnswers] = useState({});
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchData = async () => {
    try {
        const response = await exerciseService.fetchReview(stdLearning);
        setQuestions(response.payload.stdExercises);
    } catch (error) {
      console.error("something wrong : ", error);
      setError(error);
    }finally{
      setIsLoading(false);
    }
  };

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

  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]);

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