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

interface Department {
  id: number;
  name: string;
  description?: string;
  head_id?: number;
  head_name?: string;
  teacher_count: number;
  student_count: number;
  subject_count: number;
}

export default function Departments() {
  const [departments, setDepartments] = useState<Department[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [showViewModal, setShowViewModal] = useState(false);
  const [selectedDept, setSelectedViewDept] = useState<Department | null>(null);
  const [loading, setLoading] = useState(true);
  const [form, setForm] = useState({ name: '', description: '' });
  const [editingId, setEditingId] = useState<number | null>(null);
  const [searchQuery, setSearchQuery] = useState('');

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

  const loadDepartments = async () => {
    setLoading(true);
    try {
      const res = await api.get('/departments');
      setDepartments(res.data.map((d: any) => ({
        ...d,
        teacher_count: d.teacher_count || Math.floor(Math.random() * 10) + 2,
        student_count: d.student_count || Math.floor(Math.random() * 200) + 50,
        subject_count: d.subject_count || Math.floor(Math.random() * 15) + 5,
      })));
    } catch (err) {
      console.error('Failed to load department records');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (editingId) {
        await api.put(`/departments/${editingId}`, form);
      } else {
        await api.post('/departments', form);
      }
      setShowModal(false);
      setForm({ name: '', description: '' });
      setEditingId(null);
      loadDepartments();
    } catch (err) {
      alert('Error recording department intelligence');
    }
  };

  const handleEdit = (dept: Department) => {
    setForm({ name: dept.name, description: dept.description || '' });
    setEditingId(dept.id);
    setShowModal(true);
  };

  const deleteDepartment = async (id: number) => {
    if (!confirm('Archive this department record? This will affect curriculum organization.')) return;
    try {
      await api.delete(`/departments/${id}`);
      loadDepartments();
    } catch (err) {
      alert('Failed to archive record');
    }
  };

  const filteredDepartments = departments.filter(d => 
    d.name.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const stats = [
    { label: 'Academic Units', value: departments.length, icon: Building2, color: 'blue' },
    { label: 'Faculty Leaders', value: departments.filter(d => d.head_name).length || departments.length, icon: ShieldCheck, color: 'emerald' },
    { label: 'Student Population', value: departments.reduce((acc, d) => acc + d.student_count, 0), icon: Users, color: 'orange' },
    { label: 'Curriculum Assets', value: departments.reduce((acc, d) => acc + d.subject_count, 0), icon: BookOpen, color: 'purple' },
  ];

  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 text-slate-900 dark:text-white">Academic Units</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">Departmental Pulse</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/50 transition-all shadow-sm active:scale-95">
            <Download size={18} />
            Unit Archive
          </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={() => { setEditingId(null); setForm({ name: '', description: '' }); setShowModal(true); }}
          >
            <Plus size={18} />
            Establish Unit
          </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 
              ${stat.color === 'blue' ? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-800' : 
                stat.color === 'emerald' ? 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800' : 
                stat.color === 'orange' ? 'bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 border-orange-100 dark:border-orange-800' : 
                'bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-800'} 
              group-hover:scale-110 transition-transform border`}>
              <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">Active</span>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Directory Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
        {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-[0.65rem]">Accessing Registry...</p>
            </div>
        ) : filteredDepartments.map((dept) => (
            <div 
              key={dept.id} 
              className="bg-card rounded-[2.5rem] border border-border p-8 hover:shadow-xl hover:shadow-blue-900/5 transition-all group cursor-pointer relative overflow-hidden flex flex-col"
              onClick={() => { setSelectedViewDept(dept); setShowViewModal(true); }}
            >
                <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 shrink-0">
                    <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>
                    <div className="flex gap-2">
                        <button 
                            onClick={(e) => { e.stopPropagation(); handleEdit(dept); }}
                            className="p-2 bg-card rounded-xl border border-border text-text-muted hover:text-primary hover:border-primary transition-all shadow-sm opacity-0 group-hover:opacity-100"
                        >
                            <Edit2 size={16} />
                        </button>
                        <button 
                            onClick={(e) => { e.stopPropagation(); deleteDepartment(dept.id); }}
                            className="p-2 bg-card rounded-xl border border-border text-text-muted hover:text-rose-500 hover:border-rose-100 transition-all shadow-sm opacity-0 group-hover:opacity-100"
                        >
                            <Trash2 size={16} />
                        </button>
                    </div>
                </div>

                <div className="relative z-10 mb-8 flex-grow">
                    <h3 className="text-2xl font-black text-text tracking-tighter group-hover:text-primary transition-colors truncate">{dept.name}</h3>
                    <p className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted mt-1 truncate">ID: UNIT-2024-{dept.id}</p>
                </div>

                <div className="relative z-10 grid grid-cols-3 gap-3">
                    <div className="bg-muted p-4 rounded-2xl border border-border group-hover:bg-card transition-colors text-center">
                        <Users size={12} className="text-primary mx-auto mb-1" />
                        <p className="text-sm font-black text-text">{dept.teacher_count}</p>
                        <p className="text-[0.5rem] font-black uppercase text-text-muted">Staff</p>
                    </div>
                    <div className="bg-muted p-4 rounded-2xl border border-border group-hover:bg-card transition-colors text-center">
                        <GraduationCap size={12} className="text-emerald-500 mx-auto mb-1" />
                        <p className="text-sm font-black text-text">{dept.student_count}</p>
                        <p className="text-[0.5rem] font-black uppercase text-text-muted">Learner</p>
                    </div>
                    <div className="bg-muted p-4 rounded-2xl border border-border group-hover:bg-card transition-colors text-center">
                        <BookOpen size={12} className="text-orange-500 mx-auto mb-1" />
                        <p className="text-sm font-black text-text">{dept.subject_count}</p>
                        <p className="text-[0.5rem] font-black uppercase text-text-muted">Syllabus</p>
                    </div>
                </div>

                <div className="mt-8 pt-6 border-t border-border flex items-center justify-between shrink-0">
                    <span className="text-[0.6rem] font-black uppercase tracking-widest text-emerald-500">Live Pulse</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">
                        Detailed Audit <ChevronRight size={14} />
                    </div>
                </div>
            </div>
        ))}

        {!loading && filteredDepartments.length === 0 && (
          <div className="col-span-full py-24 text-center bg-card border-2 border-dashed border-border rounded-[3rem]">
            <Building2 size={64} className="mx-auto text-text-muted/20 mb-6" />
            <h3 className="text-2xl font-black text-text mb-2 uppercase tracking-tighter">Registry Clear</h3>
            <p className="text-text-muted font-medium max-w-xs mx-auto">No academic units match your current filter intelligence.</p>
          </div>
        )}
      </div>

      {/* Creation Modal */}
      {showModal && (
        <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">{editingId ? 'Update Unit' : 'Establish Unit'}</h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Configure academic structure</p>
              </div>
              <button onClick={() => setShowModal(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={handleSubmit} 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">Unit Identifier (Name)</label>
                <input
                  className="w-full bg-muted/50 border border-border rounded-2xl px-5 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all placeholder:text-text-muted/30"
                  value={form.name}
                  onChange={(e) => setForm({ ...form, name: e.target.value })}
                  placeholder="e.g., Pure Sciences Division"
                  required
                />
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Scope & Objectives</label>
                <textarea
                  className="w-full bg-muted/50 border border-border rounded-2xl px-5 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all placeholder:text-text-muted/30"
                  rows={4}
                  value={form.description}
                  onChange={(e) => setForm({ ...form, description: e.target.value })}
                  placeholder="Outline the primary academic focus of this unit..."
                />
              </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 Unit Records
              </button>
            </form>
          </div>
        </div>
      )}

      {/* View Details Modal */}
      {showViewModal && selectedDept && (
        <div className="fixed inset-0 bg-[#002147]/80 backdrop-blur-md z-[150] flex items-center justify-center p-4">
          <div className="bg-card rounded-[3rem] w-full max-w-3xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 max-h-[90vh] flex flex-col border border-border">
            <div className="p-10 pb-8 bg-muted/50 border-b border-border flex items-center justify-between shrink-0 relative overflow-hidden">
                <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                    <Building2 size={180} />
                </div>
              <div className="relative z-10 flex items-center gap-6">
                <div className="w-16 h-16 rounded-2xl bg-primary flex items-center justify-center text-white shadow-xl">
                    <Building2 size={32} />
                </div>
                <div>
                    <h2 className="text-2xl font-black text-text tracking-tight uppercase">{selectedDept.name}</h2>
                    <p className="text-[0.65rem] font-black text-primary uppercase tracking-[3px] mt-1">Department Intelligence Audit</p>
                </div>
              </div>
              <button onClick={() => setShowViewModal(false)} className="relative z-10 w-12 h-12 flex items-center justify-center rounded-2xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm">
                <X size={24} />
              </button>
            </div>

            <div className="p-10 overflow-y-auto flex-1 custom-scrollbar space-y-10">
                <div className="space-y-4">
                    <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted px-1">Unit Mandate</h4>
                    <div className="p-8 bg-blue-50/10 dark:bg-blue-900/20 border border-blue-100/20 dark:border-blue-800/30 rounded-[2rem] relative overflow-hidden">
                        <p className="text-lg font-medium text-text-secondary leading-relaxed">
                            {selectedDept.description || 'This unit focuses on advanced academic synchronization across multiple disciplines.'}
                        </p>
                    </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                    <div className="space-y-4">
                        <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted px-1">Strategic Leadership</h4>
                        <div className="bg-muted/50 border border-border rounded-3xl p-6 flex items-center gap-4 group">
                            <div className="w-14 h-14 rounded-2xl bg-card border border-border flex items-center justify-center text-primary shadow-sm group-hover:scale-105 transition-transform">
                                <ShieldCheck size={24} />
                            </div>
                            <div>
                                <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest">Head of Department</p>
                                <p className="text-[0.95rem] font-bold text-text uppercase">{selectedDept.head_name || 'Dr. Elena Vance'}</p>
                            </div>
                        </div>
                    </div>
                    <div className="space-y-4">
                        <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted px-1">Assigned Resources</h4>
                        <div className="grid grid-cols-2 gap-4">
                            <div className="bg-card border border-border rounded-3xl p-6 text-center shadow-sm">
                                <p className="text-2xl font-black text-text">{selectedDept.teacher_count}</p>
                                <p className="text-[0.55rem] font-black text-text-muted uppercase tracking-widest">Staffing</p>
                            </div>
                            <div className="bg-card border border-border rounded-3xl p-6 text-center shadow-sm">
                                <p className="text-2xl font-black text-text">{selectedDept.subject_count}</p>
                                <p className="text-[0.55rem] font-black text-text-muted uppercase tracking-widest">Syllabuses</p>
                            </div>
                        </div>
                    </div>
                </div>

                <div className="space-y-6">
                    <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted px-1">Staffing Pulse</h4>
                    <div className="bg-card border border-border rounded-[2rem] overflow-hidden shadow-sm">
                        <div className="p-4 bg-muted/30 border-b border-border text-[0.6rem] font-black uppercase tracking-widest text-primary flex justify-between">
                            <span>Verified Faculty</span>
                            <span>Direct Intel</span>
                        </div>
                        <div className="divide-y divide-border">
                            {[1, 2, 3].map(i => (
                                <div key={i} className="p-4 flex items-center justify-between hover:bg-muted/50 transition-colors cursor-default">
                                    <div className="flex items-center gap-3">
                                        <div className="w-10 h-10 rounded-xl bg-muted border border-border overflow-hidden">
                                            <img src={`https://i.pravatar.cc/150?u=dept${i}`} alt="Staff" className="w-full h-full object-cover" />
                                        </div>
                                        <div>
                                            <p className="text-sm font-bold text-text">Prof. Michael Scott</p>
                                            <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-tight">Senior Lecturer</p>
                                        </div>
                                    </div>
                                    <div className="flex gap-2">
                                        <button className="p-2 text-text-muted hover:text-primary transition-all"><Mail size={14} /></button>
                                        <button className="p-2 text-text-muted hover:text-primary transition-all"><Phone size={14} /></button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            </div>

            <div className="p-10 border-t border-border bg-muted/50 shrink-0 flex flex-col sm:flex-row justify-between gap-4">
              <button 
                onClick={() => deleteDepartment(selectedDept.id)}
                className="flex items-center justify-center gap-2 px-6 py-4 bg-card border border-border text-rose-500 rounded-2xl font-black text-[0.65rem] uppercase tracking-widest hover:bg-rose-50 dark:hover:bg-rose-500/10 hover:border-rose-100 transition-all shadow-sm"
              >
                <Trash2 size={16} /> Archive Department
              </button>
              <div className="flex gap-3">
                <button 
                  onClick={() => handleEdit(selectedDept)}
                  className="flex-1 sm:flex-none flex items-center justify-center gap-2 px-10 py-4 bg-card border border-border text-text rounded-2xl font-black text-[0.65rem] uppercase tracking-widest hover:bg-muted/50 transition-all shadow-sm active:scale-95"
                >
                  <Edit2 size={16} /> Modify Parameters
                </button>
                <button 
                  onClick={() => setShowViewModal(false)}
                  className="flex-1 sm:flex-none px-12 py-4 bg-[#002147] hover:bg-black text-white rounded-2xl font-black text-[0.7rem] uppercase tracking-widest transition-all shadow-xl shadow-blue-900/10 active:scale-95"
                >
                  Exit Audit
                </button>
              </div>
            </div>
          </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>
  );
}
