import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useExamStore } from '../../store/exams';
import { useEducationTerms } from '../../utils/educationTerms';
import { ChevronLeft, ChevronRight, AlertTriangle, BookOpen, Trash2, Plus, CheckCircle2, X, Sparkles } from 'lucide-react';

export default function ExamEditor() {
  const { id } = useParams();
  const navigate = useNavigate();
  const terms = useEducationTerms();
  const { examGroups, currentExam, fetchExamGroup, updateExamGroup, createQuestion, updateQuestion } = useExamStore();
  
  const [step, setStep] = useState(1);
  const [loading, setLoading] = useState(true);
  const [notFound, setNotFound] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [exam, setExam] = useState<any>(null);
  
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    exam_type: 'quiz',
    duration_minutes: 30,
    total_marks: 100,
    passing_marks: 50,
    max_attempts: 1,
    is_random_order: false,
    show_results: true,
    allow_review: true
  });
  
  const [questions, setQuestions] = useState<any[]>([]);
  
  // Load exam on mount
  useEffect(() => {
    const loadExam = async () => {
      try {
        setLoading(true);
        setNotFound(false);
        
        // Fetch the specific exam with its questions
        await fetchExamGroup(parseInt(id!));
      } catch (error) {
        console.error('Failed to load exam:', error);
        setNotFound(true);
      } finally {
        setLoading(false);
      }
    };
    
    loadExam();
  }, [id, fetchExamGroup]);
  
  // Apply exam data once currentExam is loaded
  useEffect(() => {
    if (loading || !currentExam) return;
    
    setExam(currentExam);
    setFormData({
      name: currentExam.name,
      description: currentExam.description || '',
      exam_type: currentExam.exam_type,
      duration_minutes: currentExam.duration_minutes,
      total_marks: currentExam.total_marks,
      passing_marks: currentExam.passing_marks,
      max_attempts: currentExam.max_attempts,
      is_random_order: currentExam.is_random_order,
      show_results: currentExam.show_results,
      allow_review: currentExam.allow_review
    });
    
    // Normalize questions - ensure options is always an array
    const normalizedQuestions = (currentExam.questions || []).map((q: any) => ({
      ...q,
      options: Array.isArray(q.options) ? q.options : (typeof q.options === 'string' ? JSON.parse(q.options) : ['', '', '', '']),
      // Normalize correct_answer for true/false questions to 'true'|'false' strings
      correct_answer: (function () {
        const ca = q.correct_answer;
        if (typeof ca === 'boolean') return ca ? 'true' : 'false';
        if (typeof ca === 'string') return ca.toLowerCase();
        return '';
      })()
    }));
    setQuestions(normalizedQuestions);
  }, [currentExam, loading]);
  
  const handleSave = async () => {
    setIsSaving(true);
    try {
      // Update exam group (configuration)
      await updateExamGroup(parseInt(id!), formData);

      // Persist questions: update existing or create new
      for (const q of questions) {
        const payload = {
          question_type: q.question_type,
          question: q.question,
          options: Array.isArray(q.options) ? q.options : (q.options ? JSON.parse(q.options) : []),
          marks: q.marks,
          difficulty: q.difficulty,
          correct_answer: q.correct_answer,
          exam_group_id: parseInt(id!)
        };

        if (q.id) {
          // existing question
          await updateQuestion(q.id, payload as any);
        } else {
          // new question
          await createQuestion(payload as any);
        }
      }

      navigate('/exams/manage');
    } catch (error) {
      console.error('Failed to save exam:', error);
    } finally {
      setIsSaving(false);
    }
  };
  
  const addQuestion = () => {
    setQuestions([...questions, {
      question_type: 'multiple-choice',
      question: '',
      options: ['', '', '', ''],
      correct_answer: '',
      marks: 1,
      difficulty: 'medium'
    }]);
  };
  
  const updateLocalQuestion = (index: number, field: string, value: any) => {
    const updated = [...questions];
    // If changing question type, normalize related fields
    if (field === 'question_type') {
      if (value === 'true-false') {
        updated[index] = {
          ...updated[index],
          question_type: value,
          options: [],
          correct_answer: (updated[index].correct_answer === true || String(updated[index].correct_answer).toLowerCase() === 'true') ? 'true' : ''
        };
      } else if (value === 'multiple-choice') {
        updated[index] = {
          ...updated[index],
          question_type: value,
          options: Array.isArray(updated[index].options) && updated[index].options.length ? updated[index].options : ['', '', '', ''],
          correct_answer: updated[index].correct_answer || ''
        };
      } else {
        updated[index] = { ...updated[index], question_type: value };
      }
    } else {
      updated[index] = { ...updated[index], [field]: value };
    }

    setQuestions(updated);
  };
  
  if (loading) {
    return (
      <div className="flex justify-center items-center min-h-[60vh] gap-4">
        <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin"></div>
        <p className="font-black uppercase tracking-[3px] text-[0.6rem]">Loading Exam...</p>
      </div>
    );
  }
  
  if (notFound) {
    return (
      <div className="space-y-8">
        <button 
          onClick={() => navigate(-1)}
          className="p-3 bg-card border border-border rounded-2xl hover:bg-muted transition-all active:scale-95"
        >
          <ChevronLeft size={24} />
        </button>
        <div className="text-center py-24 opacity-60">
          <AlertTriangle size={64} className="mx-auto text-rose-500 mb-6" />
          <h2 className="text-2xl font-black text-text uppercase">Exam Not Found</h2>
          <p className="text-text-muted font-medium mt-2">The exam you're trying to edit could not be located.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Header */}
      <div className="flex items-center justify-between gap-4">
        <div className="flex items-center gap-4">
          <button 
            onClick={() => navigate(-1)}
            className="p-3 bg-card border border-border rounded-2xl hover:bg-muted transition-all active:scale-95"
          >
            <ChevronLeft size={24} />
          </button>
          <div>
            <h1 className="text-3xl font-black text-text tracking-tight uppercase">Edit Exam</h1>
            <p className="text-text-muted font-medium">{terms.chapter} ID: {id}</p>
          </div>
        </div>
        <button 
          onClick={handleSave}
          disabled={isSaving}
          className="px-12 py-4 bg-emerald-600 hover:bg-emerald-700 text-white rounded-2xl font-black text-[0.7rem] uppercase tracking-widest transition-all shadow-lg active:scale-95 disabled:opacity-50 flex items-center gap-3"
        >
          {isSaving ? (
            <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
          ) : <CheckCircle2 size={18} />}
          {isSaving ? 'Saving...' : 'Save Changes'}
        </button>
      </div>
      
      {/* Step Indicator */}
      <div className="flex items-center gap-4 bg-muted/30 p-4 rounded-2xl border border-border w-fit">
        {[1, 2].map((s) => (
          <div key={s} className="flex items-center gap-3">
            <div className={`w-8 h-8 rounded-full flex items-center justify-center text-[0.7rem] font-black cursor-pointer transition-all ${
              step >= s ? 'bg-primary text-white shadow-lg shadow-blue-500/20' : 'bg-muted text-text-muted border border-border'
            }`}
              onClick={() => setStep(s)}
            >
              {s}
            </div>
            <span className={`text-[0.65rem] font-black uppercase tracking-widest cursor-pointer ${step >= s ? 'text-primary' : 'text-text-muted'}`}
              onClick={() => setStep(s)}
            >
              {s === 1 ? 'Configuration' : 'Questions'}
            </span>
            {s < 2 && <ChevronRight size={14} className="text-text-muted/30" />}
          </div>
        ))}
      </div>
      
      {/* Step 1: Configuration */}
      {step === 1 && (
        <div className="space-y-6 animate-in slide-in-from-right-4 duration-300">
          <div className="space-y-1.5">
            <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Exam Name</label>
            <input 
              type="text" 
              className="w-full px-4 py-3 bg-muted/30 border border-border rounded-2xl text-text placeholder:text-text-muted/50 focus:border-primary focus:ring-1 focus:ring-primary/20 transition-all"
              value={formData.name}
              onChange={(e) => setFormData({...formData, name: e.target.value})}
              placeholder="e.g., Mathematics Mastery Quiz - Term 3"
            />
          </div>
          
          <div className="space-y-1.5">
            <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Description</label>
            <textarea 
              className="w-full px-4 py-3 bg-muted/30 border border-border rounded-2xl text-text placeholder:text-text-muted/50 focus:border-primary focus:ring-1 focus:ring-primary/20 transition-all"
              rows={2}
              value={formData.description}
              onChange={(e) => setFormData({...formData, description: e.target.value})}
              placeholder="Briefly outline assessment objectives..."
            />
          </div>
          
          <div className="grid grid-cols-2 gap-6">
            <div className="space-y-1.5">
              <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Exam Type</label>
              <select 
                className="w-full px-4 py-3 bg-muted/30 border border-border rounded-2xl text-text focus:border-primary focus:ring-1 focus:ring-primary/20 transition-all appearance-none cursor-pointer"
                value={formData.exam_type}
                onChange={(e) => setFormData({...formData, exam_type: e.target.value})}
              >
                <option value="quiz">Standard Quiz</option>
                <option value="test">Academic Test</option>
                <option value="midterm">Midterm Window</option>
                <option value="final">Final Assessment</option>
              </select>
            </div>
            
            <div className="space-y-1.5">
              <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Duration (Minutes)</label>
              <input 
                type="number" 
                className="w-full px-4 py-3 bg-muted/30 border border-border rounded-2xl text-text placeholder:text-text-muted/50 focus:border-primary focus:ring-1 focus:ring-primary/20 transition-all"
                value={formData.duration_minutes}
                onChange={(e) => setFormData({...formData, duration_minutes: parseInt(e.target.value)})}
              />
            </div>
          </div>

          <div className="grid grid-cols-3 gap-6">
            <div className="space-y-1.5">
              <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Total Marks</label>
              <input 
                type="number" 
                className="w-full px-4 py-3 bg-muted/30 border border-border rounded-2xl text-text placeholder:text-text-muted/50 focus:border-primary focus:ring-1 focus:ring-primary/20 transition-all"
                value={formData.total_marks}
                onChange={(e) => setFormData({...formData, total_marks: parseInt(e.target.value)})}
              />
            </div>
            
            <div className="space-y-1.5">
              <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Pass Marks</label>
              <input 
                type="number" 
                className="w-full px-4 py-3 bg-muted/30 border border-border rounded-2xl text-text placeholder:text-text-muted/50 focus:border-primary focus:ring-1 focus:ring-primary/20 transition-all"
                value={formData.passing_marks}
                onChange={(e) => setFormData({...formData, passing_marks: parseInt(e.target.value)})}
              />
            </div>
            
            <div className="space-y-1.5">
              <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Max Attempts</label>
              <input 
                type="number" 
                className="w-full px-4 py-3 bg-muted/30 border border-border rounded-2xl text-text placeholder:text-text-muted/50 focus:border-primary focus:ring-1 focus:ring-primary/20 transition-all"
                value={formData.max_attempts}
                onChange={(e) => setFormData({...formData, max_attempts: parseInt(e.target.value)})}
              />
            </div>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 pt-4">
            {[
                { id: 'is_random_order', label: 'Randomize Order' },
                { id: 'show_results', label: 'Show Results' },
                { id: 'allow_review', label: 'Allow Review' }
            ].map(opt => (
                <label key={opt.id} className="flex items-center gap-3 p-4 bg-muted/30 border border-border rounded-2xl cursor-pointer hover:bg-muted transition-all group">
                    <input 
                        type="checkbox"
                        checked={(formData as any)[opt.id]}
                        onChange={(e) => setFormData({...formData, [opt.id]: e.target.checked})}
                        className="w-5 h-5 rounded-lg border-border text-primary focus:ring-primary/20"
                    />
                    <span className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted group-hover:text-text transition-colors">{opt.label}</span>
                </label>
            ))}
          </div>
          
          <div className="flex justify-end pt-8">
            <button 
              onClick={() => setStep(2)}
              className="px-12 py-4 bg-primary text-white rounded-2xl font-black text-[0.7rem] uppercase tracking-widest hover:bg-primary/90 transition-all shadow-xl active:scale-95 flex items-center gap-2 group/btn"
            >
              Next: Questions <ChevronRight size={16} className="group-hover/btn:translate-x-1 transition-transform" />
            </button>
          </div>
        </div>
      )}
      
      {/* Step 2: Questions */}
      {step === 2 && (
        <div className="space-y-6 animate-in slide-in-from-right-4 duration-300">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-black uppercase tracking-[3px] text-text-muted">Questions ({questions.length})</h3>
            <button 
              onClick={addQuestion}
              className="flex items-center gap-2 px-6 py-3 bg-blue-50/10 text-primary border border-blue-100/20 rounded-xl font-black text-[0.65rem] uppercase tracking-widest hover:bg-blue-50/20 transition-all"
            >
              <Plus size={16} /> Add Question
            </button>
          </div>
          <h2 className="text-2xl font-black text-text mb-4 uppercase">{terms.chapter} Under Construction</h2>
          <p className="text-text-muted leading-relaxed mb-10">
            The advanced exam editing interface is currently being synchronized from the remote development branch. Full logic node editing and intelligence pool management will be available in the next release.
          </p>
          <div className="p-6 bg-muted/50 rounded-3xl border border-border flex items-center gap-4 text-left">
            <Info className="text-primary shrink-0" size={24} />
            <p className="text-xs font-bold text-text-muted leading-snug">
              Note: You can still create new exams using the "Create Exam" button in the registry list.
            </p>
          </div>
        </div>
      )}
    </div>
  );
}
