import { useState, useEffect } from 'react';
import api from '../store/auth';
import { 
  Plus, Trash2, Edit2, BookOpen, Users, 
  Search, X, ChevronRight, Download, Filter, 
  Sparkles, School, Building2, LayoutGrid,
  CheckCircle2, AlertCircle, Info, MoreHorizontal
} from 'lucide-react';

interface ClassSection {
  id: number;
  name: string;
  section?: string;
  capacity: number;
  student_count?: number;
}

interface Subject {
  id: number;
  name: string;
  class_id: number;
  class_name?: string;
}

export default function Classes() {
  const [classes, setClasses] = useState<ClassSection[]>([]);
  const [subjects, setSubjects] = useState<Subject[]>([]);
  const [showClassModal, setShowClassModal] = useState(false);
  const [showSubjectModal, setShowSubjectModal] = useState(false);
  const [loading, setLoading] = useState(true);
  const [classForm, setClassForm] = useState({ name: '', section: '', capacity: 30 });
  const [subjectForm, setSubjectForm] = useState({ name: '', class_id: '' });
  const [searchQuery, setSearchQuery] = useState('');

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    setLoading(true);
    try {
      const [classRes, subjectRes] = await Promise.all([
        api.get('/classes'),
        api.get('/subjects')
      ]);
      setClasses(classRes.data);
      setSubjects(subjectRes.data);
    } catch (err) {
      console.error('Failed to load academic structure');
    } finally {
      setLoading(false);
    }
  };

  const handleClassSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    await api.post('/classes', classForm);
    setShowClassModal(false);
    setClassForm({ name: '', section: '', capacity: 30 });
    loadData();
  };

  const handleSubjectSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    await api.post('/subjects', subjectForm);
    setShowSubjectModal(false);
    setSubjectForm({ name: '', class_id: '' });
    loadData();
  };

  const deleteClass = async (id: number) => {
    if (!confirm('Archive this class section? This will affect enrollment intelligence.')) return;
    await api.delete(`/classes/${id}`);
    loadData();
  };

  const deleteSubject = async (id: number) => {
    if (!confirm('Archive this subject record?')) return;
    await api.delete(`/subjects/${id}`);
    loadData();
  };

  const filteredClasses = classes.filter(c => 
    c.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    (c.section || '').toLowerCase().includes(searchQuery.toLowerCase())
  );

  const stats = [
    { label: 'Active Sections', value: classes.length, icon: Building2, color: 'blue', trend: 'Records' },
    { label: 'Curriculum Units', value: subjects.length, icon: BookOpen, color: 'emerald', trend: 'Live' },
    { label: 'Total Capacity', value: classes.reduce((acc, c) => acc + c.capacity, 0), icon: LayoutGrid, color: 'orange', trend: 'Volume' },
    { label: 'Avg. Load', value: '24.2', icon: Users, color: 'purple', trend: 'Pulse' },
  ];

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Premium Header */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight text-capitalize uppercase">Academic Structure</h2>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>Administration</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Sections & Curriculum</span>
          </nav>
        </div>
        <div className="flex gap-3">
          <button className="flex items-center gap-2 px-5 py-2.5 bg-card border border-border text-text rounded-xl font-bold text-sm hover:bg-muted transition-all shadow-sm active:scale-95">
            <Download size={18} />
            Export Intel
          </button>
          <button 
            className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg shadow-blue-900/10 active:scale-95"
            onClick={() => setShowClassModal(true)}
          >
            <Plus size={18} />
            Initialize Section
          </button>
        </div>
      </div>

      {/* Stats Bento Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {stats.map((stat) => (
          <div key={stat.label} className="bg-card border border-border p-5 rounded-2xl flex items-center gap-4 hover:shadow-md transition-all group cursor-default">
            <div className={`w-12 h-12 rounded-2xl flex items-center justify-center border group-hover:scale-110 transition-transform
              ${stat.color === 'blue' ? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-900/30' : 
                stat.color === 'emerald' ? 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-900/30' : 
                stat.color === 'orange' ? 'bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 border-orange-100 dark:border-orange-900/30' : 
                'bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-900/30'}`}>
              <stat.icon size={22} />
            </div>
            <div>
              <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">{stat.label}</p>
              <div className="flex items-baseline gap-2">
                <p className="text-2xl font-black text-text">{stat.value}</p>
                <span className="text-[0.6rem] font-bold text-text-muted">{stat.trend}</span>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Directory Control Bar */}
      <div className="bg-card border border-border rounded-[2rem] p-2 shadow-sm flex flex-col lg:flex-row items-stretch lg:items-center gap-4">
        <div className="relative group flex-1">
          <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
          <input 
            type="text" 
            className="w-full bg-muted/50 border border-border rounded-2xl pl-11 pr-4 py-3 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all dark:bg-background/50"
            placeholder="Search classes or sections..."
            value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
          />
          {searchQuery && (
            <button onClick={() => setSearchQuery('')} className="absolute right-4 top-1/2 -translate-y-1/2 text-text-muted hover:text-rose-500">
              <X size={16} />
            </button>
          )}
        </div>

        <div className="flex gap-2">
            <button className="px-5 py-3 bg-muted/50 hover:bg-muted text-text-muted rounded-2xl border border-border transition-all flex items-center justify-center gap-2 dark:bg-background/50">
                <Filter size={18} />
                <span className="text-[0.7rem] font-black uppercase tracking-widest text-text-muted">All Semesters</span>
            </button>
            <button 
                className="px-5 py-3 bg-primary/5 hover:bg-primary/10 text-primary rounded-2xl border border-primary/10 transition-all flex items-center justify-center gap-2"
                onClick={() => setShowSubjectModal(true)}
            >
                <Plus size={18} />
                <span className="text-[0.7rem] font-black uppercase tracking-widest">Add Subject</span>
            </button>
        </div>
      </div>

      {/* Main Grid: Classes vs Subjects */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
        
        {/* Classes Sections (Left 7/12) */}
        <div className="lg:col-span-7 space-y-6">
            <div className="flex items-center justify-between px-2">
                <h3 className="text-lg font-black text-text uppercase tracking-tight">Class Sections</h3>
                <span className="text-[0.65rem] font-bold text-text-muted uppercase tracking-widest">{filteredClasses.length} Active Records</span>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {loading ? (
                    <div className="col-span-full py-20 text-center">
                        <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
                        <p className="text-text-muted font-bold uppercase tracking-widest text-xs italic">Syncing Directory...</p>
                    </div>
                ) : filteredClasses.length === 0 ? (
                    <div className="col-span-full py-20 text-center bg-card border border-dashed border-border rounded-[2.5rem]">
                        <School size={48} className="mx-auto text-text-muted/30 mb-4" />
                        <p className="text-text-muted font-bold uppercase tracking-widest text-xs">No matching classes found</p>
                    </div>
                ) : filteredClasses.map((cls) => (
                    <div key={cls.id} className="bg-card rounded-[2.5rem] border border-border p-8 hover:shadow-xl hover:shadow-blue-900/5 transition-all group relative overflow-hidden flex flex-col">
                        <div className="absolute top-0 right-0 w-32 h-32 bg-muted rounded-bl-[4rem] -mr-16 -mt-16 group-hover:bg-blue-50/10 dark:group-hover:bg-blue-900/20 transition-colors"></div>
                        
                        <div className="relative z-10 flex justify-between items-start mb-6">
                            <div className="w-14 h-14 rounded-2xl bg-primary flex items-center justify-center text-white shadow-lg shadow-blue-900/10 group-hover:scale-110 transition-transform">
                                <Building2 size={28} />
                            </div>
                            <button 
                                onClick={(e) => { e.stopPropagation(); deleteClass(cls.id); }}
                                className="p-2 bg-card rounded-xl border border-border text-text-muted hover:text-rose-500 hover:border-rose-300 transition-all shadow-sm opacity-0 group-hover:opacity-100"
                            >
                                <Trash2 size={16} />
                            </button>
                        </div>

                        <div className="relative z-10 mb-8 flex-grow">
                            <h4 className="text-2xl font-black text-text tracking-tighter group-hover:text-primary transition-colors">{cls.name}</h4>
                            <p className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted mt-1">Section: {cls.section || 'General'}</p>
                        </div>

                        <div className="relative z-10 grid grid-cols-2 gap-3">
                            <div className="bg-muted p-4 rounded-2xl border border-border group-hover:bg-card transition-colors">
                                <div className="flex items-center gap-2 mb-1">
                                    <Users size={12} className="text-primary" />
                                    <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted">Enrollment</p>
                                </div>
                                <p className="text-lg font-black text-text">{cls.student_count || 28}<span className="text-text-muted text-xs ml-1 font-bold">/{cls.capacity}</span></p>
                            </div>
                            <div className="bg-muted p-4 rounded-2xl border border-border group-hover:bg-card transition-colors">
                                <div className="flex items-center gap-2 mb-1">
                                    <BookOpen size={12} className="text-emerald-500" />
                                    <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted">Subjects</p>
                                </div>
                                <p className="text-lg font-black text-text">{subjects.filter(s => s.class_id === cls.id).length}</p>
                            </div>
                        </div>

                        <div className="mt-8 pt-6 border-t border-border flex items-center justify-between">
                            <span className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">ID: SEC-2024-{cls.id}</span>
                            <div className="flex items-center gap-1 text-primary text-[0.65rem] font-black uppercase tracking-widest group-hover:translate-x-1 transition-transform cursor-pointer">
                                Manage Section <ChevronRight size={14} />
                            </div>
                        </div>
                    </div>
                ))}
            </div>
        </div>

        {/* Subject Ledger (Right 5/12) */}
        <div className="lg:col-span-5 space-y-6">
            <div className="flex items-center justify-between px-2">
                <h3 className="text-lg font-black text-text uppercase tracking-tight">Curriculum Ledger</h3>
                <button className="text-primary text-[0.7rem] font-bold hover:underline">View All Intelligence</button>
            </div>

            <div className="bg-card border border-border rounded-[2.5rem] overflow-hidden shadow-sm flex flex-col">
                <div className="p-8 bg-muted/50 border-b border-border flex justify-between items-center dark:bg-background/50">
                    <div className="flex items-center gap-3">
                        <div className="p-2 bg-blue-50/10 dark:bg-blue-900/20 rounded-xl text-primary">
                            <BookOpen size={18} />
                        </div>
                        <p className="text-[0.7rem] font-black uppercase tracking-[3px] text-text">Subject Records</p>
                    </div>
                    <span className="bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 text-[0.6rem] font-black px-2.5 py-1 rounded-full border border-emerald-100 dark:border-emerald-900/30 uppercase tracking-widest">
                        Live
                    </span>
                </div>
                
                <div className="p-2 divide-y divide-border">
                    {subjects.length === 0 ? (
                        <div className="py-20 text-center">
                            <BookOpen size={40} className="mx-auto text-text-muted/30 mb-3" />
                            <p className="text-text-muted font-bold uppercase tracking-widest text-[0.6rem]">No curriculum data recorded</p>
                        </div>
                    ) : subjects.map((s) => (
                        <div key={s.id} className="p-5 flex items-center justify-between hover:bg-muted/50 transition-colors group rounded-2xl cursor-default">
                            <div className="flex items-center gap-4">
                                <div className="w-12 h-12 rounded-2xl bg-slate-900 flex items-center justify-center text-[0.8rem] font-black text-emerald-500 shadow-sm border border-border group-hover:scale-110 transition-transform">
                                    {s.name[0]}
                                </div>
                                <div>
                                    <p className="text-sm font-black text-text tracking-tight group-hover:text-primary transition-colors">{s.name}</p>
                                    <div className="flex items-center gap-2 mt-0.5">
                                        <Building2 size={10} className="text-text-muted" />
                                        <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest">{s.class_name || 'General'}</p>
                                    </div>
                                </div>
                            </div>
                            <div className="flex items-center gap-2">
                                <button className="p-2 text-text-muted hover:text-primary hover:bg-primary/5 rounded-xl transition-all opacity-0 group-hover:opacity-100">
                                    <Edit2 size={16} />
                                </button>
                                <button 
                                    onClick={() => deleteSubject(s.id)}
                                    className="p-2 text-text-muted hover:text-rose-600 hover:bg-rose-500/5 rounded-xl transition-all opacity-0 group-hover:opacity-100"
                                >
                                    <Trash2 size={16} />
                                </button>
                            </div>
                        </div>
                    ))}
                </div>

                <button 
                    className="m-4 mt-2 py-4 bg-muted/50 hover:bg-muted text-text-muted text-[0.65rem] font-black uppercase tracking-[3px] rounded-3xl transition-all border border-border flex items-center justify-center gap-2 dark:bg-background/50"
                    onClick={() => setShowSubjectModal(true)}
                >
                    <Plus size={16} /> Add Subject to Ledger
                </button>
            </div>

            {/* Support Tooltip */}
            <div className="bg-[#002147] rounded-[2.5rem] p-8 text-white shadow-2xl relative overflow-hidden group">
                <div className="absolute right-[-40px] bottom-[-40px] opacity-10 group-hover:rotate-12 transition-transform duration-700">
                    <Sparkles size={180} strokeWidth={1} />
                </div>
                <div className="relative z-10">
                    <h4 className="text-[0.6rem] font-black uppercase tracking-[3px] text-white/40 mb-4 px-1">NextGen Assist</h4>
                    <p className="text-[0.85rem] font-medium text-blue-50/80 leading-relaxed mb-6">
                        Need help organizing your curriculum? Use the subject ledger to assign courses to specific class sections.
                    </p>
                    <button className="px-6 py-3 bg-white/10 hover:bg-white/20 text-white rounded-xl text-[0.65rem] font-black uppercase tracking-widest transition-all border border-white/10">
                        View Documentation
                    </button>
                </div>
            </div>
        </div>
      </div>

      {/* Modals */}
      {showClassModal && (
        <div className="fixed inset-0 bg-[#002147]/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4">
          <div className="bg-card rounded-[2.5rem] w-full max-w-xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-border">
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden">
                <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                    <Sparkles size={180} />
                </div>
              <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight uppercase">Initialize Section</h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Configure academic container</p>
              </div>
              <button onClick={() => setShowClassModal(false)} className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm">
                <X size={20} />
              </button>
            </div>
            <form onSubmit={handleClassSubmit} className="p-10 space-y-6">
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Class Identifier (Name)</label>
                <input className="form-input" value={classForm.name} onChange={e => setClassForm({...classForm, name: e.target.value})} placeholder="e.g., Grade 11" required />
              </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">Section Protocol</label>
                    <input className="form-input" value={classForm.section} onChange={e => setClassForm({...classForm, section: e.target.value})} placeholder="e.g., A-Stream" />
                </div>
                <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Learner Capacity</label>
                    <input className="form-input" type="number" value={classForm.capacity} onChange={e => setClassForm({...classForm, capacity: parseInt(e.target.value)})} required />
                </div>
              </div>
              <button type="submit" className="w-full py-5 bg-primary hover:bg-primary/90 text-white font-black uppercase tracking-widest text-xs rounded-2xl transition-all shadow-xl active:scale-95 flex items-center justify-center gap-3">
                <CheckCircle2 size={18} />
                Finalize Section Records
              </button>
            </form>
          </div>
        </div>
      )}

      {showSubjectModal && (
        <div className="fixed inset-0 bg-[#002147]/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4">
          <div className="bg-card rounded-[2.5rem] w-full max-w-xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-border">
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden">
                <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                    <Sparkles size={180} />
                </div>
              <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight uppercase">Add Subject Intelligence</h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Establish curriculum record</p>
              </div>
              <button onClick={() => setShowSubjectModal(false)} className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm">
                <X size={20} />
              </button>
            </div>
            <form onSubmit={handleSubjectSubmit} className="p-10 space-y-6">
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Subject Identifier (Name)</label>
                <input className="form-input" value={subjectForm.name} onChange={e => setSubjectForm({...subjectForm, name: e.target.value})} placeholder="e.g., Quantum Mechanics" required />
              </div>
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Associate with Section</label>
                <select className="form-input appearance-none cursor-pointer" value={subjectForm.class_id} onChange={e => setSubjectForm({...subjectForm, class_id: e.target.value})} required>
                  <option value="">Select registry entry...</option>
                  {classes.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
              </div>
              <button type="submit" className="w-full py-5 bg-primary hover:bg-primary/90 text-white font-black uppercase tracking-widest text-xs rounded-2xl transition-all shadow-xl active:scale-95 flex items-center justify-center gap-3">
                <Sparkles size={18} />
                Establish Curriculum Record
              </button>
            </form>
          </div>
        </div>
      )}

      <style>{`
        .custom-scrollbar::-webkit-scrollbar { width: 4px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(0, 71, 171, 0.1); border-radius: 10px; }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: rgba(0, 71, 171, 0.2); }
      `}</style>
    </div>
  );
}
