'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { EnhancedQuestionBuilder } from '@/components/admin/EnhancedQuestionBuilder';
import { InteractiveQuestionData } from '@/components/admin/EnhancedQuestionBuilder';

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

const CreateQuestionPage: React.FC = () => {
  const router = useRouter();
  const [useEnhancedBuilder, setUseEnhancedBuilder] = useState(false);
  
  const [enhancedQuestionData, setEnhancedQuestionData] = useState<InteractiveQuestionData>({
    id: '',
    title: '',
    type: 'multiple_choice',
    category: '',
    difficulty: 'medium',
    points: 10,
    explanation: '',
    status: 'draft',
    options: [
      { id: '1', text: '', isCorrect: false },
      { id: '2', text: '', isCorrect: false },
      { id: '3', text: '', isCorrect: false },
      { id: '4', text: '', isCorrect: false }
    ],
    essayAnswer: '',
    trueFalseAnswer: true,
    multimedia: [],
    interactiveConfig: {
      enableHints: true,
      timeLimit: 300,
      showTimer: true,
      trackBehavior: false,
      allowReview: true,
    },
  });
  
  const [formData, setFormData] = useState({
    title: '',
    type: 'multiple_choice',
    category: '',
    difficulty: 'medium',
    points: 10,
    explanation: '',
    status: 'draft'
  });

  const [options, setOptions] = useState<QuestionOption[]>([
    { id: '1', text: '', isCorrect: false },
    { id: '2', text: '', isCorrect: false },
    { id: '3', text: '', isCorrect: false },
    { id: '4', text: '', isCorrect: false }
  ]);

  const [essayAnswer, setEssayAnswer] = useState('');
  const [trueFalseAnswer, setTrueFalseAnswer] = useState(true);

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

  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();
    
    if (useEnhancedBuilder) {
      if (!enhancedQuestionData.title.trim()) {
        alert('Judul soal harus diisi');
        return;
      }

      console.log('Saving enhanced question:', enhancedQuestionData);
      alert('Soal interaktif berhasil disimpan!');
      router.push('/admin/questions');
      return;
    }

    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;
    }

    console.log('Saving question:', {
      ...formData,
      options: formData.type === 'multiple_choice' ? options : null,
      essayAnswer: formData.type === 'essay' ? essayAnswer : null,
      trueFalseAnswer: formData.type === 'true_false' ? trueFalseAnswer : null
    });

    alert('Soal berhasil disimpan!');
    router.push('/admin/questions');
  };

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Buat Soal Baru</h1>
          <p className="text-gray-600 mt-1">Buat soal baru untuk bank soal</p>
        </div>
        <Link
          href="/admin/questions"
          className="px-4 py-2 text-gray-600 hover:text-gray-900 transition-colors"
        >
          Kembali ke Bank Soal
        </Link>
      </div>

      <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">Mode Builder</h2>
        <div className="flex space-x-4">
          <label className="flex items-center">
            <input
              type="radio"
              name="builderMode"
              checked={!useEnhancedBuilder}
              onChange={() => setUseEnhancedBuilder(false)}
              className="mr-2"
            />
            Original Basic Question Builder
          </label>
          <label className="flex items-center">
            <input
              type="radio"
              name="builderMode"
              checked={useEnhancedBuilder}
              onChange={() => setUseEnhancedBuilder(true)}
              className="mr-2"
            />
            Enhanced Interactive Builder
          </label>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        {useEnhancedBuilder ? (
          <EnhancedQuestionBuilder
            initialData={enhancedQuestionData}
            onSave={(data) => {
              setEnhancedQuestionData(data);
              // Handle save logic here
              console.log('Question saved:', data);
            }}
            onCancel={() => setUseEnhancedBuilder(false)}
            categories={['Matematika', 'Bahasa Indonesia', 'IPA', 'IPS', 'Bahasa Inggris']}
          />
        ) : (
          <>
            <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>
                  <input
                    type="text"
                    name="title"
                    value={formData.title}
                    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"
                    placeholder="Masukkan judul soal"
                  />
                </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"
                  >
                    <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"
                    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>

            {formData.type === 'multiple_choice' && (
              <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                <div className="flex justify-between items-center mb-4">
                  <h2 className="text-lg font-semibold text-gray-900">Pilihan Jawaban</h2>
                  <button
                    type="button"
                    onClick={addOption}
                    className="px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700"
                  >
                    Tambah Pilihan
                  </button>
                </div>
                
                <div className="space-y-3">
                  {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="text-blue-600"
                      />
                      <span className="text-sm font-medium text-gray-700 w-8">
                        {String.fromCharCode(65 + index)}.
                      </span>
                      <input
                        type="text"
                        value={option.text}
                        onChange={(e) => handleOptionChange(option.id, e.target.value)}
                        className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                        placeholder={`Pilihan ${String.fromCharCode(65 + index)}`}
                      />
                      {options.length > 2 && (
                        <button
                          type="button"
                          onClick={() => removeOption(option.id)}
                          className="px-2 py-1 text-red-600 hover:bg-red-50 rounded"
                        >
                          Hapus
                        </button>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            )}

            {formData.type === 'essay' && (
              <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">Kunci Jawaban Essay</h2>
                <textarea
                  value={essayAnswer}
                  onChange={(e) => setEssayAnswer(e.target.value)}
                  rows={4}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="Masukkan kunci jawaban atau poin-poin penting"
                />
              </div>
            )}

            {formData.type === 'true_false' && (
              <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 Benar</h2>
                <div className="space-y-2">
                  <label className="flex items-center">
                    <input
                      type="radio"
                      name="trueFalseAnswer"
                      checked={trueFalseAnswer === true}
                      onChange={() => setTrueFalseAnswer(true)}
                      className="mr-2"
                    />
                    Benar
                  </label>
                  <label className="flex items-center">
                    <input
                      type="radio"
                      name="trueFalseAnswer"
                      checked={trueFalseAnswer === false}
                      onChange={() => setTrueFalseAnswer(false)}
                      className="mr-2"
                    />
                    Salah
                  </label>
                </div>
              </div>
            )}

            <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</h2>
              <textarea
                name="explanation"
                value={formData.explanation}
                onChange={handleInputChange}
                rows={4}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                placeholder="Masukkan penjelasan jawaban (opsional)"
              />
            </div>

            <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>
              </select>
            </div>
          </>
        )}

        <div className="flex justify-end space-x-4">
          <Link
            href="/admin/questions"
            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 Soal
          </button>
        </div>
      </form>
    </div>
  );
};

export default CreateQuestionPage;