'use client';

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

interface Exam {
  id: string;
  title: string;
  description: string;
  status: 'draft' | 'scheduled' | 'active' | 'completed' | 'cancelled';
  startDate: string;
  endDate: string;
  duration: number; // in minutes
  totalQuestions: number;
  totalParticipants: number;
  completedParticipants: number;
  passingScore: number;
  createdBy: string;
  createdAt: string;
}

const ExamManagementPage: React.FC = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [sortBy, setSortBy] = useState('startDate');

  // Mock data
  const [exams] = useState<Exam[]>([
    {
      id: '1',
      title: 'Ujian Sertifikasi - Teknik Dasar Memasak',
      description: 'Ujian sertifikasi untuk menguji kemampuan teknik dasar memasak seperti memotong, menumis, dan merebus',
      status: 'scheduled',
      startDate: '2024-02-15T09:00:00Z',
      endDate: '2024-02-15T11:00:00Z',
      duration: 120,
      totalQuestions: 50,
      totalParticipants: 45,
      completedParticipants: 0,
      passingScore: 70,
      createdBy: 'Chef Ahmad Fauzi',
      createdAt: '2024-01-20T10:30:00Z'
    },
    {
      id: '2',
      title: 'Quiz Mingguan - Hygiene dan Sanitasi Dapur',
      description: 'Quiz mingguan untuk evaluasi pemahaman hygiene dan sanitasi dalam operasional dapur',
      status: 'active',
      startDate: '2024-01-25T14:00:00Z',
      endDate: '2024-01-25T15:00:00Z',
      duration: 60,
      totalQuestions: 25,
      totalParticipants: 38,
      completedParticipants: 22,
      passingScore: 75,
      createdBy: 'Chef Sarah Wijaya',
      createdAt: '2024-01-22T08:15:00Z'
    },
    {
      id: '3',
      title: 'Ujian Akhir - Manajemen Inventori Bahan Makanan',
      description: 'Ujian akhir untuk menguji kemampuan manajemen inventori, penyimpanan, dan rotasi bahan makanan',
      status: 'completed',
      startDate: '2024-01-20T08:00:00Z',
      endDate: '2024-01-20T10:30:00Z',
      duration: 150,
      totalQuestions: 60,
      totalParticipants: 42,
      completedParticipants: 42,
      passingScore: 65,
      createdBy: 'Chef Budi Santoso',
      createdAt: '2024-01-15T16:20:00Z'
    },
    {
      id: '4',
      title: 'Pre-Test Pengetahuan Bahan Makanan',
      description: 'Pre-test untuk mengukur pemahaman awal tentang jenis-jenis bahan makanan dan karakteristiknya',
      status: 'draft',
      startDate: '2024-02-20T10:00:00Z',
      endDate: '2024-02-20T11:30:00Z',
      duration: 90,
      totalQuestions: 35,
      totalParticipants: 0,
      completedParticipants: 0,
      passingScore: 60,
      createdBy: 'Chef Lisa Permata',
      createdAt: '2024-01-28T14:45:00Z'
    }
  ]);

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'draft': return 'bg-gray-100 text-gray-800';
      case 'scheduled': return 'bg-blue-100 text-blue-800';
      case 'active': return 'bg-green-100 text-green-800';
      case 'completed': return 'bg-purple-100 text-purple-800';
      case 'cancelled': return 'bg-red-100 text-red-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const getStatusLabel = (status: string) => {
    switch (status) {
      case 'draft': return 'Draft';
      case 'scheduled': return 'Terjadwal';
      case 'active': return 'Berlangsung';
      case 'completed': return 'Selesai';
      case 'cancelled': return 'Dibatalkan';
      default: return status;
    }
  };

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

  const getProgressPercentage = (completed: number, total: number) => {
    return total > 0 ? Math.round((completed / total) * 100) : 0;
  };

  const filteredExams = exams.filter(exam => {
    const matchesSearch = exam.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         exam.description.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = statusFilter === 'all' || exam.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  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">Manajemen Ujian</h1>
          <p className="text-gray-600 mt-1">Kelola penjadwalan dan monitoring ujian</p>
        </div>
        <Link
          href="/admin/exams/create"
          className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
        >
          + Buat Ujian Baru
        </Link>
      </div>

      {/* Filters */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Cari Ujian
            </label>
            <input
              type="text"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder="Cari berdasarkan judul atau deskripsi..."
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Status
            </label>
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="all">Semua Status</option>
              <option value="draft">Draft</option>
              <option value="scheduled">Terjadwal</option>
              <option value="active">Berlangsung</option>
              <option value="completed">Selesai</option>
              <option value="cancelled">Dibatalkan</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Urutkan
            </label>
            <select
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="startDate">Tanggal Mulai</option>
              <option value="title">Judul</option>
              <option value="status">Status</option>
              <option value="createdAt">Tanggal Dibuat</option>
            </select>
          </div>
        </div>
      </div>

      {/* Exams List */}
      <div className="space-y-4">
        {filteredExams.map((exam) => (
          <div key={exam.id} className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <div className="flex items-start justify-between">
              <div className="flex-1">
                <div className="flex items-center space-x-3 mb-2">
                  <h3 className="text-lg font-semibold text-gray-900">{exam.title}</h3>
                  <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(exam.status)}`}>
                    {getStatusLabel(exam.status)}
                  </span>
                </div>
                
                <p className="text-gray-600 mb-4">{exam.description}</p>

                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                  <div>
                    <span className="font-medium text-gray-700">Mulai:</span>
                    <div className="text-gray-900">{formatDateTime(exam.startDate)}</div>
                  </div>
                  <div>
                    <span className="font-medium text-gray-700">Selesai:</span>
                    <div className="text-gray-900">{formatDateTime(exam.endDate)}</div>
                  </div>
                  <div>
                    <span className="font-medium text-gray-700">Durasi:</span>
                    <div className="text-gray-900">{exam.duration} menit</div>
                  </div>
                  <div>
                    <span className="font-medium text-gray-700">Soal:</span>
                    <div className="text-gray-900">{exam.totalQuestions} soal</div>
                  </div>
                </div>

                {/* Progress Bar for Active/Completed Exams */}
                {(exam.status === 'active' || exam.status === 'completed') && (
                  <div className="mt-4">
                    <div className="flex items-center justify-between text-sm mb-2">
                      <span className="font-medium text-gray-700">Progress Peserta:</span>
                      <span className="text-gray-900">
                        {exam.completedParticipants}/{exam.totalParticipants} 
                        ({getProgressPercentage(exam.completedParticipants, exam.totalParticipants)}%)
                      </span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2">
                      <div 
                        className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                        style={{ width: `${getProgressPercentage(exam.completedParticipants, exam.totalParticipants)}%` }}
                      ></div>
                    </div>
                  </div>
                )}
              </div>

              <div className="flex items-center space-x-2 ml-6">
                <Link
                  href={`/admin/exams/${exam.id}`}
                  className="px-3 py-1 text-blue-600 hover:text-blue-800 text-sm font-medium"
                >
                  Detail
                </Link>
                <Link
                  href={`/admin/exams/${exam.id}/edit`}
                  className="px-3 py-1 text-gray-600 hover:text-gray-800 text-sm font-medium"
                >
                  Edit
                </Link>
                {exam.status === 'active' && (
                  <Link
                    href={`/admin/exams/${exam.id}/monitor`}
                    className="px-3 py-1 bg-green-100 text-green-800 rounded text-sm font-medium hover:bg-green-200"
                  >
                    Monitor
                  </Link>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>

      {filteredExams.length === 0 && (
        <div className="text-center py-12">
          <div className="text-gray-400 text-lg mb-2">Tidak ada ujian ditemukan</div>
          <p className="text-gray-500">Coba ubah filter pencarian atau buat ujian baru</p>
        </div>
      )}
    </div>
  );
};

export default ExamManagementPage;