'use client';

import DashboardLayout from '@/layouts/DashboardLayout';
import { ClipboardDocumentListIcon, ClockIcon, CalendarIcon, CheckCircleIcon, ExclamationCircleIcon, PlayIcon, XMarkIcon } from '@heroicons/react/24/outline';
import { cn } from '@/utils/cn';
import { useState } from 'react';
import Link from 'next/link';

const exams = [
  {
    id: 1,
    title: 'Kuis Interaktif - Keamanan Dapur BGN',
    course: 'Keamanan Pangan dan Gizi - Badan Gizi Nasional',
    type: 'Interactive Quiz',
    date: '2024-01-26',
    startTime: '09:00',
    endTime: '10:00',
    duration: 60,
    questions: 10,
    status: 'available',
    attempts: 0,
    maxAttempts: 3,
    passingScore: 70,
    description: 'Kuis interaktif tentang keamanan pangan dan praktik dapur yang baik di lingkungan BGN',
    instructions: ['Kuis ini menggunakan berbagai jenis soal interaktif', 'Termasuk drag & drop, simulasi dapur, dan skenario nyata', 'Baca instruksi setiap soal dengan teliti'],
    isInteractive: true
  },
  {
    id: 2,
    title: 'Ujian Tengah Semester - HACCP',
    course: 'HACCP - Hazard Analysis Critical Control Point',
    type: 'Midterm Exam',
    date: '2024-01-28',
    startTime: '10:00',
    endTime: '12:00',
    duration: 120,
    questions: 50,
    status: 'upcoming',
    attempts: 0,
    maxAttempts: 1,
    passingScore: 75,
    description: 'Ujian tengah semester mencakup materi HACCP dari modul 1-6',
    instructions: ['Pastikan koneksi internet stabil', 'Siapkan alat tulis', 'Baca soal dengan teliti']
  },
  {
    id: 5,
    title: 'Quiz Mingguan - Sanitasi Dasar',
    course: 'SLHS - Sanitasi Lingkungan Hidup Sehat',
    type: 'Weekly Quiz',
    date: '2024-01-26',
    startTime: '14:00',
    endTime: '14:30',
    duration: 30,
    questions: 15,
    status: 'available',
    attempts: 0,
    maxAttempts: 2,
    passingScore: 70,
    description: 'Quiz mingguan tentang prinsip-prinsip sanitasi dasar',
    instructions: ['Quiz dapat dikerjakan 2 kali', 'Nilai tertinggi yang akan diambil']
  },
  {
    id: 3,
    title: 'Ujian Akhir - Sertifikasi Halal',
    course: 'Sertifikasi Halal - Sistem Jaminan Halal',
    type: 'Final Exam',
    date: '2024-01-22',
    startTime: '09:00',
    endTime: '11:00',
    duration: 120,
    questions: 40,
    status: 'completed',
    attempts: 1,
    maxAttempts: 1,
    passingScore: 80,
    score: 88,
    grade: 'A',
    description: 'Ujian akhir komprehensif materi sertifikasi halal',
    completedAt: '2024-01-22T10:45:00'
  },
  {
    id: 4,
    title: 'Pre-Test Keamanan Pangan',
    course: 'Keamanan Pangan Industri',
    type: 'Pre-Test',
    date: '2024-01-25',
    startTime: '08:00',
    endTime: '08:30',
    duration: 30,
    questions: 20,
    status: 'missed',
    attempts: 0,
    maxAttempts: 1,
    passingScore: 60,
    description: 'Pre-test untuk mengukur pemahaman awal tentang keamanan pangan'
  }
];

const statusConfig = {
  upcoming: {
    label: 'Akan Datang',
    color: 'bg-blue-100 text-blue-800 border-blue-200',
    icon: CalendarIcon,
    bgColor: 'bg-blue-50'
  },
  available: {
    label: 'Tersedia',
    color: 'bg-green-100 text-green-800 border-green-200',
    icon: PlayIcon,
    bgColor: 'bg-green-50'
  },
  completed: {
    label: 'Selesai',
    color: 'bg-gray-100 text-gray-800 border-gray-200',
    icon: CheckCircleIcon,
    bgColor: 'bg-gray-50'
  },
  missed: {
    label: 'Terlewat',
    color: 'bg-red-100 text-red-800 border-red-200',
    icon: ExclamationCircleIcon,
    bgColor: 'bg-red-50'
  }
};

const typeColors = {
  'Midterm Exam': 'bg-purple-100 text-purple-800',
  'Final Exam': 'bg-red-100 text-red-800',
  'Weekly Quiz': 'bg-blue-100 text-blue-800',
  'Pre-Test': 'bg-yellow-100 text-yellow-800'
};

const statusColors = {
  upcoming: 'bg-blue-100 text-blue-800',
  available: 'bg-green-100 text-green-800',
  completed: 'bg-gray-100 text-gray-800',
  missed: 'bg-red-100 text-red-800'
};

