import { useEffect } from "react";
import { useQuizStore } from "@root/quizes/store";
import { quizApi } from "@api/quiz";
import { setQuizes } from "@root/quizes/actions";
import { questionApi } from "@api/question";
import { setQuestions } from "@root/questions/actions";
import { resultApi } from "@api/result";
import { parseFilters } from "./helper";
import { setResults } from "@root/results/actions";

export const useGetData = (filterNew: string, filterDate: string): void => {
  const { editQuizId } = useQuizStore();

  useEffect(() => {
    const getData = async (): Promise<void> => {
      if (editQuizId !== null) {
        const [quizes, quizesError] = await quizApi.getList();

        if (quizesError) {
          console.error(
            "An error occurred while receiving data: ",
            quizesError,
          );

          return;
        }

        setQuizes(quizes);

        const [questions, questionsError] = await questionApi.getList({
          quiz_id: editQuizId,
        });

        if (questionsError) {
          return console.error(questionsError);
        }

        setQuestions(questions);

        const [result, resultError] = await resultApi.getList(
          editQuizId,
          0,
          parseFilters(filterNew, filterDate),
        );

        if (resultError || !result) {
          console.error(resultError);

          return;
        }

        if (result.total_count === 0) {
          console.error("No results found");
        }
        setResults(result);
      }
    };

    getData();
  }, [editQuizId, filterNew, filterDate, setResults]);
};
