import { questionApi } from "@api/question";
import { devlog } from "@frontend/kitui";
import { isAxiosError } from "axios";
import { enqueueSnackbar } from "notistack";
import useSWR from "swr";
import { setQuestions } from "./actions";
import { useQuestionsStore } from "./store";
import { useCurrentQuiz } from "@root/quizes/hooks";


export function useQuestions() {
    const quiz = useCurrentQuiz();
    const { isLoading, error, isValidating } = useSWR(["questions", quiz?.backendId], ([, id]) => questionApi.getList({ quiz_id: id }), {
        onSuccess: setQuestions,
        onError: error => {
            const message = isAxiosError<string>(error) ? (error.response?.data ?? "") : "";

            devlog("Error getting question list", error);
            enqueueSnackbar(`Не удалось получить вопросы. ${message}`);
        }
    });
    const questions = useQuestionsStore(state => state.questions);

    return { questions, isLoading, error, isValidating };
}
