'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';

// Define participant type to handle optional properties
interface Participant {
  id: string;
  name: string;
  email: string;
  class: string;
  status: string;
  progress: number;
  totalQuestions: number;
  startedAt: string | null;
  lastActivity: string | null;
  timeRemaining: number;
  currentQuestion: number;
  flaggedQuestions: number;
  ipAddress: string | null;
  completedAt?: string;
  score?: number;
}

const ExamMonitorPage: React.FC = () => {
  const params = useParams();
  const examId = params.id as string;
  const [currentTime, setCurrentTime] = useState(new Date());
  const [autoRefresh, setAutoRefresh] = useState(true);

  // Mock exam data
  const exam = {
    id: examId,
    title: 'Ujian Tengah Semester - Pemrograman Web',
    startDateTime: '2024-01-15T09:00:00',
    endDateTime: '2024-01-15T11:00:00',
    duration: 120,
    status: 'active',
    totalParticipants: 45,
    activeParticipants: 28,
    completedParticipants: 15,
    notStartedParticipants: 2
  };

  // Mock participants data with real-time status
  const [participants, setParticipants] = useState<Participant[]>([
    { 
      id: '1', 
      name: 'Ahmad Fauzi', 
      email: 'ahmad@student.ac.id', 
      class: 'TI-3A', 
      status: 'active', 
      progress: 15, 
      totalQuestions: 25, 
      startedAt: '2024-01-15T09:05:00',
      lastActivity: '2024-01-15T09:45:00',
      timeRemaining: 75,
      currentQuestion: 16,
      flaggedQuestions: 3,
      ipAddress: '192.168.1.101'
    },
    { 
      id: '2', 
      name: 'Siti Nurhaliza', 
      email: 'siti@student.ac.id', 
      class: 'TI-3A', 
      status: 'completed', 
      progress: 25, 
      totalQuestions: 25, 
      startedAt: '2024-01-15T09:02:00',
      lastActivity: '2024-01-15T10:30:00',
      timeRemaining: 0,
      currentQuestion: 25,
      flaggedQuestions: 0,
      ipAddress: '192.168.1.102',
      completedAt: '2024-01-15T10:30:00',
      score: 92
    },
    { 
      id: '3', 
      name: 'Budi Santoso', 
      email: 'budi@student.ac.id', 
      class: 'TI-3B', 
      status: 'active', 
      progress: 8, 
      totalQuestions: 25, 
      startedAt: '2024-01-15T09:15:00',
      lastActivity: '2024-01-15T09:42:00',
      timeRemaining: 93,
      currentQuestion: 9,
      flaggedQuestions: 2,
      ipAddress: '192.168.1.103'
    },
    { 
      id: '4', 
      name: 'Dewi Sartika', 
      email: 'dewi@student.ac.id', 
      class: 'TI-3B', 
      status: 'paused', 
      progress: 12, 
      totalQuestions: 25, 
      startedAt: '2024-01-15T09:08:00',
      lastActivity: '2024-01-15T09:35:00',
      timeRemaining: 85,
      currentQuestion: 13,
      flaggedQuestions: 1,
      ipAddress: '192.168.1.104'
    },
    { 
      id: '5', 
      name: 'Rizki Pratama', 
      email: 'rizki@student.ac.id', 
      class: 'TI-3C', 
      status: 'not_started', 
      progress: 0, 
      totalQuestions: 25, 
      startedAt: null,
      lastActivity: null,
      timeRemaining: 120,
      currentQuestion: 0,
      flaggedQuestions: 0,
      ipAddress: null
    }
  ]);

  // Mock recent activities
  const [recentActivities, setRecentActivities] = useState([
    { id: '1', participantName: 'Ahmad Fauzi', action: 'Menjawab soal #15', timestamp: '2024-01-15T09:45:00', type: 'answer' },
    { id: '2', participantName: 'Budi Santoso', action: 'Menandai soal #8 untuk review', timestamp: '2024-01-15T09:42:00', type: 'flag' },
    { id: '3', participantName: 'Siti Nurhaliza', action: 'Menyelesaikan ujian', timestamp: '2024-01-15T10:30:00', type: 'complete' },
    { id: '4', participantName: 'Dewi Sartika', action: 'Menjeda ujian', timestamp: '2024-01-15T09:35:00', type: 'pause' },
    { id: '5', participantName: 'Ahmad Fauzi', action: 'Memulai ujian', timestamp: '2024-01-15T09:05:00', type: 'start' }
  ]);

  // Update current time every second
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  // Auto refresh data every 30 seconds
  useEffect(() => {
    if (!autoRefresh) return;

    const refreshTimer = setInterval(() => {
      // Simulate data refresh
      console.log('Refreshing exam data...');
    }, 30000);

    return () => clearInterval(refreshTimer);
  }, [autoRefresh]);

  const formatDateTime = (dateString: string) => {
    return new Date(dateString).toLocaleString('id-ID', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const formatTimeRemaining = (minutes: number) => {
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    return `${hours}:${mins.toString().padStart(2, '0')}`;
  };

  const getStatusBadge = (status: string) => {
    const statusConfig = {
      not_started: { label: 'Belum Mulai', className: 'bg-gray-100 text-gray-800' },
      active: { label: 'Sedang Mengerjakan', className: 'bg-green-100 text-green-800' },
      paused: { label: 'Dijeda', className: 'bg-yellow-100 text-yellow-800' },
      completed: { label: 'Selesai', className: 'bg-blue-100 text-blue-800' },
      time_up: { label: 'Waktu Habis', className: 'bg-red-100 text-red-800' },
      disconnected: { label: 'Terputus', className: 'bg-red-100 text-red-800' }
    };

    const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.not_started;
    
    return (
      <span className={`px-2 py-1 rounded-full text-xs font-medium ${config.className}`}>
        {config.label}
      </span>
    );
  };

  const getActivityIcon = (type: string) => {
    switch (type) {
      case 'start':
        return '🚀';
      case 'answer':
        return '✏️';
      case 'flag':
        return '🏳️';
      case 'pause':
        return '⏸️';
      case 'complete':
        return '✅';
      default:
        return '📝';
    }
  };

  const handleForceSubmit = (participantId: string) => {
    if (confirm('Apakah Anda yakin ingin memaksa peserta ini untuk menyelesaikan ujian?')) {
      // Simulate force submit
      setParticipants(prev => 
        prev.map(p => 
          p.id === participantId 
            ? { 
                ...p, 
                status: 'completed', 
                completedAt: new Date().toISOString(),
                score: Math.floor(Math.random() * 40) + 60 // Random score between 60-100
              }
            : p
        )
      );
      alert('Peserta berhasil dipaksa menyelesaikan ujian');
    }
  };

  const handleKickParticipant = (participantId: string) => {
    if (confirm('Apakah Anda yakin ingin mengeluarkan peserta ini dari ujian?')) {
      // Simulate kick participant
      setParticipants(prev => 
        prev.map(p => 
          p.id === participantId 
            ? { ...p, status: 'disconnected' }
            : p
        )
      );
      alert('Peserta berhasil dikeluarkan dari ujian');
    }
  };

  return (
    <div className="max-w-7xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Monitor Ujian</h1>
          <p className="text-gray-600 mt-1">{exam.title}</p>
        </div>
        <div className="flex items-center space-x-4">
          <label className="flex items-center">
            <input
              type="checkbox"
              checked={autoRefresh}
              onChange={(e) => setAutoRefresh(e.target.checked)}
              className="w-4 h-4 text-blue-600 focus:ring-blue-500"
            />
            <span className="ml-2 text-sm text-gray-700">Auto Refresh</span>
          </label>
          <Link
            href={`/admin/exams/${examId}`}
            className="text-gray-600 hover:text-gray-900"
          >
            ← Kembali ke Detail
          </Link>
        </div>
      </div>

      {/* Exam Status */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div className="grid grid-cols-1 md:grid-cols-5 gap-6">
          <div className="text-center">
            <div className="text-2xl font-bold text-blue-600">{exam.totalParticipants}</div>
            <div className="text-sm text-gray-600">Total Peserta</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-green-600">{exam.activeParticipants}</div>
            <div className="text-sm text-gray-600">Sedang Mengerjakan</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-purple-600">{exam.completedParticipants}</div>
            <div className="text-sm text-gray-600">Selesai</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-orange-600">{exam.notStartedParticipants}</div>
            <div className="text-sm text-gray-600">Belum Mulai</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-gray-600">{currentTime.toLocaleTimeString('id-ID')}</div>
            <div className="text-sm text-gray-600">Waktu Sekarang</div>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Participants List */}
        <div className="lg:col-span-2">
          <div className="bg-white rounded-lg shadow-sm border border-gray-200">
            <div className="px-6 py-4 border-b border-gray-200">
              <h2 className="text-lg font-semibold text-gray-900">Daftar Peserta</h2>
            </div>
            
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Peserta
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Status
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Progress
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Waktu
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Aksi
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {participants.map((participant) => (
                    <tr key={participant.id} className="hover:bg-gray-50">
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div>
                          <div className="text-sm font-medium text-gray-900">{participant.name}</div>
                          <div className="text-sm text-gray-500">{participant.class}</div>
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        {getStatusBadge(participant.status)}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="text-sm text-gray-900">
                          {participant.progress}/{participant.totalQuestions} soal
                        </div>
                        <div className="w-full bg-gray-200 rounded-full h-2 mt-1">
                          <div 
                            className="bg-blue-600 h-2 rounded-full" 
                            style={{ width: `${(participant.progress / participant.totalQuestions) * 100}%` }}
                          ></div>
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        {participant.status === 'active' || participant.status === 'paused' ? (
                          <div>
                            <div>Sisa: {formatTimeRemaining(participant.timeRemaining)}</div>
                            <div className="text-xs text-gray-500">
                              Soal: {participant.currentQuestion}/{participant.totalQuestions}
                            </div>
                          </div>
                        ) : participant.status === 'completed' ? (
                          <div>
                            <div>Selesai</div>
                            {participant.score && (
                              <div className="text-xs text-gray-500">Nilai: {participant.score}%</div>
                            )}
                          </div>
                        ) : (
                          <div>-</div>
                        )}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        {participant.status === 'active' || participant.status === 'paused' ? (
                          <div className="flex space-x-2">
                            <button
                              onClick={() => handleForceSubmit(participant.id)}
                              className="text-orange-600 hover:text-orange-900"
                              title="Paksa Selesai"
                            >
                              ⏹️
                            </button>
                            <button
                              onClick={() => handleKickParticipant(participant.id)}
                              className="text-red-600 hover:text-red-900"
                              title="Keluarkan"
                            >
                              🚫
                            </button>
                          </div>
                        ) : (
                          <span className="text-gray-400">-</span>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>

        {/* Recent Activities */}
        <div className="space-y-6">
          <div className="bg-white rounded-lg shadow-sm border border-gray-200">
            <div className="px-6 py-4 border-b border-gray-200">
              <h2 className="text-lg font-semibold text-gray-900">Aktivitas Terbaru</h2>
            </div>
            
            <div className="p-6">
              <div className="space-y-4 max-h-96 overflow-y-auto">
                {recentActivities.map((activity) => (
                  <div key={activity.id} className="flex items-start space-x-3">
                    <div className="flex-shrink-0 text-lg">
                      {getActivityIcon(activity.type)}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="text-sm font-medium text-gray-900">
                        {activity.participantName}
                      </div>
                      <div className="text-sm text-gray-600">
                        {activity.action}
                      </div>
                      <div className="text-xs text-gray-500">
                        {formatDateTime(activity.timestamp)}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Exam Timer */}
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">Waktu Ujian</h3>
            <div className="space-y-3">
              <div className="flex justify-between">
                <span className="text-gray-600">Mulai:</span>
                <span className="font-medium">{formatDateTime(exam.startDateTime)}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-600">Selesai:</span>
                <span className="font-medium">{formatDateTime(exam.endDateTime)}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-600">Durasi:</span>
                <span className="font-medium">{exam.duration} menit</span>
              </div>
            </div>
          </div>

          {/* Quick Actions */}
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">Aksi Cepat</h3>
            <div className="space-y-3">
              <button className="w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                Kirim Pengumuman
              </button>
              <button className="w-full px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition-colors">
                Perpanjang Waktu
              </button>
              <button className="w-full px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors">
                Akhiri Ujian
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ExamMonitorPage;