fix(ui): fix exam and result screen ui

This commit is contained in:
shafin-r
2025-07-07 17:52:01 +06:00
parent 48519c42c3
commit 22eb8285ec
8 changed files with 554 additions and 364 deletions

View File

@ -1,8 +1,9 @@
"use client";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import React, { useEffect, useState, useCallback, useReducer } from "react";
import React, { useEffect, useState, useCallback } from "react";
import { useTimer } from "@/context/TimerContext";
import { useExam } from "@/context/ExamContext";
import { API_URL, getToken } from "@/lib/auth";
import Header from "@/components/Header";
@ -19,16 +20,6 @@ interface QuestionItemProps {
handleSelect: (questionId: number, option: string) => void;
}
interface AnswerState {
[questionId: number]: string;
}
interface AnswerAction {
type: "SELECT_ANSWER";
questionId: number;
option: string;
}
// Components
const QuestionItem = React.memo<QuestionItemProps>(
({ question, selectedAnswer, handleSelect }) => (
@ -62,30 +53,58 @@ const QuestionItem = React.memo<QuestionItemProps>(
QuestionItem.displayName = "QuestionItem";
const reducer = (state: AnswerState, action: AnswerAction): AnswerState => {
switch (action.type) {
case "SELECT_ANSWER":
return { ...state, [action.questionId]: action.option };
default:
return state;
}
};
export default function ExamPage() {
const router = useRouter();
const params = useParams();
const searchParams = useSearchParams();
const [isSubmitting, setIsSubmitting] = useState(false);
const id = params.id as string;
const time = searchParams.get("time");
const { setInitialTime, stopTimer } = useTimer();
// Use exam context instead of local state
const {
currentAttempt,
setAnswer,
getAnswer,
submitExam: submitExamContext,
setApiResponse,
isExamStarted,
isExamCompleted,
isHydrated,
isInitialized,
} = useExam();
const [questions, setQuestions] = useState<Question[] | null>(null);
const [answers, dispatch] = useReducer(reducer, {});
const [loading, setLoading] = useState(true);
const [submissionLoading, setSubmissionLoading] = useState(false);
// Check if exam is properly started
useEffect(() => {
if (!isHydrated) return;
if (!isInitialized) return;
if (isSubmitting) return; // Don't redirect while submitting
if (!isExamStarted()) {
router.push("/unit");
return;
}
if (isExamCompleted()) {
router.push("/exam/results");
return;
}
}, [
isHydrated,
isExamStarted,
isExamCompleted,
router,
isInitialized,
isSubmitting,
]);
const fetchQuestions = async () => {
try {
const response = await fetch(`${API_URL}/mock/${id}`, {
@ -107,17 +126,33 @@ export default function ExamPage() {
}
}, [id, time, setInitialTime]);
const handleSelect = useCallback((questionId: number, option: string) => {
dispatch({ type: "SELECT_ANSWER", questionId, option });
}, []);
const handleSelect = useCallback(
(questionId: number, option: string) => {
// Store answer in context instead of local reducer
setAnswer(questionId.toString(), option);
},
[setAnswer]
);
const handleSubmit = async () => {
if (!currentAttempt) {
console.error("No exam attempt found");
return;
}
stopTimer();
setSubmissionLoading(true);
setIsSubmitting(true); // Add this line
// Convert context answers to the format your API expects
const answersForAPI = currentAttempt.answers.reduce((acc, answer) => {
acc[parseInt(answer.questionId)] = answer.answer;
return acc;
}, {} as Record<number, string>);
const payload = {
mock_id: id,
data: answers,
data: answersForAPI,
};
try {
@ -136,18 +171,24 @@ export default function ExamPage() {
"Submission failed:",
errorData.message || "Unknown error"
);
setIsSubmitting(false); // Reset on error
return;
}
const responseData = await response.json();
router.push(
`/exam/results?id=${id}&answers=${encodeURIComponent(
JSON.stringify(responseData)
)}`
);
// Submit exam in context (this will store the completed attempt)
const completedAttempt = submitExamContext();
// Store API response in context for results page
setApiResponse(responseData);
// Navigate to results without URL parameters
router.push("/exam/results");
console.log("I'm here");
} catch (error) {
console.error("Error submitting answers:", error);
setIsSubmitting(false); // Reset on error
} finally {
setSubmissionLoading(false);
}
@ -215,7 +256,7 @@ export default function ExamPage() {
<QuestionItem
key={question.id}
question={question}
selectedAnswer={answers[question.id]}
selectedAnswer={getAnswer(question.id.toString())}
handleSelect={handleSelect}
/>
))}
@ -234,85 +275,6 @@ export default function ExamPage() {
</div>
</div>
</div>
<style jsx>{`
.question-container {
border: 1px solid #8abdff;
border-radius: 25px;
padding: 20px;
margin-bottom: 20px;
background: white;
}
.question-text {
font-size: 18px;
font-weight: 600;
margin-bottom: 10px;
color: #1a1a1a;
}
.options-container {
display: flex;
flex-direction: column;
gap: 8px;
}
.option-button {
display: flex;
align-items: center;
gap: 10px;
padding: 6px 0;
border-radius: 5px;
border: 1px solid transparent;
background: none;
cursor: pointer;
transition: all 0.2s ease;
}
.option-button:hover {
background-color: #f8f9fa;
}
.selected-option {
background-color: #f0f8ff;
}
.option-text {
font-size: 14px;
padding: 4px 10px;
border-radius: 25px;
text-align: center;
border: 1px solid #ddd;
min-width: 32px;
font-weight: 500;
}
.selected-option-text {
color: white;
background-color: #113768;
border-color: #113768;
}
.option-description {
font-size: 16px;
color: #333;
}
@media (max-width: 768px) {
.question-container {
padding: 16px;
border-radius: 16px;
}
.question-text {
font-size: 16px;
}
.option-description {
font-size: 14px;
}
}
`}</style>
</div>
);
}