'use client';

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

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

  // Mock existing exam data
  const existingExam = {
    id: examId,
    title: 'Ujian Tengah Semester - Pemrograman Web',
    description: 'Ujian tengah semester untuk mata kuliah Pemrograman Web yang mencakup HTML, CSS, JavaScript, dan React.',
    startDate: '2024-01-15',
    startTime: '09:00',
    endDate: '2024-01-15',
    endTime: '11: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',
    selectedQuestions: ['1', '2', '3', '4', '5'],
    selectedParticipants: ['1', '2', '3', '4', '5']
  };

  const [formData, setFormData] = useState(existingExam);
  const [selectedQuestions, setSelectedQuestions] = useState<string[]>(existingExam.selectedQuestions);
  const [selectedParticipants, setSelectedParticipants] = useState<string[]>(existingExam.selectedParticipants);

  // Mock data for questions and participants
  const availableQuestions = [
    { id: '1', title: 'Apa yang dimaksud dengan algoritma?', category: 'Pemrograman', difficulty: 'medium' },
    { id: '2', title: 'Jelaskan konsep OOP', category: 'Pemrograman', difficulty: 'hard' },
    { id: '3', title: 'Apa itu struktur data array?', category: 'Struktur Data', difficulty: 'easy' },
    { id: '4', title: 'Implementasi linked list', category: 'Struktur Data', difficulty: 'medium' },
    { id: '5', title: 'Konsep database normalisasi', category: 'Database', difficulty: 'hard' },
    { id: '6', title: 'HTML semantic elements', category: 'HTML', difficulty: 'easy' },
    { id: '7', title: 'CSS Grid vs Flexbox', category: 'CSS', difficulty: 'medium' }
  ];

  const availableParticipants = [
    { id: '1', name: 'Ahmad Fauzi', email: 'ahmad@student.ac.id', class: 'TI-3A' },
    { id: '2', name: 'Siti Nurhaliza', email: 'siti@student.ac.id', class: 'TI-3A' },
    { id: '3', name: 'Budi Santoso', email: 'budi@student.ac.id', class: 'TI-3B' },
    { id: '4', name: 'Dewi Sartika', email: 'dewi@student.ac.id', class: 'TI-3B' },
    { id: '5', name: 'Rizki Pratama', email: 'rizki@student.ac.id', class: 'TI-3C' },
    { id: '6', name: 'Andi Wijaya', email: 'andi@student.ac.id', class: 'TI-3C' },
    { id: '7', name: 'Maya Sari', email: 'maya@student.ac.id', class: 'TI-3A' }
  ];

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value, type } = e.target;
    if (type === 'checkbox') {
      const checked = (e.target as HTMLInputElement).checked;
      setFormData(prev => ({
        ...prev,
        [name]: checked
      }));
    } else {
      setFormData(prev => ({
        ...prev,
        [name]: value
      }));
    }
  };

  const handleQuestionToggle = (questionId: string) => {
    setSelectedQuestions(prev => 
      prev.includes(questionId) 
        ? prev.filter(id => id !== questionId)
        : [...prev, questionId]
    );
  };

  const handleParticipantToggle = (participantId: string) => {
    setSelectedParticipants(prev => 
      prev.includes(participantId) 
        ? prev.filter(id => id !== participantId)
        : [...prev, participantId]
    );
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    // Validation
    if (!formData.title.trim()) {
      alert('Judul ujian harus diisi');
      return;
    }

    if (!formData.startDate || !formData.startTime) {
      alert('Tanggal dan waktu mulai harus diisi');
      return;
    }

    if (!formData.endDate || !formData.endTime) {
      alert('Tanggal dan waktu selesai harus diisi');
      return;
    }

    if (selectedQuestions.length === 0) {
      alert('Pilih minimal 1 soal untuk ujian');
      return;
    }

    if (selectedParticipants.length === 0) {
      alert('Pilih minimal 1 peserta untuk ujian');
      return;
    }

    // Combine date and time
    const startDateTime = new Date(`${formData.startDate}T${formData.startTime}`);
    const endDateTime = new Date(`${formData.endDate}T${formData.endTime}`);

    if (endDateTime <= startDateTime) {
      alert('Waktu selesai harus setelah waktu mulai');
      return;
    }

    // Simulate API call
    const examData = {
      ...formData,
      startDateTime: startDateTime.toISOString(),
      endDateTime: endDateTime.toISOString(),
      selectedQuestions,
      selectedParticipants,
      totalQuestions: selectedQuestions.length,
      totalParticipants: selectedParticipants.length
    };

    console.log('Updating exam:', examData);
    alert('Ujian berhasil diperbarui!');
    router.push(`/admin/exams/${examId}`);
  };

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Edit Ujian</h1>
          <p className="text-gray-600 mt-1">Perbarui konfigurasi dan jadwal ujian</p>
        </div>
        <Link
          href={`/admin/exams/${examId}`}
          className="text-gray-600 hover:text-gray-900 flex items-center"
        >
          ← Kembali ke Detail Ujian
        </Link>
      </div>

      {/* Warning for Active Exam */}
      {formData.status === 'active' && (
        <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
          <div className="flex">
            <div className="flex-shrink-0">
              <svg className="h-5 w-5 text-yellow-400" viewBox="0 0 20 20" fill="currentColor">
                <path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
              </svg>
            </div>
            <div className="ml-3">
              <h3 className="text-sm font-medium text-yellow-800">
                Peringatan: Ujian Sedang Aktif
              </h3>
              <div className="mt-2 text-sm text-yellow-700">
                <p>Ujian ini sedang aktif. Perubahan tertentu mungkin mempengaruhi peserta yang sedang mengerjakan ujian.</p>
              </div>
            </div>
          </div>
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Basic Information */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">Informasi Dasar</h2>
          
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Judul Ujian *
              </label>
              <input
                type="text"
                name="title"
                value={formData.title}
                onChange={handleInputChange}
                placeholder="Masukkan judul ujian"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                required
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Deskripsi
              </label>
              <textarea
                name="description"
                value={formData.description}
                onChange={handleInputChange}
                rows={3}
                placeholder="Masukkan deskripsi ujian"
                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>
        </div>

        {/* Schedule */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">Jadwal Ujian</h2>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Tanggal Mulai *
              </label>
              <input
                type="date"
                name="startDate"
                value={formData.startDate}
                onChange={handleInputChange}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                required
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Waktu Mulai *
              </label>
              <input
                type="time"
                name="startTime"
                value={formData.startTime}
                onChange={handleInputChange}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                required
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Tanggal Selesai *
              </label>
              <input
                type="date"
                name="endDate"
                value={formData.endDate}
                onChange={handleInputChange}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                required
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Waktu Selesai *
              </label>
              <input
                type="time"
                name="endTime"
                value={formData.endTime}
                onChange={handleInputChange}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                required
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Durasi (menit)
              </label>
              <input
                type="number"
                name="duration"
                value={formData.duration}
                onChange={handleInputChange}
                min="1"
                max="480"
                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">
                Nilai Kelulusan (%)
              </label>
              <input
                type="number"
                name="passingScore"
                value={formData.passingScore}
                onChange={handleInputChange}
                min="0"
                max="100"
                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>
        </div>

        {/* Questions Selection */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">
            Pilih Soal ({selectedQuestions.length} dipilih)
          </h2>
          
          <div className="space-y-3 max-h-64 overflow-y-auto">
            {availableQuestions.map((question) => (
              <div key={question.id} className="flex items-center space-x-3 p-3 border border-gray-200 rounded-lg">
                <input
                  type="checkbox"
                  checked={selectedQuestions.includes(question.id)}
                  onChange={() => handleQuestionToggle(question.id)}
                  className="w-4 h-4 text-blue-600 focus:ring-blue-500"
                />
                <div className="flex-1">
                  <div className="font-medium text-gray-900">{question.title}</div>
                  <div className="text-sm text-gray-600">
                    {question.category} • {question.difficulty}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Participants Selection */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">
            Pilih Peserta ({selectedParticipants.length} dipilih)
          </h2>
          
          <div className="space-y-3 max-h-64 overflow-y-auto">
            {availableParticipants.map((participant) => (
              <div key={participant.id} className="flex items-center space-x-3 p-3 border border-gray-200 rounded-lg">
                <input
                  type="checkbox"
                  checked={selectedParticipants.includes(participant.id)}
                  onChange={() => handleParticipantToggle(participant.id)}
                  className="w-4 h-4 text-blue-600 focus:ring-blue-500"
                />
                <div className="flex-1">
                  <div className="font-medium text-gray-900">{participant.name}</div>
                  <div className="text-sm text-gray-600">
                    {participant.email} • {participant.class}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Settings */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">Pengaturan Ujian</h2>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Maksimal Percobaan
              </label>
              <input
                type="number"
                name="maxAttempts"
                value={formData.maxAttempts}
                onChange={handleInputChange}
                min="1"
                max="10"
                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">
                Tampilkan Hasil
              </label>
              <select
                name="showResults"
                value={formData.showResults}
                onChange={handleInputChange}
                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="immediately">Langsung</option>
                <option value="after_completion">Setelah Selesai</option>
                <option value="manual">Manual</option>
              </select>
            </div>

            <div className="md:col-span-2 space-y-3">
              <label className="flex items-center">
                <input
                  type="checkbox"
                  name="shuffleQuestions"
                  checked={formData.shuffleQuestions}
                  onChange={handleInputChange}
                  className="w-4 h-4 text-blue-600 focus:ring-blue-500"
                />
                <span className="ml-2 text-sm text-gray-700">Acak urutan soal</span>
              </label>

              <label className="flex items-center">
                <input
                  type="checkbox"
                  name="shuffleAnswers"
                  checked={formData.shuffleAnswers}
                  onChange={handleInputChange}
                  className="w-4 h-4 text-blue-600 focus:ring-blue-500"
                />
                <span className="ml-2 text-sm text-gray-700">Acak urutan jawaban</span>
              </label>

              <label className="flex items-center">
                <input
                  type="checkbox"
                  name="allowReview"
                  checked={formData.allowReview}
                  onChange={handleInputChange}
                  className="w-4 h-4 text-blue-600 focus:ring-blue-500"
                />
                <span className="ml-2 text-sm text-gray-700">Izinkan review jawaban</span>
              </label>
            </div>
          </div>
        </div>

        {/* Instructions */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">Instruksi Ujian</h2>
          <textarea
            name="instructions"
            value={formData.instructions}
            onChange={handleInputChange}
            rows={5}
            placeholder="Masukkan instruksi khusus untuk ujian ini..."
            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>

        {/* Status */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">Status</h2>
          <select
            name="status"
            value={formData.status}
            onChange={handleInputChange}
            className="w-full md:w-auto px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
          >
            <option value="draft">Draft</option>
            <option value="scheduled">Jadwalkan</option>
            <option value="active">Aktif</option>
            <option value="completed">Selesai</option>
            <option value="cancelled">Dibatalkan</option>
          </select>
        </div>

        {/* Submit Buttons */}
        <div className="flex justify-end space-x-4">
          <Link
            href={`/admin/exams/${examId}`}
            className="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
          >
            Batal
          </Link>
          <button
            type="submit"
            className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            Simpan Perubahan
          </button>
        </div>
      </form>
    </div>
  );
};

export default EditExamPage;