'use client' import { useState } from 'react' import { useRouter } from 'next/navigation' export default function CreateExam() { const [examData, setExamData] = useState({ title: 'String Capitalizer Challenge', host_name: '', duration_minutes: 30, max_participants: 50, problem_id: 'string-capitalizer' }) const [loading, setLoading] = useState(false) const [result, setResult] = useState('') const [error, setError] = useState('') const router = useRouter() const handleInputChange = (field: string, value: any) => { setExamData(prev => ({ ...prev, [field]: value })) setError('') } const createExam = async () => { // Clear previous messages setError('') setResult('') // Validation if (!examData.title.trim()) { setError('Please enter exam title') return } if (!examData.host_name.trim()) { setError('Please enter host name') return } setLoading(true) setResult('⏳ Creating exam...') try { const payload = { title: examData.title.trim(), problem_id: examData.problem_id, duration_minutes: examData.duration_minutes, host_name: examData.host_name.trim(), max_participants: examData.max_participants } console.log('📤 Sending payload:', payload) const response = await fetch('http://127.0.0.1:5000/api/exam/create-exam', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify(payload) }) console.log('📡 Response status:', response.status) const data = await response.json() console.log('📦 Full backend response:', data) if (data.success) { // ✅ ENHANCED DEBUGGING - Log all fields console.log('🔍 All response fields:', Object.keys(data)) console.log('📝 exam_code field:', data.exam_code) console.log('🗄️ exam_id field:', data.exam_id) console.log('📋 exam_details:', data.exam_details) // ✅ CORRECTED: Use exam_code, NOT exam_id const participantCode = data.exam_code // This should be "JEX99M" const databaseId = data.exam_id // This is the MongoDB ObjectId console.log('📝 Participant Code (CORRECT for sharing):', participantCode) console.log('🗄️ Database ID (internal only):', databaseId) // ✅ ENHANCED: Check if exam_code exists if (!participantCode) { console.error('❌ ERROR: exam_code is missing from response!') setError('Backend did not return exam_code. Check backend logs.') return } // ✅ SIMPLIFIED SUCCESS MESSAGE - Easier to spot issues const simpleAlert = `Exam created! Share this code with participants: ${participantCode}` // ✅ DETAILED SUCCESS MESSAGE for result display const successMessage = `🎉 EXAM CREATED SUCCESSFULLY! 📝 EXAM CODE FOR PARTICIPANTS: ┌─────────────────┐ │ ${participantCode} │ └─────────────────┘ 📋 Exam Details: • Title: ${data.exam_details?.title || examData.title} • Duration: ${data.exam_details?.duration || examData.duration_minutes} minutes • Max Participants: ${data.exam_details?.max_participants || examData.max_participants} • Host: ${examData.host_name} • Languages: ${data.exam_details?.languages?.join(', ') || 'Python'} 🔗 Share this code with participants: ${participantCode} 📱 Join URL: localhost:3000/coding/join ⚠️ IMPORTANT: Give participants "${participantCode}", NOT the database ID "${databaseId}"! ✅ Participants will use: ${participantCode}` setResult(successMessage) // ✅ SIMPLE ALERT - This should show the correct code alert(simpleAlert) // ✅ ADDITIONAL PROMINENT ALERT setTimeout(() => { alert(`✅ EXAM CODE: ${participantCode} Share this 6-character code with participants. They will enter: ${participantCode}`) }, 500) // Store the correct exam code for host dashboard localStorage.setItem('created_exam', JSON.stringify({ exam_code: participantCode, // 6-character code for participants exam_id: databaseId, // Internal database ID exam_details: data.exam_details, host_name: examData.host_name, created_at: new Date().toISOString() })) // Redirect to host dashboard after 5 seconds (increased time) setTimeout(() => { router.push(`/coding/host/${participantCode}`) }, 5000) } else { setError(data.error || 'Failed to create exam') setResult('') } } catch (error) { console.error('❌ Network error:', error) setError('Network error: Could not connect to backend server') setResult('') } finally { setLoading(false) } } return (
{/* Header */}

Create Coding Exam

Set up a new coding challenge for participants

{/* Form */}
handleInputChange('title', e.target.value)} placeholder="Enter exam title" className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent" required />
handleInputChange('host_name', e.target.value)} placeholder="Enter your name" className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent" required />
handleInputChange('duration_minutes', parseInt(e.target.value) || 30)} min="5" max="180" className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent" />
handleInputChange('max_participants', parseInt(e.target.value) || 50)} min="1" max="200" className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent" />
{/* Error Display */} {error && (
{error}
)} {/* Success Result Display */} {result && (
{result}
)} {/* Enhanced Debug Info */}

Debug Info:

Title: "{examData.title}"

Host: "{examData.host_name}"

Duration: {examData.duration_minutes} minutes

✅ Will show exam_code (6 chars), NOT exam_id

🔍 Check browser console for detailed logs

{/* Features Info */}

Exam Features:

Real-time participant tracking
Live leaderboard
Multi-language support
Timed exam sessions
) }