'use client' import React, { useState, useEffect } from 'react' import { useRouter } from 'next/navigation' import { Users, Plus, Trash2, Play, Square, Settings, Brain, Crown, Target } from 'lucide-react' interface Question { question_id: string question_text: string options: string[] correct_answer: string difficulty: 'easy' | 'medium' | 'hard' points: number explanation: string } interface Participant { session_id: string username: string score: number current_difficulty: string total_questions: number correct_answers: number status: string } interface QuizRoom { room_id: string room_code: string title: string host_name: string is_private: boolean status: string questions: Question[] participants: Participant[] max_participants: number duration_minutes: number participants_count?: number questions_count?: number questions_by_difficulty?: { easy: number medium: number hard: number } } export default function QuizHostPanel() { const router = useRouter() const [currentRoom, setCurrentRoom] = useState(null) const [activeTab, setActiveTab] = useState<'setup' | 'questions' | 'participants' | 'live'>('setup') const [showCreateRoom, setShowCreateRoom] = useState(false) const [showAddQuestion, setShowAddQuestion] = useState(false) const [showAIGenerate, setShowAIGenerate] = useState(false) // Room creation form const [roomForm, setRoomForm] = useState({ host_name: '', room_title: '', is_private: false, max_participants: 50, duration_minutes: 30 }) // Question form const [questionForm, setQuestionForm] = useState({ question_text: '', options: ['', '', '', ''], correct_answer: '', difficulty: 'medium' as 'easy' | 'medium' | 'hard', points: 10, explanation: '' }) // AI generation form const [aiForm, setAiForm] = useState({ topic: '', num_easy: 3, num_medium: 3, num_hard: 2 }) const createRoom = async () => { try { const response = await fetch('http://127.0.0.1:5000/api/quizzes/create-room', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(roomForm) }) const data = await response.json() console.log('Room creation response:', data) // Debug log if (data.success) { // Ensure the room has all required properties const room = { ...data.room, status: data.room.status || 'waiting', participants: data.room.participants || [], questions: data.room.questions || [] } console.log('Room object:', room) // Debug log setCurrentRoom(room) setShowCreateRoom(false) setActiveTab('questions') alert(`🎉 Room created! Code: ${room.room_code}`) } else { alert(`Error: ${data.error}`) } } catch (error) { console.error('Room creation error:', error) alert('Network error: Could not create room') } } const addQuestion = async () => { if (!currentRoom) return if (!questionForm.question_text || questionForm.options.some(opt => !opt.trim()) || !questionForm.correct_answer) { alert('Please fill all question fields') return } try { const response = await fetch(`http://127.0.0.1:5000/api/quizzes/room/${currentRoom.room_code}/add-question`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(questionForm) }) const data = await response.json() if (data.success) { // Refresh room data fetchRoomData() setShowAddQuestion(false) setQuestionForm({ question_text: '', options: ['', '', '', ''], correct_answer: '', difficulty: 'medium', points: 10, explanation: '' }) alert('✅ Question added successfully!') } else { alert(`Error: ${data.error}`) } } catch (error) { alert('Network error: Could not add question') } } const generateAIQuestions = async () => { if (!currentRoom) return try { const response = await fetch(`http://127.0.0.1:5000/api/quizzes/room/${currentRoom.room_code}/generate-ai-questions`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(aiForm) }) const data = await response.json() if (data.success) { fetchRoomData() setShowAIGenerate(false) alert(`🤖 Generated ${data.questions.length} AI questions!`) } else { alert(`Error: ${data.error}`) } } catch (error) { alert('Network error: Could not generate questions') } } const removeQuestion = async (questionId: string) => { if (!currentRoom || !confirm('Remove this question?')) return try { const response = await fetch(`http://127.0.0.1:5000/api/quizzes/room/${currentRoom.room_code}/remove-question/${questionId}`, { method: 'DELETE' }) const data = await response.json() if (data.success) { fetchRoomData() alert('✅ Question removed') } else { alert(`Error: ${data.error}`) } } catch (error) { alert('Network error: Could not remove question') } } const removeParticipant = async (username: string) => { if (!currentRoom || !confirm(`Remove ${username} from the quiz?`)) return try { const response = await fetch(`http://127.0.0.1:5000/api/quizzes/room/${currentRoom.room_code}/remove-participant/${username}`, { method: 'DELETE' }) const data = await response.json() if (data.success) { fetchRoomData() alert(`✅ Removed ${username}`) } else { alert(`Error: ${data.error}`) } } catch (error) { alert('Network error: Could not remove participant') } } const startQuiz = async () => { if (!currentRoom) return if (currentRoom.questions.length === 0) { alert('Add questions before starting the quiz!') return } if (!confirm('Start the quiz now? Participants will begin answering questions.')) return try { const response = await fetch(`http://127.0.0.1:5000/api/quizzes/room/${currentRoom.room_code}/start`, { method: 'POST' }) const data = await response.json() if (data.success) { fetchRoomData() setActiveTab('live') alert('🚀 Quiz started!') } else { alert(`Error: ${data.error}`) } } catch (error) { alert('Network error: Could not start quiz') } } const endQuiz = async () => { if (!currentRoom || !confirm('End the quiz now?')) return try { const response = await fetch(`http://127.0.0.1:5000/api/quizzes/room/${currentRoom.room_code}/end`, { method: 'POST' }) const data = await response.json() if (data.success) { fetchRoomData() alert('✅ Quiz ended!') } else { alert(`Error: ${data.error}`) } } catch (error) { alert('Network error: Could not end quiz') } } const fetchRoomData = async () => { if (!currentRoom) return try { const response = await fetch(`http://127.0.0.1:5000/api/quizzes/room/${currentRoom.room_code}/info`) const data = await response.json() if (data.success) { setCurrentRoom(data.room) } } catch (error) { console.error('Failed to fetch room data:', error) } } // Poll for live updates when quiz is active useEffect(() => { if (currentRoom?.status === 'active') { const interval = setInterval(fetchRoomData, 3000) return () => clearInterval(interval) } }, [currentRoom?.status]) const getDifficultyColor = (difficulty: string) => { switch (difficulty) { case 'easy': return 'text-green-400 bg-green-900' case 'medium': return 'text-yellow-400 bg-yellow-900' case 'hard': return 'text-red-400 bg-red-900' default: return 'text-gray-400 bg-gray-700' } } const getStatusColor = (status: string) => { switch (status) { case 'waiting': return 'text-yellow-400 bg-yellow-900' case 'active': return 'text-green-400 bg-green-900' case 'completed': return 'text-gray-400 bg-gray-700' default: return 'text-gray-400 bg-gray-700' } } // Safe status getter const roomStatus = currentRoom?.status || 'waiting' if (!currentRoom) { return (

👑 Quiz Host Panel

Create and manage adaptive quizzes with AI-powered questions

Create New Quiz Room

setRoomForm(prev => ({...prev, host_name: e.target.value}))} className="w-full p-3 bg-gray-700 rounded border border-gray-600 focus:ring-2 focus:ring-blue-500 focus:outline-none" /> setRoomForm(prev => ({...prev, room_title: e.target.value}))} className="w-full p-3 bg-gray-700 rounded border border-gray-600 focus:ring-2 focus:ring-blue-500 focus:outline-none" />
setRoomForm(prev => ({...prev, max_participants: parseInt(e.target.value) || 50}))} className="p-3 bg-gray-700 rounded border border-gray-600 focus:ring-2 focus:ring-blue-500 focus:outline-none" min="1" max="100" /> setRoomForm(prev => ({...prev, duration_minutes: parseInt(e.target.value) || 30}))} className="p-3 bg-gray-700 rounded border border-gray-600 focus:ring-2 focus:ring-blue-500 focus:outline-none" min="5" max="180" />
) } return (
{/* Header */}

{currentRoom.title}

Code: {currentRoom.room_code} {roomStatus.toUpperCase()} 👥 {currentRoom.participants?.length || 0}/{currentRoom.max_participants} ❓ {currentRoom.questions?.length || 0} questions
{roomStatus === 'waiting' && ( )} {roomStatus === 'active' && ( )}
{/* Tabs */}
{[ { id: 'questions', label: `Questions (${currentRoom.questions?.length || 0})`, icon: Target }, { id: 'participants', label: `Participants (${currentRoom.participants?.length || 0})`, icon: Users }, { id: 'live', label: 'Live View', icon: Play } ].map(tab => ( ))}
{/* Questions Tab */} {activeTab === 'questions' && (

📝 Question Management

{/* Questions by Difficulty */} {['easy', 'medium', 'hard'].map(difficulty => { const difficultyQuestions = (currentRoom.questions || []).filter(q => q.difficulty === difficulty) return (

{difficulty.toUpperCase()} ({difficultyQuestions.length} questions)

{difficultyQuestions.map((question, index) => (

{question.question_text}

{question.options.map((option, optIndex) => ( {String.fromCharCode(65 + optIndex)}) {option} ))}
Points: {question.points} | Correct: {question.correct_answer}
))} {difficultyQuestions.length === 0 && (
No {difficulty} questions yet
)}
) })} {/* Add Question Modal */} {showAddQuestion && (

➕ Add New Question