const statusLabels = {
  upcoming: 'Akan Datang',
  available: 'Tersedia',
  completed: 'Selesai',
  missed: 'Terlewat'
};

function formatDate(dateString: string) {
  const date = new Date(dateString);
  return date.toLocaleDateString('id-ID', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
}

function formatTime(timeString: string) {
  return timeString;
}

export default function ExamsPage() {
  const [selectedExam, setSelectedExam] = useState<any>(null);
  const [showModal, setShowModal] = useState(false);

  const handleViewDetail = (exam: any) => {
    setSelectedExam(exam);
    setShowModal(true);
  };

  const closeModal = () => {
    setShowModal(false);
    setSelectedExam(null);
  };

  const upcomingExams = exams.filter(e => e.status === 'upcoming');
  const availableExams = exams.filter(e => e.status === 'available');
  const completedExams = exams.filter(e => e.status === 'completed');
  const missedExams = exams.filter(e => e.status === 'missed');

  return (
    <DashboardLayout>
      <div className="p-6">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">Ujian</h1>
          <p className="text-gray-600">Kelola dan ikuti ujian pembelajaran Anda</p>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">Total Ujian</p>
                <p className="text-2xl font-bold text-gray-900">{exams.length}</p>
              </div>
              <div className="p-3 bg-blue-100 rounded-lg">
                <ClipboardDocumentListIcon className="h-6 w-6 text-blue-600" />
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">Tersedia</p>
                <p className="text-2xl font-bold text-green-600">{availableExams.length}</p>
              </div>
              <div className="p-3 bg-green-100 rounded-lg">
                <PlayIcon className="h-6 w-6 text-green-600" />
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">Selesai</p>
                <p className="text-2xl font-bold text-gray-600">{completedExams.length}</p>
              </div>
              <div className="p-3 bg-gray-100 rounded-lg">
                <CheckCircleIcon className="h-6 w-6 text-gray-600" />
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">Rata-rata Nilai</p>
                <p className="text-2xl font-bold text-purple-600">88</p>
              </div>
              <div className="p-3 bg-purple-100 rounded-lg">
                <ClipboardDocumentListIcon className="h-6 w-6 text-purple-600" />
              </div>
            </div>
          </div>
        </div>

        {/* Exams List */}
        <div className="space-y-6">
          {exams.map((exam) => {
            const StatusIcon = statusConfig[exam.status as keyof typeof statusConfig].icon;
            
            return (
              <div key={exam.id} className={cn(
                "bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden",
                statusConfig[exam.status as keyof typeof statusConfig].bgColor
              )}>
                <div className="p-6">
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex-1">
                      <div className="flex items-center mb-2">
                        <h3 className="text-xl font-semibold text-gray-900 mr-3">{exam.title}</h3>
                        <span className={cn(
                          "px-3 py-1 rounded-full text-sm font-medium flex items-center border",
                          statusConfig[exam.status as keyof typeof statusConfig].color
                        )}>
                          <StatusIcon className="h-4 w-4 mr-1" />
                          {statusConfig[exam.status as keyof typeof statusConfig].label}
                        </span>
                      </div>
                      
                      <p className="text-blue-600 font-medium mb-2">{exam.course}</p>
                      <p className="text-gray-600 mb-4">{exam.description}</p>
                      
                      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
                        <div className="flex items-center text-sm text-gray-600">
                          <CalendarIcon className="h-4 w-4 mr-2" />
                          <span>{formatDate(exam.date)}</span>
                        </div>
                        <div className="flex items-center text-sm text-gray-600">
                          <ClockIcon className="h-4 w-4 mr-2" />
                          <span>{formatTime(exam.startTime)} - {formatTime(exam.endTime)}</span>
                        </div>
                        <div className="flex items-center text-sm text-gray-600">
                          <ClipboardDocumentListIcon className="h-4 w-4 mr-2" />
                          <span>{exam.questions} soal</span>
                        </div>
                        <div className="flex items-center text-sm text-gray-600">
                          <ClockIcon className="h-4 w-4 mr-2" />
                          <span>{exam.duration} menit</span>
                        </div>
                      </div>
                      
                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-4">
                          <span className={cn(
                            "px-2 py-1 rounded text-xs font-medium",
                            typeColors[exam.type as keyof typeof typeColors]
                          )}>
                            {exam.type}
                          </span>
                          <span className="text-sm text-gray-600">
                            Percobaan: {exam.attempts}/{exam.maxAttempts}
                          </span>
                          <span className="text-sm text-gray-600">
                            Nilai Lulus: {exam.passingScore}%
                          </span>
                          {exam.score && (
                            <span className="text-sm font-medium text-green-600">
                              Nilai: {exam.score}% ({exam.grade})
                            </span>
                          )}
                        </div>
                        <button 
                          onClick={() => handleViewDetail(exam)}
                          className="px-3 py-1 text-xs bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition-colors"
                        >
                          Detail
                        </button>
                      </div>
                    </div>
                  </div>
                  
                  {exam.instructions && exam.instructions.length > 0 && (
                    <div className="mb-4 p-4 bg-blue-50 rounded-lg">
                      <h4 className="font-medium text-gray-900 mb-2">Instruksi:</h4>
                      <ul className="text-sm text-gray-600 space-y-1">
                        {exam.instructions.map((instruction, index) => (
                          <li key={index} className="flex items-start">
                            <span className="mr-2">•</span>
                            <span>{instruction}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  )}
                  
                  <div className="flex justify-end space-x-3">
                    {exam.status === 'available' && (
                      <>
                        <Link 
                          href={exam.isInteractive ? "/exam-session?type=interactive" : "/exam-session"}
                          className="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors font-medium inline-block text-center"
                        >
                          {exam.isInteractive ? 'Mulai Kuis Interaktif' : 'Mulai Ujian'}
                        </Link>
                        <button 
                          onClick={() => handleViewDetail(exam)}
                          className="px-6 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
                        >
                          Detail
                        </button>
                      </>
                    )}
                    {exam.status === 'upcoming' && (
                      <button 
                        onClick={() => handleViewDetail(exam)}
                        className="px-6 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
                      >
                        Detail
                      </button>
                    )}
                    {exam.status === 'completed' && (
                      <>
                        <button className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                          Lihat Hasil
                        </button>
                        <button className="px-6 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors">
                          Review Jawaban
                        </button>
                      </>
                    )}
                    {exam.status === 'missed' && (
                      <button 
                        onClick={() => handleViewDetail(exam)}
                        className="px-6 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
                      >
                        Detail
                      </button>
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        {/* Modal */}
        {showModal && selectedExam && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div className="bg-white rounded-xl p-6 max-w-lg w-full mx-4">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-xl font-semibold text-gray-900">Detail Ujian</h3>
                <button 
                  onClick={closeModal}
                  className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  <XMarkIcon className="h-5 w-5 text-gray-500" />
                </button>
              </div>
              
              <div className="space-y-4">
                <div>
                  <h4 className="font-semibold text-gray-900 mb-2">{selectedExam.title}</h4>
                  <p className="text-sm text-blue-600 mb-2">{selectedExam.course}</p>
                  <p className="text-gray-600">{selectedExam.description}</p>
                </div>
                
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <span className="text-gray-500">Durasi:</span>
                    <p className="font-medium">{selectedExam.duration} menit</p>
                  </div>
                  <div>
                    <span className="text-gray-500">Jumlah Soal:</span>
                    <p className="font-medium">{selectedExam.questions} soal</p>
                  </div>
                  <div>
                    <span className="text-gray-500">Tanggal:</span>
                    <p className="font-medium">{formatDate(selectedExam.date)}</p>
                  </div>
                  <div>
                    <span className="text-gray-500">Waktu:</span>
                    <p className="font-medium">{selectedExam.time}</p>
                  </div>
                </div>
                
                {selectedExam.score && (
                  <div className="bg-green-50 p-4 rounded-lg">
                    <div className="flex items-center justify-between">
                      <span className="text-sm font-medium text-green-900">Nilai Anda</span>
                      <span className="text-2xl font-bold text-green-600">{selectedExam.score}%</span>
                    </div>
                  </div>
                )}
                
                <div className="flex items-center space-x-2">
                  <span className={cn(
                    "px-3 py-1 rounded-full text-sm font-medium",
                    statusColors[selectedExam.status as keyof typeof statusColors]
                  )}>
                    {statusLabels[selectedExam.status as keyof typeof statusLabels]}
                  </span>
                  <span className={cn(
                    "px-2 py-1 rounded-full text-xs font-medium",
                    typeColors[selectedExam.type as keyof typeof typeColors]
                  )}>
                    {selectedExam.type}
                  </span>
                </div>
                
                {selectedExam.status === 'available' && (
                  <div className="bg-blue-50 p-4 rounded-lg">
                    <div className="flex items-center mb-2">
                      <PlayIcon className="h-5 w-5 text-blue-600 mr-2" />
                      <span className="text-sm font-medium text-blue-900">Siap untuk memulai ujian?</span>
                    </div>
                    <p className="text-sm text-blue-700 mb-3">
                      Pastikan Anda memiliki koneksi internet yang stabil dan waktu yang cukup.
                    </p>
                    <button className="w-full bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700 transition-colors">
                      Mulai Ujian
                    </button>
                  </div>
                )}
              </div>
            </div>
          </div>
        )}
      </div>
    </DashboardLayout>
  );
}