import { useState, useEffect, useRef } from 'react';
import api from '../../store/auth';
import { 
  UserPlus, 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' | 'admin' | 'all';

interface User {
  id: number;
  email: string;
  first_name: string;
  last_name: string;
  role: Role;
  status: 'active' | 'inactive';
  phone?: string;
  created_at: string;
}

export default function Users() {
  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: ''
  });

  const [errors, setErrors] = useState<any>({});

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

  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;
      return matchesSearch && matchesTab;
    });
    setFilteredUsers(filtered);
  }, [searchQuery, activeTab, users]);

  const loadUsers = async () => {
    setLoading(true);
    try {
      const res = await api.get('/users');
      setUsers(res.data);
    } catch (err) {
      console.error('Failed to load user directory');
    } finally {
      setLoading(false);
    }
  };

  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);
    setForm({
      email: user.email,
      password: '',
      first_name: user.first_name,
      last_name: user.last_name,
      role: user.role,
      phone: user.phone || ''
    });
    setShowModal(true);
  };

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

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

  const handleExport = () => {
    const csvData = users.map(u => ({
      ID: u.id,
      Name: `${u.first_name} ${u.last_name}`,
      Email: u.email,
      Role: u.role,
      Status: u.status,
      Joined: new Date(u.created_at).toLocaleDateString()
    }));
    
    const headers = Object.keys(csvData[0]);
    const csvString = [
      headers.join(','),
      ...csvData.map(row => headers.map(h => row[h as keyof typeof row]).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 = `nextgen_users_${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',
    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',
  };

  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: 'Faculty Pulse', 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 [result, setResult] = useState<any>(null);
    const [preview, setPreview] = useState<any[]>([]);
    const fileRef = useRef<HTMLInputElement>(null);

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      const f = e.target.files?.[0];
      if (f) {
        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 runImport = async () => {
      if (!file) return;
      setImporting(true);
      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;
          });
          
          const res = await api.post('/users/bulk', { users: usersToImport });
          setResult(res.data);
          loadUsers();
        };
        reader.readAsText(file);
      } catch (err) {
        alert('Import failed');
      } finally {
        setImporting(false);
      }
    };

    return (
      <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-[2.5rem] w-full max-w-2xl 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">
                <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">Initialize batch registry</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">
            {/* Guide */}
            {!result && (
              <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 (Required Headers)
                </h4>
                <div className="flex flex-wrap gap-2">
                  {['email', 'first_name', 'last_name', 'role', 'phone', 'address', '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>
            )}

            {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 bg-emerald-100 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 rounded-full flex items-center justify-center mx-auto shadow-inner">
                  <Check size={40} strokeWidth={3} />
                </div>
                <div>
                  <h3 className="text-2xl font-black text-text uppercase tracking-tight">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>
                <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>
            ) : (
              <div className="space-y-6">
                <div 
                  onClick={() => fileRef.current?.click()}
                  className="border-2 border-dashed border-border rounded-3xl p-12 text-center hover:border-primary hover:bg-primary/5 transition-all cursor-pointer group"
                >
                  <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="text-text-muted group-hover:text-primary transition-colors" 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"
                  >
                    {importing ? (
                      <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    ) : <Sparkles size={16} />}
                    {importing ? 'Processing...' : 'Run Directory Import'}
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  };

  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', '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 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">
          <Filter size={18} />
          <span className="text-[0.7rem] font-black uppercase tracking-widest">More Filters</span>
        </button>
      </div>

      {/* User Ledger 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">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={5} 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={5} 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">
                        <img 
                          src={`https://i.pravatar.cc/150?u=${user.id}`} 
                          alt={user.first_name} 
                          className="w-full h-full object-cover"
                          onError={(e) => {
                            (e.target as any).src = `https://ui-avatars.com/api/?name=${user.first_name}+${user.last_name}&background=random`;
                          }}
                        />
                      </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">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">
                    <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>
                      <button 
                        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 
                        className="p-2 text-text-muted hover:text-rose-600 hover:bg-rose-500/5 rounded-lg transition-all"
                        title="Restrict Access"
                      >
                        <Trash2 size={16} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Add/Edit 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-[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">
            {/* 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 ID: 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 => 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}
                    disabled={!!editingUser}
                    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="admin">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>

              {!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' : 'Initialize Account'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {showBulkModal && <BulkImportModal />}

      <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>
  );
}
