import React, { useState, useEffect } from 'react';
import { 
  ChevronRight, 
  ChevronDown,
  GripVertical, 
  Plus, 
  Settings2, 
  Video, 
  FileText, 
  Save, 
  Trash2, 
  Edit3,
  BookOpen,
  CheckCircle2,
  Clock,
  LayoutGrid,
  Layers,
  X,
  Users,
  Award,
  BarChart3,
  ExternalLink,
  Eye,
  MoreVertical,
  HelpCircle,
  FileUp,
  Link2,
  Youtube
} from 'lucide-react';

const App = () => {
  // Curriculum State
  const [curriculum, setCurriculum] = useState([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('curriculum');
  
  // Modal States
  const [showLessonModal, setShowLessonModal] = useState(false);
  const [showModuleModal, setShowModuleModal] = useState(false);
  const [showTopicModal, setShowTopicModal] = useState(false);

  // Form States
  const [selectedModuleId, setSelectedModuleId] = useState('');
  const [newModuleName, setNewModuleName] = useState('');
  const [newTopicName, setNewTopicName] = useState('');
  const [availableTopics, setAvailableTopics] = useState([]);
  
  const [lessonFormData, setLessonFormData] = useState({
    title: '',
    type: 'video',
    topicId: '',
    sourceType: 'vimeo',
    videoUrl: '',
    duration: '',
    isFree: false
  });

  const [courseStats, setCourseStats] = useState({ enrollments: 0, completions: 0 });

  // Initial Load
  useEffect(() => {
    const fetchCourseData = async () => {
      const mockStructure = [
        {
          id: 45,
          title: 'Module 1: Introduction to Frameworks',
          topics: [
            {
              id: 88,
              title: 'Environment Setup',
              lessons: [
                { id: 1, title: 'Installing PHP & MySQL', type: 'video', duration: '15m', status: 'published', is_free: true },
                { id: 2, title: 'Configuration Files', type: 'text', duration: '5m', status: 'published', is_free: false }
              ]
            }
          ]
        }
      ];

      setTimeout(() => {
        setCurriculum(mockStructure);
        setCourseStats({ enrollments: 124, completions: 42 });
        setLoading(false);
      }, 800);
    };
    fetchCourseData();
  }, []);

  // Sync available topics when a module is selected in the Lesson Modal
  useEffect(() => {
    if (selectedModuleId) {
      const module = curriculum.find(m => m.id === parseInt(selectedModuleId));
      setAvailableTopics(module ? module.topics : []);
    } else {
      setAvailableTopics([]);
    }
    setLessonFormData(prev => ({ ...prev, topicId: '' }));
  }, [selectedModuleId, curriculum]);

  // Handler: Add Module
  const handleAddModule = () => {
    if (!newModuleName.trim()) return;
    const newModule = {
      id: Date.now(),
      title: newModuleName,
      topics: []
    };
    setCurriculum([...curriculum, newModule]);
    setNewModuleName('');
    setShowModuleModal(false);
  };

  // Handler: Add Topic
  const handleAddTopic = () => {
    if (!newTopicName.trim() || !selectedModuleId) return;
    const updatedCurriculum = curriculum.map(mod => {
      if (mod.id === parseInt(selectedModuleId)) {
        return {
          ...mod,
          topics: [...mod.topics, { id: Date.now(), title: newTopicName, lessons: [] }]
        };
      }
      return mod;
    });
    setCurriculum(updatedCurriculum);
    setNewTopicName('');
    setShowTopicModal(false);
  };

  const StatusBadge = ({ status }) => (
    <span className={`px-2 py-0.5 rounded-md text-[10px] font-bold uppercase tracking-wider ${
      status === 'published' ? 'bg-emerald-50 text-emerald-600 border border-emerald-100' : 'bg-amber-50 text-amber-600 border border-amber-100'
    }`}>
      {status}
    </span>
  );

  const getIcon = (type) => {
    switch (type) {
      case 'video': return <Video className="w-4 h-4" />;
      case 'text': return <FileText className="w-4 h-4" />;
      case 'quiz': return <HelpCircle className="w-4 h-4" />;
      case 'assignment': return <Award className="w-4 h-4" />;
      case 'resource': return <FileUp className="w-4 h-4" />;
      default: return <FileText className="w-4 h-4" />;
    }
  };

  const getBgColor = (type) => {
    switch (type) {
      case 'video': return 'bg-indigo-50 text-indigo-600';
      case 'text': return 'bg-orange-50 text-orange-600';
      case 'quiz': return 'bg-purple-50 text-purple-600';
      case 'assignment': return 'bg-emerald-50 text-emerald-600';
      case 'resource': return 'bg-blue-50 text-blue-600';
      default: return 'bg-slate-50 text-slate-600';
    }
  };

  return (
    <div className="min-h-screen bg-[#fcfcfd] text-slate-900 font-sans selection:bg-indigo-100">
      {/* Navbar */}
      <nav className="bg-white border-b border-slate-200 sticky top-0 z-40">
        <div className="max-w-7xl mx-auto px-6 h-16 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <div className="bg-slate-900 p-2 rounded-xl">
              <BookOpen className="text-white w-5 h-5" />
            </div>
            <div>
              <h1 className="font-bold text-slate-900 leading-none mb-1">Modern Web Engineering</h1>
              <p className="text-xs text-slate-400 font-medium">Draft • Last saved moments ago</p>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <button className="flex items-center gap-2 px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-50 rounded-lg transition-colors"><Eye className="w-4 h-4" /> Preview</button>
            <div className="h-6 w-px bg-slate-200 mx-1"></div>
            <button className="flex items-center gap-2 px-5 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-sm font-bold shadow-sm transition-all"><Save className="w-4 h-4" /> Publish</button>
          </div>
        </div>
      </nav>

      <div className="max-w-7xl mx-auto px-6 py-8 grid grid-cols-12 gap-8">
        {/* Left Sidebar */}
        <aside className="col-span-3 space-y-6">
          <div className="bg-white rounded-2xl border border-slate-200 p-1 shadow-sm">
            <button onClick={() => setActiveTab('curriculum')} className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-bold transition-all ${activeTab === 'curriculum' ? 'bg-indigo-50 text-indigo-600' : 'text-slate-500 hover:bg-slate-50'}`}><LayoutGrid className="w-4 h-4" /> Curriculum</button>
            <button onClick={() => setActiveTab('settings')} className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-bold transition-all ${activeTab === 'settings' ? 'bg-indigo-50 text-indigo-600' : 'text-slate-500 hover:bg-slate-50'}`}><Settings2 className="w-4 h-4" /> Settings</button>
            <button onClick={() => setActiveTab('students')} className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-bold transition-all ${activeTab === 'students' ? 'bg-indigo-50 text-indigo-600' : 'text-slate-500 hover:bg-slate-50'}`}><Users className="w-4 h-4" /> Students</button>
          </div>

          <div className="bg-white rounded-2xl border border-slate-200 p-5 space-y-4 shadow-sm">
            <h3 className="text-[10px] font-black text-slate-400 uppercase tracking-widest flex items-center gap-2"><BarChart3 className="w-3 h-3" /> Performance</h3>
            <div className="grid grid-cols-2 gap-4">
              <div className="bg-slate-50 p-3 rounded-xl border border-slate-100">
                <p className="text-[10px] font-black text-slate-400 uppercase">Enrollments</p>
                <p className="text-xl font-black text-slate-800">{courseStats.enrollments}</p>
              </div>
              <div className="bg-slate-50 p-3 rounded-xl border border-slate-100">
                <p className="text-[10px] font-black text-slate-400 uppercase">Success Rate</p>
                <p className="text-xl font-black text-slate-800">84%</p>
              </div>
            </div>
          </div>
        </aside>

        {/* Workspace */}
        <main className="col-span-9 space-y-6">
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-2xl font-black text-slate-900 tracking-tight">Curriculum Builder</h2>
              <p className="text-slate-500 text-sm">Design the path for your students.</p>
            </div>
            <div className="flex gap-2">
              <button 
                onClick={() => setShowModuleModal(true)}
                className="flex items-center gap-2 px-4 py-2.5 bg-white border border-slate-200 hover:border-indigo-200 rounded-xl text-sm font-bold text-slate-700 shadow-sm transition-all"
              >
                <Layers className="w-4 h-4 text-slate-400" />
                Add Module
              </button>
              <button 
                onClick={() => setShowLessonModal(true)}
                className="flex items-center gap-2 px-4 py-2.5 bg-indigo-600 hover:bg-indigo-700 rounded-xl text-sm font-bold text-white shadow-md shadow-indigo-100 transition-all"
              >
                <Plus className="w-4 h-4" />
                Add Lesson
              </button>
            </div>
          </div>

          {loading ? (
            <div className="h-64 flex flex-col items-center justify-center gap-3">
              <div className="w-8 h-8 border-4 border-indigo-100 border-t-indigo-600 rounded-full animate-spin"></div>
              <p className="text-xs font-bold text-slate-400 uppercase tracking-tighter">Updating Structural Data...</p>
            </div>
          ) : (
            <div className="space-y-6">
              {curriculum.map((module) => (
                <div key={module.id} className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden transition-all hover:border-indigo-200">
                  {/* Module Header */}
                  <div className="px-6 py-4 bg-slate-50/50 border-b border-slate-100 flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className="bg-white p-1.5 rounded-lg border border-slate-200 text-slate-500">
                        <GripVertical className="w-4 h-4" />
                      </div>
                      <h3 className="font-bold text-slate-800">{module.title}</h3>
                    </div>
                    <div className="flex items-center gap-2">
                      <button 
                        onClick={() => { setSelectedModuleId(module.id); setShowTopicModal(true); }}
                        className="flex items-center gap-1.5 px-3 py-1.5 bg-white border border-slate-200 rounded-lg text-[10px] font-black uppercase text-slate-500 hover:text-indigo-600 hover:border-indigo-200 transition-all"
                      >
                        <Plus className="w-3 h-3" /> Add Topic
                      </button>
                      <button className="p-2 text-slate-400 hover:text-red-500 hover:bg-white rounded-lg transition-all"><Trash2 className="w-4 h-4" /></button>
                    </div>
                  </div>

                  {/* Topics List */}
                  <div className="p-2 space-y-2">
                    {module.topics.length === 0 ? (
                      <div className="p-8 text-center border-2 border-dashed border-slate-100 rounded-xl">
                        <p className="text-xs font-bold text-slate-300 uppercase tracking-widest">No topics in this module</p>
                      </div>
                    ) : (
                      module.topics.map((topic) => (
                        <div key={topic.id} className="bg-white rounded-xl">
                          <div className="flex items-center justify-between px-4 py-3 hover:bg-slate-50 rounded-xl transition-colors group/topic">
                            <div className="flex items-center gap-3">
                              <ChevronDown className="w-4 h-4 text-slate-300" />
                              <h4 className="font-bold text-slate-700 text-sm tracking-tight">{topic.title}</h4>
                            </div>
                            <div className="flex items-center gap-1 opacity-0 group-hover/topic:opacity-100 transition-opacity">
                              <button onClick={() => { setSelectedModuleId(module.id); setLessonFormData({...lessonFormData, topicId: topic.id}); setShowLessonModal(true); }} className="p-1.5 text-slate-400 hover:text-indigo-600 rounded-lg"><Plus className="w-3.5 h-3.5" /></button>
                              <button className="p-1.5 text-slate-400 hover:text-slate-600 rounded-lg"><Settings2 className="w-3.5 h-3.5" /></button>
                            </div>
                          </div>

                          {/* Lessons inside Topic */}
                          <div className="mt-1 space-y-1 ml-4 border-l-2 border-slate-50 pl-2 pb-2">
                            {topic.lessons.map((lesson) => (
                              <div key={lesson.id} className="group/lesson flex items-center justify-between p-3 rounded-xl hover:bg-white hover:shadow-md hover:shadow-slate-100 transition-all">
                                <div className="flex items-center gap-4">
                                  <div className={`p-2 rounded-lg ${getBgColor(lesson.type)}`}>{getIcon(lesson.type)}</div>
                                  <div>
                                    <div className="flex items-center gap-3 mb-0.5">
                                      <h5 className="font-bold text-slate-800 text-sm">{lesson.title}</h5>
                                      <StatusBadge status={lesson.status} />
                                    </div>
                                    <div className="flex items-center gap-2 text-[10px] font-bold text-slate-400 uppercase">
                                      <Clock className="w-3 h-3" /> {lesson.duration}
                                    </div>
                                  </div>
                                </div>
                                <div className="flex items-center gap-1 opacity-0 group-hover/lesson:opacity-100 transition-opacity">
                                  <button className="p-2 text-slate-400 hover:text-indigo-600 rounded-lg transition-all"><Edit3 className="w-4 h-4" /></button>
                                  <button className="p-2 text-slate-400 hover:text-slate-900 rounded-lg transition-all"><MoreVertical className="w-4 h-4" /></button>
                                </div>
                              </div>
                            ))}
                          </div>
                        </div>
                      ))
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </main>
      </div>

      {/* Modal: Add Module */}
      {showModuleModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm">
          <div className="bg-white w-full max-w-md rounded-3xl shadow-2xl animate-in zoom-in duration-200 overflow-hidden">
            <div className="px-8 py-6 border-b border-slate-100 flex items-center justify-between">
              <h3 className="font-black text-slate-900 text-xl tracking-tight">New Module</h3>
              <button onClick={() => setShowModuleModal(false)}><X className="w-6 h-6 text-slate-400" /></button>
            </div>
            <div className="p-8 space-y-4">
              <div className="space-y-2">
                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Module Title</label>
                <input 
                  autoFocus
                  value={newModuleName}
                  onChange={(e) => setNewModuleName(e.target.value)}
                  placeholder="e.g. Master the Fundamentals"
                  className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-3 text-sm font-bold focus:ring-2 focus:ring-indigo-500 outline-none"
                />
              </div>
            </div>
            <div className="px-8 py-6 bg-slate-50 border-t border-slate-100 flex gap-3">
              <button onClick={() => setShowModuleModal(false)} className="flex-1 py-3 text-sm font-bold text-slate-500">Cancel</button>
              <button onClick={handleAddModule} className="flex-1 py-3 text-sm font-bold text-white bg-indigo-600 rounded-xl shadow-lg shadow-indigo-100">Create Module</button>
            </div>
          </div>
        </div>
      )}

      {/* Modal: Add Topic */}
      {showTopicModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm">
          <div className="bg-white w-full max-w-md rounded-3xl shadow-2xl animate-in zoom-in duration-200 overflow-hidden">
            <div className="px-8 py-6 border-b border-slate-100 flex items-center justify-between">
              <h3 className="font-black text-slate-900 text-xl tracking-tight">Add Topic</h3>
              <button onClick={() => setShowTopicModal(false)}><X className="w-6 h-6 text-slate-400" /></button>
            </div>
            <div className="p-8 space-y-4">
              <div className="space-y-2">
                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Topic Title</label>
                <input 
                  autoFocus
                  value={newTopicName}
                  onChange={(e) => setNewTopicName(e.target.value)}
                  placeholder="e.g. Setting up Git"
                  className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-3 text-sm font-bold focus:ring-2 focus:ring-indigo-500 outline-none"
                />
              </div>
            </div>
            <div className="px-8 py-6 bg-slate-50 border-t border-slate-100 flex gap-3">
              <button onClick={() => setShowTopicModal(false)} className="flex-1 py-3 text-sm font-bold text-slate-500">Cancel</button>
              <button onClick={handleAddTopic} className="flex-1 py-3 text-sm font-bold text-white bg-indigo-600 rounded-xl shadow-lg shadow-indigo-100">Add Topic</button>
            </div>
          </div>
        </div>
      )}

      {/* Modal: Add Lesson */}
      {showLessonModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm">
          <div className="bg-white w-full max-w-xl rounded-3xl shadow-2xl overflow-hidden animate-in fade-in zoom-in duration-200">
            <div className="px-8 py-6 border-b border-slate-100 flex items-center justify-between">
              <div>
                <h3 className="font-black text-slate-900 text-xl tracking-tight">Create Lesson</h3>
                <p className="text-slate-500 text-xs font-medium">Define your lesson parameters</p>
              </div>
              <button onClick={() => setShowLessonModal(false)}><X className="w-6 h-6 text-slate-400" /></button>
            </div>

            <div className="p-8 space-y-6 max-h-[70vh] overflow-y-auto">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Target Module</label>
                  <select 
                    className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-3 text-sm font-bold focus:ring-2 focus:ring-indigo-500 outline-none appearance-none"
                    value={selectedModuleId}
                    onChange={(e) => setSelectedModuleId(e.target.value)}
                  >
                    <option value="">Choose Module...</option>
                    {curriculum.map(m => <option key={m.id} value={m.id}>{m.title}</option>)}
                  </select>
                </div>
                <div className="space-y-2">
                  <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Target Topic</label>
                  <select 
                    className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-3 text-sm font-bold focus:ring-2 focus:ring-indigo-500 outline-none appearance-none disabled:opacity-50"
                    disabled={!selectedModuleId}
                    value={lessonFormData.topicId}
                    onChange={(e) => setLessonFormData({...lessonFormData, topicId: e.target.value})}
                  >
                    <option value="">{selectedModuleId ? 'Select Topic...' : 'Choose Module First'}</option>
                    {availableTopics.map(t => <option key={t.id} value={t.id}>{t.title}</option>)}
                  </select>
                </div>
              </div>

              <div className={`space-y-6 transition-all ${!lessonFormData.topicId ? 'opacity-30 pointer-events-none grayscale' : ''}`}>
                <div className="space-y-2">
                  <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Lesson Title</label>
                  <input type="text" placeholder="Lesson Name" className="w-full bg-white border border-slate-200 rounded-xl px-4 py-3 text-sm font-bold outline-none" />
                </div>

                <div className="space-y-2">
                  <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Content Type</label>
                  <select 
                    className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-3 text-sm font-bold outline-none"
                    value={lessonFormData.type}
                    onChange={(e) => setLessonFormData({...lessonFormData, type: e.target.value})}
                  >
                    <option value="video">Video Lesson</option>
                    <option value="text">Text / Article</option>
                    <option value="quiz">Interactive Quiz</option>
                    <option value="assignment">Assignment / Project</option>
                    <option value="resource">Downloadable Resource</option>
                  </select>
                </div>

                {lessonFormData.type === 'video' && (
                  <div className="p-5 bg-indigo-50/50 border border-indigo-100 rounded-2xl space-y-4 animate-in slide-in-from-top-2">
                    <div className="grid grid-cols-3 gap-2">
                      {['youtube', 'vimeo', 'direct'].map(p => (
                        <button key={p} onClick={() => setLessonFormData({...lessonFormData, sourceType: p})} className={`py-2 text-[10px] font-black rounded-xl border transition-all ${lessonFormData.sourceType === p ? 'bg-indigo-600 text-white border-indigo-600' : 'bg-white text-slate-500 border-slate-200'}`}>
                          {p.toUpperCase()}
                        </button>
                      ))}
                    </div>
                    <input placeholder="Enter Video URL..." className="w-full bg-white border border-slate-200 rounded-xl px-4 py-3 text-sm font-medium outline-none shadow-sm" />
                  </div>
                )}
              </div>
            </div>

            <div className="px-8 py-6 bg-slate-50 border-t border-slate-100 flex gap-3">
              <button onClick={() => setShowLessonModal(false)} className="flex-1 py-3 text-sm font-bold text-slate-500">Discard</button>
              <button disabled={!lessonFormData.topicId} className="flex-1 py-3 text-sm font-bold text-white bg-indigo-600 rounded-xl disabled:bg-slate-200">Create Lesson</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default App;