import { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { createPortal } from 'react-dom';
import api from '../../store/auth';
import { Avatar } from '../../components/Avatar';
import { 
  UserPlus, UserMinus, Edit2, Trash2, Search, X, 
  ChevronRight, Download, Filter, Sparkles,
  Users as UsersIcon, GraduationCap, Building2,
  TrendingUp, Mail, Phone, Key, ShieldCheck,
  CheckCircle2, AlertCircle, MoreHorizontal,
  Briefcase, Award, Clock, Upload, FileText, Check, ArrowUpRight
} from 'lucide-react';

type Role = 'teacher' | 'student' | 'parent' | 'principal' | 'hr' | 'bursar' | 'school_admin' | 'systems_admin' | 'clubs_head' | 'nurse' | 'dining_staff' | 'librarian' | 'accountant' | 'all';
type Gender = 'male' | 'female' | 'other';

interface User {
  id: number;
  uid: string;
  id_number: string;
  email: string;
  first_name: string;
  last_name: string;
  role: Role;
  status: 'active' | 'inactive';
  phone?: string;
  address?: string;
  gender?: Gender | null;
  date_of_birth?: string;
  emergency_contact?: string;
  emergency_phone?: string;
  created_at: string;
}

export default function Users() {
  const navigate = useNavigate();
  const [users, setUsers] = useState<User[]>([]);
  const [filteredUsers, setFilteredUsers] = useState<User[]>([]);
  const [activeTab, setActiveTab] = useState<Role>('all');
  const [showModal, setShowModal] = useState(false);
  const [showBulkModal, setShowBulkModal] = useState(false);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [editingUser, setEditingUser] = useState<User | null>(null);
  
  const [form, setForm] = useState({ 
    email: '', 
    password: '', 
    first_name: '', 
    last_name: '', 
    role: 'student' as Role,
    phone: '',
    gender: '' as Gender | ''
  });

  const [hasEmailBeenManuallyChanged, setHasEmailBeenManuallyChanged] = useState(false);
  const [institutionDomain, setInstitutionDomain] = useState('nextgen.edu');

  const [studentSearchQuery, setStudentSearchQuery] = useState('');

  const [errors, setErrors] = useState<any>({});
  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'inactive'>('all');
  const [showFilters, setShowFilters] = useState(false);

  useEffect(() => {
    if (!editingUser && !hasEmailBeenManuallyChanged && form.first_name && form.last_name) {
      const email = `${form.first_name.toLowerCase()}.${form.last_name.toLowerCase()}@${institutionDomain}`.replace(/\s+/g, '');
      setForm(prev => ({ ...prev, email }));
    }
  }, [form.first_name, form.last_name, editingUser, hasEmailBeenManuallyChanged, institutionDomain]);

  useEffect(() => {
    loadUsers();
    loadSettings();
  }, []);

  const loadSettings = async () => {
    try {
      const res = await api.get('/settings');
      if (res.data.system_email) {
        const domain = res.data.system_email.split('@')[1];
        if (domain) setInstitutionDomain(domain);
      } else if (res.data.school_name) {
        const domain = res.data.school_name.toLowerCase().replace(/[^a-z0-9]/g, '') + '.edu';
        setInstitutionDomain(domain);
      }
    } catch (err) {
      console.error('Failed to load system parameters for email settings');
    }
  };

  useEffect(() => {
    const filtered = users.filter(user => {
      const matchesSearch =
        `${user.first_name} ${user.last_name}`.toLowerCase().includes(searchQuery.toLowerCase()) ||
        user.email.toLowerCase().includes(searchQuery.toLowerCase());
      const matchesTab = activeTab === 'all' || user.role === activeTab;
      const matchesStatus = statusFilter === 'all' || user.status === statusFilter;
      return matchesSearch && matchesTab && matchesStatus;
    });
    setFilteredUsers(filtered);
  }, [searchQuery, activeTab, statusFilter, users]);

  const loadUsers = async () => {
    setLoading(true);
    try {
      const res = await api.get('/users', { params: { limit: 1000 } }); // Get a larger set for management
      const data = res.data.users || res.data;
      setUsers(Array.isArray(data) ? data : []);
    } catch (err) {
      console.error('Failed to load user directory');
    } finally {
      setLoading(false);
    }
  };

  const handleRestrict = async (id: number) => {
    if (!window.confirm('Are you sure you want to restrict access for this user?')) return;
    try {
      await api.delete(`/users/${id}`);
      loadUsers();
    } catch (err) {
      alert('Failed to delete user');
    }
  };

  const handleResetCredentials = async (id: number) => {
    const newPassword = window.prompt('Enter new temporary password (min 6 chars):', 'changeme123');
    if (!newPassword) return;
    if (newPassword.length < 6) {
      alert('Password too short');
      return;
    }
    
    try {
      await api.patch(`/users/${id}/reset-password`, { password: newPassword });
      alert('Credentials reset successfully');
    } catch (err: any) {
      alert(err.response?.data?.error || 'Failed to reset credentials');
    }
  };

  const [showLinkModal, setShowLinkModal] = useState(false);
  const [selectedParent, setSelectedParent] = useState<User | null>(null);
  const [students, setStudents] = useState<User[]>([]);
  const [linkForm, setLinkForm] = useState({ student_id: '', relationship: 'guardian' });

  const handleOpenLink = async (parent: User) => {
    setSelectedParent(parent);
    setShowLinkModal(true);
    try {
      const res = await api.get('/users', { params: { role: 'student', limit: 1000 } });
      const data = res.data.users || res.data;
      setStudents(Array.isArray(data) ? data : []);
    } catch (err) {
      console.error('Failed to load students');
    }
  };

  const handleLinkSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedParent || !linkForm.student_id) return;
    try {
      await api.post('/users/link-student', {
        parent_id: selectedParent.id,
        student_id: parseInt(linkForm.student_id),
        relationship: linkForm.relationship
      });
      setShowLinkModal(false);
      setLinkForm({ student_id: '', relationship: 'guardian' });
      alert('Student linked successfully');
    } catch (err: any) {
      alert(err.response?.data?.error || 'Failed to link student');
    }
  };

  const validate = () => {
    const newErrors: any = {};
    if (!form.email) newErrors.email = 'Email required';
    if (!form.first_name) newErrors.first_name = 'First name required';
    if (!form.last_name) newErrors.last_name = 'Last name required';
    if (!editingUser && !form.password) newErrors.password = 'Password required';
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;

    try {
      if (editingUser) {
        await api.put(`/users/${editingUser.id}`, form);
      } else {
        await api.post('/users', form);
      }
      setShowModal(false);
      resetForm();
      loadUsers();
    } catch (err: any) {
      alert(err.response?.data?.error || 'Error saving user record');
    }
  };

  const handleEdit = (user: User) => {
    setEditingUser(user);
    setHasEmailBeenManuallyChanged(false);
    setForm({
      email: user.email,
      password: '',
      first_name: user.first_name,
      last_name: user.last_name,
      role: user.role,
      phone: user.phone || '',
      gender: user.gender || ''
    });
    setShowModal(true);
  };

  const handleAddNew = () => {
    setEditingUser(null);
    resetForm();
    setShowModal(true);
  };

  const resetForm = () => {
    setForm({ email: '', password: '', first_name: '', last_name: '', role: 'student', phone: '', gender: '' });
    setHasEmailBeenManuallyChanged(false);
    setErrors({});
  };

  const handleExport = () => {
    if (!users || users.length === 0) {
      alert('No data available to export');
      return;
    }
    const csvData = users.map(u => ({
      'Institutional ID': u.id_number || `UID-2024-${u.id.toString().padStart(4, '0')}`,
      'First Name': u.first_name,
      'Last Name': u.last_name,
      'Email': u.email,
      'Role': u.role,
      'Phone': u.phone || '',
      'Address': u.address || '',
      'Gender': u.gender || '',
      'Date of Birth': u.date_of_birth || '',
      'Emergency Contact': u.emergency_contact || '',
      'Emergency Phone': u.emergency_phone || '',
      'Status': u.status,
      'Joined Date': new Date(u.created_at).toLocaleDateString()
    }));
    
    const headers = Object.keys(csvData[0]);
    const csvString = [
      headers.join(','),
      ...csvData.map(row => headers.map(h => {
        const val = row[h as keyof typeof row];
        return `"${val}"`; // Wrap in quotes to handle commas in data
      }).join(','))
    ].join('\n');
    
    const blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `AAA_Directory_Export_${new Date().toISOString().split('T')[0]}.csv`;
    link.click();
  };

  const roleColors: Record<string, string> = {
    admin: 'bg-rose-50 dark:bg-rose-900/30 text-rose-600 dark:text-rose-400 border-rose-100 dark:border-rose-800',
    systems_admin: 'bg-rose-50 dark:bg-rose-900/30 text-rose-600 dark:text-rose-400 border-rose-100 dark:border-rose-800',
    school_admin: 'bg-rose-50 dark:bg-rose-900/30 text-rose-600 dark:text-rose-400 border-rose-100 dark:border-rose-800',
    teacher: 'bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800',
    student: 'bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-800',
    parent: 'bg-orange-50 dark:bg-orange-900/30 text-orange-600 dark:text-orange-400 border-orange-100 dark:border-orange-800',
    principal: 'bg-purple-50 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-800',
    hr: 'bg-indigo-50 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-400 border-indigo-100 dark:border-indigo-800',
    bursar: 'bg-amber-50 dark:bg-amber-900/30 text-amber-600 dark:text-amber-400 border-amber-100 dark:border-amber-800',
    accountant: 'bg-teal-50 dark:bg-teal-900/30 text-teal-600 dark:text-teal-400 border-teal-100 dark:border-teal-800',
    nurse: 'bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800',
    dining_staff: 'bg-amber-50 dark:bg-amber-900/30 text-amber-600 dark:text-amber-400 border-amber-100 dark:border-amber-800',
    librarian: 'bg-cyan-50 dark:bg-cyan-900/30 text-cyan-600 dark:text-cyan-400 border-cyan-100 dark:border-cyan-800',
    clubs_head: 'bg-violet-50 dark:bg-violet-900/30 text-violet-600 dark:text-violet-400 border-violet-100 dark:border-violet-800',
  };

  const getCounts = (role: Role) => users.filter(u => u.role === role).length;

  const stats = [
    { label: 'System Registry', value: users.length, icon: UsersIcon, color: 'blue', sub: 'Total' },
    { label: 'Teaching Staff', value: getCounts('teacher'), icon: Briefcase, color: 'emerald', sub: 'Active' },
    { label: 'Learner Index', value: getCounts('student'), icon: GraduationCap, color: 'purple', sub: 'Enroll' },
    { label: 'Guardians', value: getCounts('parent'), icon: ShieldCheck, color: 'orange', sub: 'Portal' },
  ];

  const getStatColors = (color: string) => {
    switch (color) {
      case 'blue': return 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-800';
      case 'emerald': return 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800';
      case 'purple': return 'bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-800';
      case 'orange': return 'bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 border-orange-100 dark:border-orange-800';
      default: return 'bg-muted text-text-muted border-border';
    }
  };

  const BulkImportModal = () => {
    const [file, setFile] = useState<File | null>(null);
    const [importing, setImporting] = useState(false);
    const [isDragging, setIsDragging] = useState(false);
    const [progress, setProgress] = useState(0);
    const [result, setResult] = useState<any>(null);
    const [preview, setPreview] = useState<any[]>([]);
    const fileRef = useRef<HTMLInputElement>(null);

    const processFile = (f: File) => {
      setFile(f);
      const reader = new FileReader();
      reader.onload = (event) => {
        const text = event.target?.result as string;
        const rows = text.split('\n').slice(1, 6).map(row => row.split(','));
        setPreview(rows.map(r => ({ email: r[0], name: `${r[1]} ${r[2]}`, role: r[3] })));
      };
      reader.readAsText(f);
    };

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      const f = e.target.files?.[0];
      if (f) processFile(f);
    };

    const handleDragOver = (e: React.DragEvent) => {
      e.preventDefault();
      setIsDragging(true);
    };

    const handleDragLeave = () => {
      setIsDragging(false);
    };

    const handleDrop = (e: React.DragEvent) => {
      e.preventDefault();
      setIsDragging(false);
      const f = e.dataTransfer.files?.[0];
      if (f) {
        processFile(f);
      }
    };

    const runImport = async () => {
      if (!file) return;
      
      setImporting(true);
      setProgress(10);
      
      const progressInterval = setInterval(() => {
        setProgress(prev => {
          if (prev >= 90) return prev;
          return prev + (90 - prev) * 0.1;
        });
      }, 500);

      try {
        const reader = new FileReader();
        reader.onload = async (event) => {
          const text = event.target?.result as string;
          const rows = text.split('\n').map(row => row.split(',').map(cell => cell.trim()));
          const headers = rows[0].map(h => h.toLowerCase().replace(/ /g, '_'));
          const usersToImport = rows.slice(1).filter(r => r.length > 1).map(row => {
            const obj: any = {};
            headers.forEach((h, i) => { obj[h] = row[i]; });
            return obj;
          });
          
          try {
            const res = await api.post('/users/bulk', { users: usersToImport });
            clearInterval(progressInterval);
            setProgress(100);
            setTimeout(() => {
              setResult(res.data);
              setImporting(false);
              loadUsers();
            }, 500);
          } catch (err: any) {
            clearInterval(progressInterval);
            setImporting(false);
            alert(err.response?.data?.error || 'Import failed');
          }
        };
        reader.readAsText(file);
      } catch (err) {
        clearInterval(progressInterval);
        setImporting(false);
        alert('File reading failed');
      }
    };

    return createPortal(
      <div className="fixed inset-0 bg-[#002147]/80 backdrop-blur-md z-[150] flex items-center justify-center p-4" onClick={() => setShowBulkModal(false)}>
        <div className="bg-card rounded-[2.5rem] w-full max-w-2xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-border max-h-[90vh] flex flex-col" onClick={(e) => e.stopPropagation()}>
          <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden shrink-0">
            <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                <Upload size={180} />
            </div>
            <div className="relative z-10">
              <h2 className="text-2xl font-black text-text tracking-tight flex items-center gap-3 uppercase">
                Bulk Account Import
              </h2>
              <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Import CSV to create accounts in bulk</p>
            </div>
            <button onClick={() => setShowBulkModal(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>

          <div className="p-10 space-y-8 overflow-y-auto flex-1 custom-scrollbar">
            {/* Guide */}
            {!result && !importing && (
              <div className="bg-primary/5 rounded-2xl p-6 border border-primary/10">
                <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary mb-4 flex items-center gap-2">
                  <FileText size={14} /> Column Protocol (Supported Headers)
                </h4>
                <div className="flex flex-wrap gap-2">
                  {['email', 'first_name', 'last_name', 'role', 'phone', 'address', 'gender', 'password'].map(h => (
                    <span key={h} className="px-3 py-1 bg-card border border-border text-primary rounded-lg text-[0.65rem] font-bold font-mono">
                      {h}
                    </span>
                  ))}
                </div>
                <p className="text-[0.65rem] text-text-muted mt-4 italic font-medium">
                  * Role values: teacher, student, parent. Default password: changeme123
                </p>
              </div>
            )}

            {importing && (
              <div className="py-20 text-center space-y-6 animate-in fade-in">
                <div className="w-16 h-16 bg-primary/10 text-primary rounded-2xl flex items-center justify-center mx-auto animate-bounce">
                  <Sparkles size={32} />
                </div>
                <div className="space-y-2">
                  <h3 className="text-xl font-black text-text uppercase">Processing Directory</h3>
                  <p className="text-xs font-bold text-text-muted uppercase tracking-widest">Integrating account records...</p>
                </div>
                <div className="max-w-xs mx-auto space-y-2">
                  <div className="h-2 w-full bg-muted rounded-full overflow-hidden border border-border">
                    <div 
                      className="h-full bg-primary transition-all duration-500 ease-out"
                      style={{ width: `${progress}%` }}
                    />
                  </div>
                  <p className="text-[0.6rem] font-black text-primary text-right uppercase">{Math.round(progress)}% Complete</p>
                </div>
              </div>
            )}

            {result ? (
              <div className="space-y-6 text-center py-10 animate-in fade-in slide-in-from-bottom-4">
                <div className={`w-20 h-20 rounded-full flex items-center justify-center mx-auto shadow-inner ${result.failed > 0 ? 'bg-amber-100 dark:bg-amber-900/30 text-amber-600 dark:text-amber-400' : 'bg-emerald-100 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400'}`}>
                  {result.failed > 0 ? <AlertCircle size={40} strokeWidth={3} /> : <Check size={40} strokeWidth={3} />}
                </div>
                <div>
                  <h3 className="text-2xl font-black text-text uppercase tracking-tight">
                    {result.failed > 0 ? 'Import with Exceptions' : 'Import Complete!'}
                  </h3>
                  <p className="text-text-muted font-medium mt-2">Successfully processed directory records.</p>
                </div>
                <div className="grid grid-cols-2 gap-4 max-w-xs mx-auto">
                  <div className="bg-emerald-50/10 p-4 rounded-2xl border border-emerald-100/20">
                    <p className="text-2xl font-black text-emerald-500">{result.created}</p>
                    <p className="text-[0.6rem] font-black uppercase tracking-widest text-emerald-500">Created</p>
                  </div>
                  <div className="bg-rose-50/10 p-4 rounded-2xl border border-rose-100/20">
                    <p className="text-2xl font-black text-rose-500">{result.failed}</p>
                    <p className="text-[0.6rem] font-black uppercase tracking-widest text-rose-500">Errors</p>
                  </div>
                </div>

                {result.results.filter((r: any) => !r.success).length > 0 && (
                  <div className="text-left space-y-2 mt-6">
                    <p className="text-[0.6rem] font-black uppercase tracking-[2px] text-rose-500 px-1">Error Registry (Failed Rows)</p>
                    <div className="bg-rose-50/5 rounded-xl border border-rose-100/10 max-h-40 overflow-y-auto custom-scrollbar">
                      {result.results.filter((r: any) => !r.success).map((r: any, i: number) => (
                        <div key={i} className="px-4 py-2 border-b border-rose-100/5 last:border-0 flex justify-between items-center gap-4">
                          <span className="text-[0.65rem] font-bold text-text truncate">{r.email}</span>
                          <span className="text-[0.6rem] font-black text-rose-500 uppercase shrink-0">{r.error}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                <button 
                  onClick={() => setShowBulkModal(false)}
                  className="mt-6 px-12 py-4 bg-primary hover:bg-primary/90 text-white font-black uppercase tracking-widest text-[0.7rem] rounded-2xl transition-all shadow-xl"
                >
                  Done
                </button>
              </div>
            ) : !importing && (
              <div className="space-y-6">
                <div 
                  onClick={() => fileRef.current?.click()}
                  onDragOver={handleDragOver}
                  onDragLeave={handleDragLeave}
                  onDrop={handleDrop}
                  className={`border-2 border-dashed rounded-3xl p-12 text-center transition-all cursor-pointer group ${isDragging ? 'border-primary bg-primary/10 scale-[1.02]' : 'border-border hover:border-primary hover:bg-primary/5'}`}
                >
                  <input type="file" ref={fileRef} className="hidden" accept=".csv,.txt" onChange={handleFileChange} />
                  <div className="w-16 h-16 bg-muted rounded-2xl flex items-center justify-center mx-auto mb-4 group-hover:scale-110 transition-transform">
                    <Upload className={`transition-colors ${isDragging ? 'text-primary' : 'text-text-muted group-hover:text-primary'}`} size={32} />
                  </div>
                  <p className="text-sm font-bold text-text">{file ? file.name : 'Select CSV file to import'}</p>
                  <p className="text-xs text-text-muted mt-1 font-medium uppercase tracking-widest">Drag and drop or click to browse</p>
                </div>

                {preview.length > 0 && (
                  <div className="space-y-3">
                    <p className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Data Preview (Top 5 rows)</p>
                    <div className="bg-muted/50 rounded-2xl border border-border overflow-hidden overflow-x-auto">
                      <table className="w-full text-left text-[0.65rem]">
                        <thead className="bg-muted border-b border-border">
                          <tr>
                            {Object.keys(preview[0]).map(h => <th key={h} className="px-4 py-2 font-black uppercase text-text-muted">{h}</th>)}
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-border">
                          {preview.map((row, i) => (
                            <tr key={i}>
                              {Object.values(row).map((v: any, j) => <td key={j} className="px-4 py-2 font-medium text-text-secondary">{v}</td>)}
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </div>
                )}

                <div className="flex gap-4 pt-4">
                  <button 
                    disabled={!file || importing}
                    onClick={runImport}
                    className="flex-1 py-5 bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-text-muted text-white font-black uppercase tracking-widest text-[0.7rem] rounded-2xl transition-all shadow-xl active:scale-95 flex items-center justify-center gap-2"
                  >
                    <Sparkles size={16} />
                    Run Directory Import
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    ,
      document.body
    );
  };

  return (
    <div className="space-y-8 animate-in fade-in duration-500 pb-10">
      {/* Header Section */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight text-capitalize uppercase">User Management</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">System Directory</span>
          </nav>
        </div>
        <div className="flex flex-wrap 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"
            onClick={handleExport}
          >
            <Download size={18} className="text-primary" />
            Export Directory
          </button>
          <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"
            onClick={() => setShowBulkModal(true)}
          >
            <Upload size={18} className="text-primary" />
            Bulk Import
          </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={handleAddNew}
          >
            <UserPlus size={18} />
            Create New Account
          </button>
        </div>
      </div>

      <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 ${getStatColors(stat.color)} group-hover:scale-110 transition-transform`}>
              <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.sub}</span>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Directory Control Bar */}
      <div className="bg-card border border-border rounded-3xl p-2 shadow-sm flex flex-col lg:flex-row items-stretch lg:items-center gap-4">
        {/* Role Filter Tabs */}
        <div className="flex p-1 bg-muted/50 rounded-2xl flex-1 min-w-0 overflow-x-auto custom-scrollbar text-text">
          {(['all', 'teacher', 'student', 'parent', 'principal', 'hr', 'bursar', 'accountant', 'nurse', 'dining_staff', 'librarian', 'clubs_head', 'school_admin', 'systems_admin'] as const).map((role) => (
            <button
              key={role}
              onClick={() => setActiveTab(role)}
              className={`
                flex-1 px-4 py-2.5 rounded-xl text-[0.7rem] font-black uppercase tracking-widest transition-all whitespace-nowrap
                ${activeTab === role 
                  ? 'bg-card text-primary shadow-sm ring-1 ring-border' 
                  : 'text-text-muted hover:text-text'}
              `}
            >
              {role}
              {role !== 'all' && <span className="ml-2 opacity-50">{getCounts(role as Role)}</span>}
            </button>
          ))}
        </div>

        {/* Search Bar */}
        <div className="relative group min-w-[300px]">
          <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-blue-500/5 focus:bg-card focus:border-primary transition-all text-text"
            placeholder="Search by name, email or ID..."
            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>

        <button
          onClick={() => setShowFilters(v => !v)}
          className={`px-5 py-3 rounded-2xl border transition-all flex items-center justify-center gap-2 ${showFilters ? 'bg-primary text-white border-primary' : 'bg-muted/50 hover:bg-muted text-text-muted border-border'}`}
        >
          <Filter size={18} />
          <span className="text-[0.7rem] font-black uppercase tracking-widest">More Filters</span>
        </button>
      </div>

      {showFilters && (
        <div className="bg-card border border-border rounded-2xl p-4 shadow-sm flex flex-wrap items-center gap-4 animate-in slide-in-from-top-2 duration-200">
          <span className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted">Status:</span>
          {(['all', 'active', 'inactive'] as const).map(s => (
            <button
              key={s}
              onClick={() => setStatusFilter(s)}
              className={`px-4 py-2 rounded-xl text-[0.65rem] font-black uppercase tracking-widest transition-all border ${statusFilter === s ? 'bg-primary text-white border-primary' : 'bg-muted/50 text-text-muted border-border hover:bg-muted'}`}
            >
              {s}
            </button>
          ))}
        </div>
      )}

      {/* User List Table */}
      <div className="bg-card border border-border rounded-3xl shadow-sm overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="bg-muted/80 border-b border-border">
                <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest">Account Holder</th>
                <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest">System Role</th>
                <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest">Gender</th>
                <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest">Contact Information</th>
                <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest">Account Status</th>
                <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest text-right">Management</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {loading ? (
                <tr>
                  <td colSpan={6} className="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 Directory Records...</p>
                  </td>
                </tr>
              ) : filteredUsers.length === 0 ? (
                <tr>
                  <td colSpan={6} className="py-20 text-center">
                    <UsersIcon size={40} className="mx-auto text-muted mb-4 opacity-20" />
                    <p className="text-text-muted font-bold uppercase tracking-widest text-[0.65rem]">No matching user records found</p>
                  </td>
                </tr>
              ) : filteredUsers.map((user) => (
                <tr key={user.id} className="hover:bg-muted/30 transition-colors group">
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 rounded-xl bg-muted overflow-hidden flex-shrink-0 border border-border shadow-inner group-hover:scale-105 transition-transform flex items-center justify-center">
                        <Avatar 
                          src={`https://api.dicebear.com/9.x/initials/svg?seed=${user.id}`} 
                          firstName={user.first_name}
                          lastName={user.last_name}
                        />
                      </div>
                      <div>
                        <div className="text-[0.9rem] font-bold text-text">{user.first_name} {user.last_name}</div>
                        <div className="text-[0.6rem] text-text-muted font-black tracking-tighter uppercase mt-0.5">{user.id_number || `UID-2024-${user.id.toString().padStart(4, '0')}`}</div>
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <span className={`px-2.5 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-widest border ${roleColors[user.role] || ''}`}>
                      {user.role}
                    </span>
                  </td>
                  <td className="px-6 py-4">
                    <span className="text-[0.65rem] font-black uppercase tracking-widest text-text-secondary">
                      {user.gender || 'Not specified'}
                    </span>
                  </td>
                  <td className="px-6 py-4">
                    <div className="space-y-1">
                      <div className="flex items-center gap-2 text-xs font-medium text-text-secondary">
                        <Mail size={12} className="text-text-muted/50" />
                        {user.email}
                      </div>
                      <div className="flex items-center gap-2 text-[0.65rem] text-text-muted font-bold">
                        <Phone size={12} className="text-text-muted/50" />
                        {user.phone || 'No phone recorded'}
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-2">
                      <div className={`w-2 h-2 rounded-full ${user.status === 'active' ? 'bg-emerald-500' : 'bg-amber-500'} animate-pulse`} />
                      <span className={`text-[0.6rem] font-black uppercase tracking-widest ${user.status === 'active' ? 'text-emerald-600 dark:text-emerald-400' : 'text-amber-600 dark:text-amber-400'}`}>
                        {user.status}
                      </span>
                    </div>
                  </td>
                  <td className="px-6 py-4 text-right">
                    <div className="flex justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                      <button 
                        onClick={() => handleEdit(user)}
                        className="p-2 text-text-muted hover:text-primary hover:bg-primary/5 rounded-lg transition-all"
                        title="Edit Profile"
                      >
                        <Edit2 size={16} />
                      </button>
                      {user.role === 'parent' && (
                        <button 
                          onClick={() => handleOpenLink(user)}
                          className="p-2 text-text-muted hover:text-orange-600 hover:bg-orange-500/5 rounded-lg transition-all"
                          title="Link Students"
                        >
                          <UsersIcon size={16} />
                        </button>
                      )}
                      {user.role === 'student' && user.status === 'active' && (
                        <button 
                          onClick={() => navigate(`/admin/offboarding/wizard/${user.id}`)}
                          className="p-2 text-text-muted hover:text-rose-500 hover:bg-rose-500/5 rounded-lg transition-all"
                          title="Offboard Student"
                        >
                          <UserMinus size={16} />
                        </button>
                      )}
                      <button 
                        onClick={() => handleResetCredentials(user.id)}
                        className="p-2 text-text-muted hover:text-primary hover:bg-primary/5 rounded-lg transition-all"
                        title="Reset Credentials"
                      >
                        <Key size={16} />
                      </button>
                      <button 
                        onClick={() => handleRestrict(user.id)}
                        className="p-2 text-text-muted hover:text-rose-600 hover:bg-rose-50/5 rounded-lg transition-all"
                        title="Restrict Access"
                      >
                        <Trash2 size={16} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Add/Edit Modal */}
      {showModal && createPortal(
        <div className="fixed inset-0 bg-[#002147]/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4" onClick={() => setShowModal(false)}>
          <div className="bg-card rounded-[2rem] w-full max-w-xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-border max-h-[90vh] flex flex-col" onClick={(e) => e.stopPropagation()}>
            {/* Modal Header */}
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden shrink-0">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                <UserPlus size={160} />
              </div>
              <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight uppercase">
                  {editingUser ? 'Update Profile' : 'New System Account'}
                </h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">
                  {editingUser ? `Editing: ${editingUser.id_number || `UID-2024-${editingUser.id}`}` : `Creating ${form.role} account`}
                </p>
              </div>
              <button 
                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" 
                onClick={() => setShowModal(false)}
              >
                <X size={20} />
              </button>
            </div>

            <form onSubmit={handleSubmit} className="p-10 space-y-6 overflow-y-auto flex-1 custom-scrollbar">
              {/* Form Grid */}
              <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">First Name</label>
                  <input 
                    className={`w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all text-text ${errors.first_name ? 'border-red-200 bg-red-50/30' : ''}`}
                    value={form.first_name} 
                    onChange={e => setForm({...form, first_name: e.target.value})} 
                    placeholder="Enter first name"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Last Name</label>
                  <input 
                    className={`w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all text-text ${errors.last_name ? 'border-red-200 bg-red-50/30' : ''}`}
                    value={form.last_name} 
                    onChange={e => setForm({...form, last_name: e.target.value})} 
                    placeholder="Enter last name"
                  />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Email Address</label>
                <input 
                  className={`w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all text-text ${errors.email ? 'border-red-200 bg-red-50/30' : ''}`}
                  type="email"
                  value={form.email} 
                  onChange={e => {
                    setHasEmailBeenManuallyChanged(true);
                    setForm({...form, email: e.target.value});
                  }} 
                  placeholder="name@nextgen.edu"
                />
              </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">Access Role</label>
                  <select 
                    className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-sm font-semibold focus:outline-none focus:border-primary transition-all appearance-none cursor-pointer text-text"
                    value={form.role}
                    onChange={e => setForm({...form, role: e.target.value as Role})}
                  >
                    <option value="teacher">Teacher (SMS)</option>
                    <option value="student">Student (LMS)</option>
                    <option value="parent">Parent Portal</option>
                    <option value="principal">Principal</option>
                    <option value="hr">HR</option>
                    <option value="bursar">Bursar</option>
                    <option value="accountant">Accountant</option>
                    <option value="nurse">Nurse (Sanatorium / Medical)</option>
                    <option value="dining_staff">Dining Hall Staff</option>
                    <option value="librarian">Librarian</option>
                    <option value="clubs_head">Clubs Head</option>
                    <option value="school_admin">School Admin</option>
                    <option value="systems_admin">Systems Admin</option>
                  </select>
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Phone Contact</label>
                  <input 
                    className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-sm font-semibold focus:outline-none focus:border-primary transition-all text-text"
                    value={form.phone} 
                    onChange={e => setForm({...form, phone: e.target.value})} 
                    placeholder="+1 234 567 890"
                  />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Gender</label>
                <select
                  className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-sm font-semibold focus:outline-none focus:border-primary transition-all appearance-none cursor-pointer text-text"
                  value={form.gender}
                  onChange={e => setForm({...form, gender: e.target.value as Gender | ''})}
                >
                  <option value="">Not specified</option>
                  <option value="male">Male</option>
                  <option value="female">Female</option>
                  <option value="other">Other</option>
                </select>
              </div>

              {!editingUser && (
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Initial Password</label>
                  <div className="relative">
                    <Key size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted/50" />
                    <input 
                      className={`w-full bg-muted/50 border border-border rounded-xl pl-11 pr-4 py-3 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all text-text ${errors.password ? 'border-red-200 bg-red-50/30' : ''}`}
                      type="password"
                      value={form.password} 
                      onChange={e => setForm({...form, password: e.target.value})} 
                      placeholder="Minimum 6 characters"
                    />
                  </div>
                </div>
              )}

              <div className="pt-4 flex gap-4">
                <button 
                  type="button" 
                  className="flex-1 py-4 bg-muted/50 hover:bg-muted text-text font-black uppercase tracking-widest text-[0.7rem] rounded-2xl transition-all border border-border" 
                  onClick={() => setShowModal(false)}
                >
                  Cancel
                </button>
                <button 
                  type="submit" 
                  className={`flex-1 py-4 text-white font-black uppercase tracking-widest text-[0.7rem] rounded-2xl transition-all shadow-lg active:scale-95 flex items-center justify-center gap-2 ${editingUser ? 'bg-primary hover:bg-primary/90 shadow-blue-900/10' : 'bg-emerald-600 hover:bg-emerald-700 shadow-emerald-900/10'}`}
                >
                  {editingUser ? <CheckCircle2 size={16} /> : <UserPlus size={16} />}
                  {editingUser ? 'Commit Changes' : 'Create Account'}
                </button>
              </div>
            </form>
          </div>
        </div>
      ,
        document.body
      )}

      {showBulkModal && <BulkImportModal />}

      {showLinkModal && selectedParent && createPortal(
        <div className="fixed inset-0 bg-[#002147]/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4" onClick={() => setShowLinkModal(false)}>
          <div className="bg-card rounded-[2rem] w-full max-w-lg shadow-2xl border border-border overflow-hidden animate-in zoom-in-95 duration-200" onClick={(e) => e.stopPropagation()}>
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden shrink-0">
               <div className="relative z-10">
                <h2 className="text-xl font-black text-text tracking-tight uppercase">Link Student to Parent</h2>
                <p className="text-[0.6rem] font-bold text-text-muted uppercase tracking-widest mt-1">
                  Parent: {selectedParent.first_name} {selectedParent.last_name}
                </p>
              </div>
              <button onClick={() => setShowLinkModal(false)} className="relative z-10 w-8 h-8 flex items-center justify-center rounded-lg bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm">
                <X size={16} />
              </button>
            </div>
            <form onSubmit={handleLinkSubmit} className="p-10 space-y-6">
              <div className="space-y-4">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Search & Select Student</label>
                
                {/* Search Input */}
                <div className="relative group">
                  <Search size={14} className="absolute left-3 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-xl pl-9 pr-4 py-2.5 text-xs font-bold focus:outline-none focus:border-primary transition-all text-text"
                    placeholder="Search student by name or email..."
                    value={studentSearchQuery}
                    onChange={e => setStudentSearchQuery(e.target.value)}
                  />
                </div>

                {/* Student List */}
                <div className="bg-muted/30 border border-border rounded-2xl max-h-48 overflow-y-auto custom-scrollbar">
                  {students
                    .filter(s => 
                      `${s.first_name} ${s.last_name}`.toLowerCase().includes(studentSearchQuery.toLowerCase()) ||
                      s.email.toLowerCase().includes(studentSearchQuery.toLowerCase())
                    )
                    .map(s => (
                      <div 
                        key={s.id} 
                        onClick={() => setLinkForm({...linkForm, student_id: s.id.toString()})}
                        className={`px-4 py-3 border-b border-border last:border-0 cursor-pointer transition-all flex items-center justify-between group ${linkForm.student_id === s.id.toString() ? 'bg-primary/10' : 'hover:bg-muted/50'}`}
                      >
                        <div>
                          <p className={`text-[0.7rem] font-black uppercase tracking-tight ${linkForm.student_id === s.id.toString() ? 'text-primary' : 'text-text'}`}>
                            {s.first_name} {s.last_name}
                          </p>
                          <p className="text-[0.6rem] font-bold text-text-muted">{s.email}</p>
                        </div>
                        {linkForm.student_id === s.id.toString() && (
                          <div className="w-5 h-5 bg-primary text-white rounded-full flex items-center justify-center shadow-sm">
                            <Check size={12} strokeWidth={4} />
                          </div>
                        )}
                      </div>
                    ))}
                  {students.filter(s => 
                      `${s.first_name} ${s.last_name}`.toLowerCase().includes(studentSearchQuery.toLowerCase()) ||
                      s.email.toLowerCase().includes(studentSearchQuery.toLowerCase())
                    ).length === 0 && (
                    <div className="p-8 text-center">
                      <UsersIcon size={24} className="mx-auto text-muted opacity-20 mb-2" />
                      <p className="text-[0.6rem] font-bold text-text-muted uppercase tracking-widest">No matching students</p>
                    </div>
                  )}
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Relationship</label>
                <select 
                  className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-sm font-semibold focus:outline-none focus:border-primary transition-all text-text"
                  value={linkForm.relationship}
                  onChange={e => setLinkForm({...linkForm, relationship: e.target.value})}
                >
                  <option value="father">Father</option>
                  <option value="mother">Mother</option>
                  <option value="guardian">Guardian</option>
                  <option value="other">Other</option>
                </select>
              </div>
              <div className="pt-4 flex gap-4">
                <button 
                  type="button" 
                  className="flex-1 py-3 bg-muted/50 hover:bg-muted text-text font-black uppercase tracking-widest text-[0.65rem] rounded-xl transition-all border border-border" 
                  onClick={() => {
                    setShowLinkModal(false);
                    setStudentSearchQuery('');
                  }}
                >
                  Cancel
                </button>
                <button 
                  type="submit" 
                  disabled={!linkForm.student_id}
                  className="flex-1 py-3 bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-text-muted text-white font-black uppercase tracking-widest text-[0.65rem] rounded-xl transition-all shadow-lg active:scale-95 disabled:scale-100"
                >
                  Link Student
                </button>
              </div>
            </form>
          </div>
        </div>
      ,
        document.body
      )}

      <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); }
        .dark .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.1); }
      `}</style>
    </div>
  );
}