'use client' import React, { useState, useEffect } from 'react' import { useParams, useRouter } from 'next/navigation' import { Brain, Clock, CheckCircle, XCircle, Sparkles, AlertCircle } from 'lucide-react' interface Question { id: string question_number: number question_text: string options: string[] correct_answer: string points: number ai_prediction?: any } interface Quiz { id: string title: string description: string questions: Question[] generated_by?: string total_points: number } export default function QuizTaking() { const params = useParams() const router = useRouter() const quizId = params.quizId as string const [quiz, setQuiz] = useState(null) const [currentQuestion, setCurrentQuestion] = useState(0) const [answers, setAnswers] = useState>({}) const [loading, setLoading] = useState(true) const [submitting, setSubmitting] = useState(false) const [results, setResults] = useState(null) const [showAIHint, setShowAIHint] = useState(false) const [aiPrediction, setAIPrediction] = useState(null) const [error, setError] = useState('') useEffect(() => { fetchQuiz() }, [quizId]) const fetchQuiz = async () => { try { const response = await fetch(`http://127.0.0.1:5000/api/quizzes/${quizId}`) const data = await response.json() if (data.success) { setQuiz(data.quiz) } else { setError(data.error || 'Quiz not found') } } catch (err) { setError('Failed to load quiz') } finally { setLoading(false) } } const getAIHint = async () => { if (!quiz || !quiz.questions[currentQuestion]) return try { setShowAIHint(true) const response = await fetch('http://127.0.0.1:5000/api/quizzes/ai-predict', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ question_text: quiz.questions[currentQuestion].question_text }) }) const data = await response.json() if (data.success) { setAIPrediction(data.prediction) } } catch (err) { console.error('Failed to get AI hint:', err) } } const handleAnswerSelect = (questionId: string, answer: string) => { setAnswers(prev => ({ ...prev, [questionId]: answer })) } const submitQuiz = async () => { if (!quiz) return const unanswered = quiz.questions.filter(q => !answers[q.id]) if (unanswered.length > 0) { if (!confirm(`You have ${unanswered.length} unanswered questions. Submit anyway?`)) { return } } setSubmitting(true) try { const token = localStorage.getItem("openlearnx_jwt_token") || localStorage.getItem("openlearnx_token") const storedUserRaw = localStorage.getItem("openlearnx_user") const storedUser = storedUserRaw ? JSON.parse(storedUserRaw) : null const response = await fetch(`http://127.0.0.1:5000/api/quizzes/${quizId}/submit`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) }, body: JSON.stringify({ answers, participant_name: storedUser?.name || storedUser?.username || 'User', user_id: storedUser?.id, wallet_address: storedUser?.wallet_address }) }) const data = await response.json() if (data.success) { setResults(data.results) } else { setError(data.error || 'Failed to submit quiz') } } catch (err) { setError('Failed to submit quiz') } finally { setSubmitting(false) } } if (loading) { return (

Loading AI Quiz...

) } if (error) { return (

{error}

) } if (results) { return (
{results.score >= 80 ? '🏆' : results.score >= 60 ? '🎉' : '📚'}

Quiz Complete!

You scored {results.score}% ({results.correct_answers}/{results.total_questions})

{/* AI Feedback */} {results.ai_feedback && (

🤖 AI Feedback

{results.ai_feedback.map((feedback: any, index: number) => (

Question {index + 1}

{feedback.question}

{feedback.is_correct ? ( ) : ( )} Your answer: {feedback.user_answer}
{feedback.ai_feedback && (

🤖 {feedback.ai_feedback.feedback}

)}
))}
)}
) } if (!quiz) return null const question = quiz.questions[currentQuestion] const progress = ((currentQuestion + 1) / quiz.questions.length) * 100 return (
{/* Header */}

{quiz.generated_by === 'AI' && } {quiz.title}

Question {currentQuestion + 1} of {quiz.questions.length}
{/* Progress Bar */}
{/* Question */}

{question.question_text}

{quiz.generated_by === 'AI' && ( )}
{/* AI Hint */} {showAIHint && aiPrediction && (

🤖 AI Suggestion

AI predicts: {aiPrediction.predicted_answer}

Confidence: {(aiPrediction.confidence * 100).toFixed(1)}%

)} {/* Options */}
{question.options.map((option, index) => ( ))}
{/* Navigation */}
{Object.keys(answers).length} of {quiz.questions.length} answered
{currentQuestion === quiz.questions.length - 1 ? ( ) : ( )}
) }