'use client';

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

const ExamDetailPage: React.FC = () => {
  const params = useParams();
  const examId = params.id as string;

  // Mock exam data
  const exam = {
    id: examId,
    title: 'Ujian Tengah Semester - Pemrograman Web',
    description: 'Ujian tengah semester untuk mata kuliah Pemrograman Web yang mencakup HTML, CSS, JavaScript, dan React.',
    startDateTime: '2024-01-15T09:00:00',
    endDateTime: '2024-01-15T11:00:00',
    duration: 120,
    passingScore: 70,
    maxAttempts: 1,
    shuffleQuestions: true,
    shuffleAnswers: true,
    showResults: 'after_completion',
    allowReview: true,
    instructions: 'Bacalah setiap soal dengan teliti. Pastikan koneksi internet stabil selama ujian. Tidak diperbolehkan membuka aplikasi lain selama ujian berlangsung.',
    status: 'active',
    createdAt: '2024-01-10T10:30:00',
    updatedAt: '2024-01-12T14:20:00',
    createdBy: 'Dr. Ahmad Fauzi',
    totalQuestions: 25,
    totalParticipants: 45,
    completedParticipants: 32,
    averageScore: 78.5,
    highestScore: 95,
    lowestScore: 45
  };

  const questions = [
    { id: '1', title: 'Apa yang dimaksud dengan HTML?', type: 'multiple_choice', category: 'HTML', difficulty: 'easy', points: 4 },
    { id: '2', title: 'Jelaskan perbedaan antara CSS Grid dan Flexbox', type: 'essay', category: 'CSS', difficulty: 'medium', points: 10 },
    { id: '3', title: 'JavaScript adalah bahasa pemrograman yang compiled', type: 'true_false', category: 'JavaScript', difficulty: 'easy', points: 2 },
    { id: '4', title: 'Implementasi useState hook dalam React', type: 'multiple_choice', category: 'React', difficulty: 'hard', points: 8 },
    { id: '5', title: 'Apa itu DOM dalam JavaScript?', type: 'essay', category: 'JavaScript', difficulty: 'medium', points: 6 }
  ];

  const participants = [
    { id: '1', name: 'Ahmad Fauzi', email: 'ahmad@student.ac.id', class: 'TI-3A', status: 'completed', score: 85, attempts: 1, completedAt: '2024-01-15T10:45:00' },
    { id: '2', name: 'Siti Nurhaliza', email: 'siti@student.ac.id', class: 'TI-3A', status: 'completed', score: 92, attempts: 1, completedAt: '2024-01-15T10:30:00' },
    { id: '3', name: 'Budi Santoso', email: 'budi@student.ac.id', class: 'TI-3B', status: 'in_progress', score: null, attempts: 1, completedAt: null },
    { id: '4', name: 'Dewi Sartika', email: 'dewi@student.ac.id', class: 'TI-3B', status: 'completed', score: 78, attempts: 1, completedAt: '2024-01-15T10:55:00' },
    { id: '5', name: 'Rizki Pratama', email: 'rizki@student.ac.id', class: 'TI-3C', status: 'not_started', score: null, attempts: 0, completedAt: null }
  ];

  const [activeTab, setActiveTab] = useState<'overview' | 'questions' | 'participants' | 'results'>('overview');

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

  const getStatusBadge = (status: string) => {
    const statusConfig = {
      draft: { label: 'Draft', className: 'bg-gray-100 text-gray-800' },
      scheduled: { label: 'Terjadwal', className: 'bg-blue-100 text-blue-800' },
      active: { label: 'Aktif', className: 'bg-green-100 text-green-800' },
      completed: { label: 'Selesai', className: 'bg-purple-100 text-purple-800' },
      cancelled: { label: 'Dibatalkan', className: 'bg-red-100 text-red-800' }
    };

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

  const getParticipantStatusBadge = (status: string) => {
    const statusConfig = {
      not_started: { label: 'Belum Mulai', className: 'bg-gray-100 text-gray-800' },
      in_progress: { label: 'Sedang Mengerjakan', className: 'bg-blue-100 text-blue-800' },
      completed: { label: 'Selesai', className: 'bg-green-100 text-green-800' },
      time_up: { label: 'Waktu Habis', 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>
    );
  };

  return (
    <div className="max-w-6xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <div className="flex items-center space-x-3">
            <h1 className="text-2xl font-bold text-gray-900">{exam.title}</h1>
            {getStatusBadge(exam.status)}
          </div>
          <p className="text-gray-600 mt-1">{exam.description}</p>
        </div>
        <div className="flex items-center space-x-3">
          <Link
            href={`/admin/exams/${examId}/edit`}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            Edit Ujian
          </Link>
          <Link
            href="/admin/exams"
            className="text-gray-600 hover:text-gray-900"
          >
            ← Kembali
          </Link>
        </div>
      </div>

      {/* Quick Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="text-2xl font-bold text-blue-600">{exam.totalQuestions}</div>
          <div className="text-sm text-gray-600">Total Soal</div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="text-2xl font-bold text-green-600">{exam.completedParticipants}/{exam.totalParticipants}</div>
          <div className="text-sm text-gray-600">Peserta Selesai</div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="text-2xl font-bold text-purple-600">{exam.averageScore}%</div>
          <div className="text-sm text-gray-600">Rata-rata Nilai</div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="text-2xl font-bold text-orange-600">{exam.duration} menit</div>
          <div className="text-sm text-gray-600">Durasi</div>
        </div>
      </div>

      {/* Tabs */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200">
        <div className="border-b border-gray-200">
          <nav className="flex space-x-8 px-6">
            {[
              { key: 'overview', label: 'Ringkasan' },
              { key: 'questions', label: 'Soal' },
              { key: 'participants', label: 'Peserta' },
              { key: 'results', label: 'Hasil' }
            ].map((tab) => (
              <button
                key={tab.key}
                onClick={() => setActiveTab(tab.key as any)}
                className={`py-4 px-1 border-b-2 font-medium text-sm ${
                  activeTab === tab.key
                    ? 'border-blue-500 text-blue-600'
                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                }`}
              >
                {tab.label}
              </button>
            ))}
          </nav>
        </div>

        <div className="p-6">
          {/* Overview Tab */}
          {activeTab === 'overview' && (
            <div className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <h3 className="text-lg font-semibold text-gray-900 mb-4">Informasi Ujian</h3>
                  <div className="space-y-3">
                    <div className="flex justify-between">
                      <span className="text-gray-600">Waktu Mulai:</span>
                      <span className="font-medium">{formatDateTime(exam.startDateTime)}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-600">Waktu 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 className="flex justify-between">
                      <span className="text-gray-600">Nilai Kelulusan:</span>
                      <span className="font-medium">{exam.passingScore}%</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-600">Maksimal Percobaan:</span>
                      <span className="font-medium">{exam.maxAttempts}x</span>
                    </div>
                  </div>
                </div>

                <div>
                  <h3 className="text-lg font-semibold text-gray-900 mb-4">Pengaturan</h3>
                  <div className="space-y-3">
                    <div className="flex justify-between">
                      <span className="text-gray-600">Acak Soal:</span>
                      <span className="font-medium">{exam.shuffleQuestions ? 'Ya' : 'Tidak'}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-600">Acak Jawaban:</span>
                      <span className="font-medium">{exam.shuffleAnswers ? 'Ya' : 'Tidak'}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-600">Tampilkan Hasil:</span>
                      <span className="font-medium">
                        {exam.showResults === 'immediately' ? 'Langsung' : 
                         exam.showResults === 'after_completion' ? 'Setelah Selesai' : 'Manual'}
                      </span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-600">Review Jawaban:</span>
                      <span className="font-medium">{exam.allowReview ? 'Diizinkan' : 'Tidak Diizinkan'}</span>
                    </div>
                  </div>
                </div>
              </div>

              {exam.instructions && (
                <div>
                  <h3 className="text-lg font-semibold text-gray-900 mb-4">Instruksi</h3>
                  <div className="bg-gray-50 rounded-lg p-4">
                    <p className="text-gray-700 whitespace-pre-wrap">{exam.instructions}</p>
                  </div>
                </div>
              )}

              <div>
                <h3 className="text-lg font-semibold text-gray-900 mb-4">Metadata</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="space-y-3">
                    <div className="flex justify-between">
                      <span className="text-gray-600">Dibuat:</span>
                      <span className="font-medium">{formatDateTime(exam.createdAt)}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-600">Diperbarui:</span>
                      <span className="font-medium">{formatDateTime(exam.updatedAt)}</span>
                    </div>
                  </div>
                  <div className="space-y-3">
                    <div className="flex justify-between">
                      <span className="text-gray-600">Dibuat oleh:</span>
                      <span className="font-medium">{exam.createdBy}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Questions Tab */}
          {activeTab === 'questions' && (
            <div>
              <div className="flex items-center justify-between mb-6">
                <h3 className="text-lg font-semibold text-gray-900">
                  Daftar Soal ({questions.length} soal)
                </h3>
              </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">
                        No
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Soal
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Tipe
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Kategori
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Tingkat
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Poin
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {questions.map((question, index) => (
                      <tr key={question.id} className="hover:bg-gray-50">
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                          {index + 1}
                        </td>
                        <td className="px-6 py-4 text-sm text-gray-900">
                          <div className="max-w-xs truncate">{question.title}</div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                          {question.type === 'multiple_choice' ? 'Pilihan Ganda' :
                           question.type === 'essay' ? 'Essay' : 'Benar/Salah'}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                          {question.category}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                          <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                            question.difficulty === 'easy' ? 'bg-green-100 text-green-800' :
                            question.difficulty === 'medium' ? 'bg-yellow-100 text-yellow-800' :
                            'bg-red-100 text-red-800'
                          }`}>
                            {question.difficulty === 'easy' ? 'Mudah' :
                             question.difficulty === 'medium' ? 'Sedang' : 'Sulit'}
                          </span>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                          {question.points}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* Participants Tab */}
          {activeTab === 'participants' && (
            <div>
              <div className="flex items-center justify-between mb-6">
                <h3 className="text-lg font-semibold text-gray-900">
                  Daftar Peserta ({participants.length} peserta)
                </h3>
              </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">
                        Nama
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Email
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Kelas
                      </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">
                        Nilai
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Percobaan
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Selesai
                      </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 text-sm font-medium text-gray-900">
                          {participant.name}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                          {participant.email}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                          {participant.class}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          {getParticipantStatusBadge(participant.status)}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                          {participant.score !== null ? `${participant.score}%` : '-'}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                          {participant.attempts}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                          {participant.completedAt ? formatDateTime(participant.completedAt) : '-'}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* Results Tab */}
          {activeTab === 'results' && (
            <div className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="bg-green-50 rounded-lg p-6">
                  <div className="text-2xl font-bold text-green-600">{exam.highestScore}%</div>
                  <div className="text-sm text-green-700">Nilai Tertinggi</div>
                </div>
                <div className="bg-blue-50 rounded-lg p-6">
                  <div className="text-2xl font-bold text-blue-600">{exam.averageScore}%</div>
                  <div className="text-sm text-blue-700">Rata-rata</div>
                </div>
                <div className="bg-red-50 rounded-lg p-6">
                  <div className="text-2xl font-bold text-red-600">{exam.lowestScore}%</div>
                  <div className="text-sm text-red-700">Nilai Terendah</div>
                </div>
              </div>

              <div>
                <h4 className="text-lg font-semibold text-gray-900 mb-4">Distribusi Nilai</h4>
                <div className="bg-gray-50 rounded-lg p-6">
                  <div className="text-center text-gray-600">
                    Grafik distribusi nilai akan ditampilkan di sini
                  </div>
                </div>
              </div>

              <div>
                <h4 className="text-lg font-semibold text-gray-900 mb-4">Analisis Soal</h4>
                <div className="bg-gray-50 rounded-lg p-6">
                  <div className="text-center text-gray-600">
                    Analisis tingkat kesulitan dan daya beda soal akan ditampilkan di sini
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default ExamDetailPage;