import { useParams } from "react-router-dom";
import Container from "../../components/shared/Container";
import { useUserTestById } from "../../hooks/tests/useUserTestById";
import { useState } from "react";
import { Box, Button, Pagination, Typography } from "@mui/material";
import TestQuestion from "../../components/TestQuestion/TestQuestion";
import { useSubmitAnswer } from "../../hooks/tests/useSubmitAnswer";
import { useCompleteTest } from "../../hooks/tests/useCompleteTest";
import LearningAnswers from "../../components/Answers/Answers";
import { formatDate } from "../../utils/functions";
import NotFoundPage from "../NotFoundPage/NotFoundPage";
import { useAuth } from "../../context/AuthContext";
import { useGetTestById } from "../../hooks/tests/useGetTestById";
export const TestPage = () => {
const { id } = useParams();
const { user } = useAuth();
const { data: test, isLoading, error } = useUserTestById(Number(id));
const [currentQuestion, setCurrentQuestion] = useState(1);
const submitAnswerMutation = useSubmitAnswer();
const completeTestMutation = useCompleteTest();
const allAnswered = test?.answers?.every((ans) => ans.answer !== null);
const { data: createdTest } = useGetTestById(test?.test_id ?? undefined);
const handleCompleteTest = () => {
if (test) completeTestMutation.mutate(test.id);
};
if (isLoading)
return (
Loading your test, please wait...
);
if (error) return ;
if (!test) return ;
if (!test.is_available && !test.is_completed && user?.type == "user")
return (
This test is no longer available.
);
if (test.is_completed) {
return (
Results
Your score: {test.score}%
{test?.answers?.map((ans) => (
{ans.question.title}
{ans.question.description}
))}
);
}
const questionsAndAnswers = test.answers;
const currentQA = questionsAndAnswers?.[currentQuestion - 1];
return (
{createdTest?.title ?? "User Test"}
Expires at: {test.closed_at ? formatDate(test.closed_at) : "N/A"}
{currentQA ? (
submitAnswerMutation.mutate({
answerId: questionsAndAnswers[currentQuestion - 1].id,
answer: ans,
})
}
/>
) : (
No question found.
)}
setCurrentQuestion(page)}
/>
{currentQuestion == questionsAndAnswers?.length && (
)}
{currentQuestion == questionsAndAnswers?.length && !allAnswered && (
You must answer all questions before completing the test
)}
);
};