'use client';

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

interface QuestionOption {
  id: string;
  text: string;
  isCorrect: boolean;
}

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

  const [formData, setFormData] = useState({
    title: '',
    type: 'multiple_choice',
    category: '',
    difficulty: 'medium',
    points: 10,
    explanation: '',
    status: 'draft'
  });

  const [options, setOptions] = useState<QuestionOption[]>([]);
  const [essayAnswer, setEssayAnswer] = useState('');
  const [trueFalseAnswer, setTrueFalseAnswer] = useState(true);
  const [loading, setLoading] = useState(true);

  const categories = ['Pemrograman', 'Struktur Data', 'Web Development', 'Database', 'Jaringan'];

  // Mock data loading - in real app, fetch from API
  useEffect(() => {
    const loadQuestion = async () => {
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const mockQuestion = {
        id: questionId,
        title: 'Apa yang dimaksud dengan algoritma dalam pemrograman?',
        type: 'multiple_choice',
        category: 'Pemrograman',
        difficulty: 'medium',
        points: 10,
        status: 'active',
        explanation: 'Algoritma adalah sekumpulan instruksi atau langkah-langkah yang terstruktur dan logis untuk menyelesaikan suatu masalah atau mencapai tujuan tertentu dalam pemrograman.',
        options: [
          { id: '1', text: 'Sekumpulan instruksi yang terstruktur untuk menyelesaikan masalah', isCorrect: true },
          { id: '2', text: 'Bahasa pemrograman yang digunakan untuk membuat aplikasi', isCorrect: false },
          { id: '3', text: 'Software yang digunakan untuk menulis kode', isCorrect: false },
          { id: '4', text: 'Hardware yang digunakan untuk menjalankan program', isCorrect: false }
        ]
      };

      setFormData({
        title: mockQuestion.title,
        type: mockQuestion.type,
        category: mockQuestion.category,
        difficulty: mockQuestion.difficulty,
        points: mockQuestion.points,
        explanation: mockQuestion.explanation,
        status: mockQuestion.status
      });

      if (mockQuestion.type === 'multiple_choice') {
        setOptions(mockQuestion.options);
      }

      setLoading(false);
    };

    loadQuestion();
  }, [questionId]);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleOptionChange = (optionId: string, text: string) => {
    setOptions(prev => prev.map(option => 
      option.id === optionId ? { ...option, text } : option
    ));
  };

  const handleCorrectAnswerChange = (optionId: string) => {
    setOptions(prev => prev.map(option => ({
      ...option,
      isCorrect: option.id === optionId
    })));
  };

  const addOption = () => {
    const newId = (options.length + 1).toString();
    setOptions(prev => [...prev, { id: newId, text: '', isCorrect: false }]);
  };

  const removeOption = (optionId: string) => {
    if (options.length > 2) {
      setOptions(prev => prev.filter(option => option.id !== optionId));
    }
  };

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

    if (formData.type === 'multiple_choice') {
      const hasCorrectAnswer = options.some(option => option.isCorrect);
      const hasEmptyOption = options.some(option => !option.text.trim());
      
      if (hasEmptyOption) {
        alert('Semua pilihan jawaban harus diisi');
        return;
      }
      
      if (!hasCorrectAnswer) {
        alert('Pilih jawaban yang benar');
        return;
      }
    }

    if (formData.type === 'essay' && !essayAnswer.trim()) {
      alert('Kunci jawaban essay harus diisi');
      return;
    }

    // Simulate API call
    console.log('Updating question:', {
      id: questionId,
      ...formData,
      options: formData.type === 'multiple_choice' ? options : null,
      essayAnswer: formData.type === 'essay' ? essayAnswer : null,
      trueFalseAnswer: formData.type === 'true_false' ? trueFalseAnswer : null
    });

    alert('Soal berhasil diperbarui!');
    router.push(`/admin/questions/${questionId}`);
  };

  if (loading) {
    return (
      <div className="max-w-4xl mx-auto">
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
          <span className="ml-3 text-gray-600">Memuat data soal...</span>
        </div>
      </div>
    );
  }

  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 Soal</h1>
          <p className="text-gray-600 mt-1">ID: {questionId}</p>
        </div>
        <Link
          href={`/admin/questions/${questionId}`}
          className="text-gray-600 hover:text-gray-900 flex items-center"
        >
          ← Kembali ke Detail
        </Link>
      </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="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="md:col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Judul Soal *
              </label>
              <textarea
                name="title"
                value={formData.title}
                onChange={handleInputChange}
                rows={3}
                placeholder="Masukkan pertanyaan soal..."
                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">
                Tipe Soal *
              </label>
              <select
                name="type"
                value={formData.type}
                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="multiple_choice">Pilihan Ganda</option>
                <option value="essay">Essay</option>
                <option value="true_false">Benar/Salah</option>
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Kategori *
              </label>
              <select
                name="category"
                value={formData.category}
                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
              >
                <option value="">Pilih Kategori</option>
                {categories.map(category => (
                  <option key={category} value={category}>{category}</option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Tingkat Kesulitan
              </label>
              <select
                name="difficulty"
                value={formData.difficulty}
                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="easy">Mudah</option>
                <option value="medium">Sedang</option>
                <option value="hard">Sulit</option>
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Poin
              </label>
              <input
                type="number"
                name="points"
                value={formData.points}
                onChange={handleInputChange}
                min="1"
                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>

        {/* Answer Options */}
        <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">Jawaban</h2>

          {formData.type === 'multiple_choice' && (
            <div className="space-y-4">
              {options.map((option, index) => (
                <div key={option.id} className="flex items-center space-x-3">
                  <input
                    type="radio"
                    name="correctAnswer"
                    checked={option.isCorrect}
                    onChange={() => handleCorrectAnswerChange(option.id)}
                    className="w-4 h-4 text-blue-600 focus:ring-blue-500"
                  />
                  <div className="flex-1">
                    <input
                      type="text"
                      value={option.text}
                      onChange={(e) => handleOptionChange(option.id, e.target.value)}
                      placeholder={`Pilihan ${String.fromCharCode(65 + index)}`}
                      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>
                  {options.length > 2 && (
                    <button
                      type="button"
                      onClick={() => removeOption(option.id)}
                      className="text-red-600 hover:text-red-800"
                    >
                      Hapus
                    </button>
                  )}
                </div>
              ))}
              
              <button
                type="button"
                onClick={addOption}
                className="text-blue-600 hover:text-blue-800 text-sm font-medium"
              >
                + Tambah Pilihan
              </button>
            </div>
          )}

          {formData.type === 'essay' && (
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Kunci Jawaban / Rubrik Penilaian
              </label>
              <textarea
                value={essayAnswer}
                onChange={(e) => setEssayAnswer(e.target.value)}
                rows={5}
                placeholder="Masukkan kunci jawaban atau rubrik penilaian..."
                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>
          )}

          {formData.type === 'true_false' && (
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Jawaban yang Benar
              </label>
              <div className="flex space-x-4">
                <label className="flex items-center">
                  <input
                    type="radio"
                    name="trueFalseAnswer"
                    checked={trueFalseAnswer === true}
                    onChange={() => setTrueFalseAnswer(true)}
                    className="w-4 h-4 text-blue-600 focus:ring-blue-500"
                  />
                  <span className="ml-2">Benar</span>
                </label>
                <label className="flex items-center">
                  <input
                    type="radio"
                    name="trueFalseAnswer"
                    checked={trueFalseAnswer === false}
                    onChange={() => setTrueFalseAnswer(false)}
                    className="w-4 h-4 text-blue-600 focus:ring-blue-500"
                  />
                  <span className="ml-2">Salah</span>
                </label>
              </div>
            </div>
          )}
        </div>

        {/* Explanation */}
        <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">Penjelasan (Opsional)</h2>
          <textarea
            name="explanation"
            value={formData.explanation}
            onChange={handleInputChange}
            rows={4}
            placeholder="Berikan penjelasan untuk jawaban yang benar..."
            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="active">Aktif</option>
            <option value="archived">Arsip</option>
          </select>
        </div>

        {/* Submit Buttons */}
        <div className="flex justify-end space-x-4">
          <Link
            href={`/admin/questions/${questionId}`}
            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 EditQuestionPage;