import { API_BASE_URL } from '../../lib/config';
import React, { useEffect, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Users, 
  UserPlus, 
  Edit2, 
  Trash2, 
  X, 
  Check, 
  Search,
  Shield,
  Mail,
  Building2,
  Lock,
  Zap,
  GraduationCap
} from 'lucide-react';
import { cn } from '../../lib/utils';
import { CLUBS } from '../../constants/clubs';
import { Pagination } from './Pagination';

interface User {
  id: number;
  fullName: string;
  email: string;
  role: string;
  department: string;
  password?: string;
  isClubCoordinator?: boolean;
  isPlacementStaff?: boolean;
  isClassIncharge?: boolean;
  inchargeClass?: string;
  inchargeBatch?: string;
  inchargeSection?: string;
  classStrength?: number;
  assignedClubs?: string[];
}

export const UserManagement: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [classes, setClasses] = useState<any[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [formData, setFormData] = useState({
    fullName: '',
    email: '',
    role: 'FACULTY',
    department: '',
    password: '',
    isClubCoordinator: false,
    isPlacementStaff: false,
    isClassIncharge: false,
    inchargeClass: '',
    inchargeBatch: '',
    inchargeSection: '',
    classStrength: 0,
    assignedClubs: [] as string[],
    year: '',
    section: '',
    regNo: '',
    phone: '',
    gender: 'Male',
    collegeName: 'Rajalakshmi Institute of Technology'
  });

  useEffect(() => {
    fetchUsers();
    fetchClasses();
  }, []);

  const fetchClasses = async () => {
    try {
      const response = await fetch(API_BASE_URL + '/api/classes');
      if (response.ok) {
        setClasses(await response.json());
      }
    } catch (error) {
      console.error('Failed to fetch classes:', error);
    }
  };

  const fetchUsers = async () => {
    try {
      const response = await fetch(API_BASE_URL + '/api/admin/users');
      if (response.ok) {
        const data = await response.json();
        setUsers(data);
      }
    } catch (error) {
      console.error('Failed to fetch users:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleOpenModal = (user: User | null = null) => {
    if (user) {
      setEditingUser(user);
      setFormData({
        fullName: user.fullName,
        email: user.email,
        role: user.role,
        department: user.department || '',
        password: '',
        isClubCoordinator: user.isClubCoordinator || false,
        isPlacementStaff: user.isPlacementStaff || false,
        isClassIncharge: user.isClassIncharge || false,
        inchargeClass: user.inchargeClass || '',
        inchargeBatch: user.inchargeBatch || '',
        inchargeSection: user.inchargeSection || '',
        classStrength: user.classStrength || 0,
        assignedClubs: user.assignedClubs || [],
        year: (user as any).year || '',
        section: (user as any).section || '',
        regNo: (user as any).regNo || '',
        phone: (user as any).phone || '',
        gender: (user as any).gender || 'Male',
        collegeName: (user as any).collegeName || 'Rajalakshmi Institute of Technology'
      });
    } else {
      setEditingUser(null);
      setFormData({
        fullName: '',
        email: '',
        role: 'FACULTY',
        department: '',
        password: '',
        isClubCoordinator: false,
        isPlacementStaff: false,
        isClassIncharge: false,
        inchargeClass: '',
        inchargeBatch: '',
        inchargeSection: '',
        classStrength: 0,
        assignedClubs: [],
        year: '',
        section: '',
        regNo: '',
        phone: '',
        gender: 'Male',
        collegeName: 'Rajalakshmi Institute of Technology'
      });
    }
    setIsModalOpen(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if ((formData.role === 'HOD' || formData.role === 'FACULTY') && !formData.department.trim()) {
      alert("Please select at least one department.");
      return;
    }
    const url = editingUser 
      ? `${API_BASE_URL}/api/admin/users/${editingUser.id}` 
      : API_BASE_URL + '/api/admin/users';
    
    const method = editingUser ? 'PUT' : 'POST';

    try {
      const response = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
      });

      if (response.ok) {
        fetchUsers();
        setIsModalOpen(false);
      } else {
        const err = await response.json();
        alert(err.message || 'Operation failed');
      }
    } catch (error) {
      console.error('Operation failed:', error);
      alert('An error occurred during submission.');
    }
  };

  const handleDelete = async (id: number) => {
    if (window.confirm('Are you sure you want to delete this user?')) {
      try {
        const response = await fetch(`${API_BASE_URL}/api/admin/users/${id}`, {
          method: 'DELETE'
        });
        if (response.ok) {
          setUsers(prev => prev.filter(u => u.id !== id));
        }
      } catch (error) {
        console.error('Delete failed:', error);
      }
    }
  };

  const filteredUsers = users
    .filter(u => 
      u.fullName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      u.email.toLowerCase().includes(searchTerm.toLowerCase())
    )
    .sort((a, b) => b.id - a.id);

  const currentUsers = filteredUsers.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  return (
    <div className="space-y-8">
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <h2 className="text-3xl font-black text-text-dark tracking-tight">User Management</h2>
          <p className="text-text-muted font-medium">Add and manage institutional roles and permissions.</p>
        </div>
        
        <button 
          onClick={() => handleOpenModal()}
          className="flex items-center gap-2 bg-brand-navy text-white px-6 py-3 rounded-xl font-black text-[10px] uppercase tracking-widest premium-shadow hover:scale-105 transition-all"
        >
          <UserPlus className="w-4 h-4" />
          Add New User
        </button>
      </div>

      <div className="bg-white rounded-[2.5rem] border border-slate-100 premium-shadow overflow-hidden">
        <div className="p-6 border-b border-slate-50 flex items-center justify-between gap-4">
          <div className="relative flex-1 max-w-md">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted" />
            <input 
              type="text" 
              placeholder="Search users by name or email..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full bg-slate-50 border-transparent rounded-xl py-2 pl-10 pr-4 text-sm focus:bg-white focus:border-brand-indigo transition-all"
            />
          </div>
          <div className="text-[10px] font-black uppercase tracking-widest text-text-muted">
            Total Users: {users.length}
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-left border-collapse">
            <thead>
              <tr className="bg-slate-50/50">
                <th className="px-8 py-5 text-[10px] font-black uppercase tracking-[0.2em] text-text-muted">User Info</th>
                <th className="px-8 py-5 text-[10px] font-black uppercase tracking-[0.2em] text-text-muted">Role</th>
                <th className="px-8 py-5 text-[10px] font-black uppercase tracking-[0.2em] text-text-muted">Department</th>
                <th className="px-8 py-5 text-[10px] font-black uppercase tracking-[0.2em] text-text-muted">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50">
              {currentUsers.map((user) => (
                <tr key={user.id} className="group hover:bg-slate-50/50 transition-colors">
                  <td className="px-8 py-5">
                    <div className="flex items-center gap-4">
                      <div className="w-10 h-10 rounded-full bg-brand-glow flex items-center justify-center text-brand-indigo font-black text-xs">
                        {user.fullName.split(' ').map(n => n[0]).join('').substring(0, 2)}
                      </div>
                      <div className="flex flex-col">
                        <span className="font-bold text-text-dark text-sm">{user.fullName}</span>
                        <span className="text-xs text-text-muted">{user.email}</span>
                      </div>
                    </div>
                  </td>
                  <td className="px-8 py-5">
                    <div className="flex flex-col gap-2 items-start">
                      <span className={cn(
                        "px-3 py-1 rounded-full text-[9px] font-black uppercase tracking-widest border",
                        user.role === 'ADMIN' ? 'bg-purple-50 text-purple-600 border-purple-100' :
                        user.role === 'HOD' ? 'bg-amber-50 text-amber-600 border-amber-100' :
                        user.role === 'PRINCIPAL' ? 'bg-emerald-50 text-emerald-600 border-emerald-100' :
                        'bg-blue-50 text-blue-600 border-blue-100'
                      )}>
                        {user.role}
                      </span>
                      {user.isClassIncharge && (
                        <span className="px-3 py-1 rounded-full text-[9px] font-black uppercase tracking-widest border bg-indigo-50 text-indigo-600 border-indigo-100 flex items-center gap-1">
                          <GraduationCap className="w-3 h-3" />
                          Class Incharge ({user.inchargeClass} {user.inchargeBatch} - Sec {user.inchargeSection})
                        </span>
                      )}
                    </div>
                  </td>
                  <td className="px-8 py-5 text-sm font-bold text-text-secondary">
                    {user.department || 'N/A'}
                  </td>
                  <td className="px-8 py-5">
                    <div className="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                      <button 
                        onClick={() => handleOpenModal(user)}
                        className="p-2 hover:bg-white rounded-lg hover:premium-shadow-sm transition-all text-slate-400 hover:text-brand-indigo"
                      >
                        <Edit2 className="w-4 h-4" />
                      </button>
                      {user.role !== 'ADMIN' && (
                        <button 
                          onClick={() => handleDelete(user.id)}
                          className="p-2 hover:bg-white rounded-lg hover:premium-shadow-sm transition-all text-slate-400 hover:text-status-danger"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        
        <Pagination 
          currentPage={currentPage}
          totalItems={filteredUsers.length}
          itemsPerPage={itemsPerPage}
          onPageChange={setCurrentPage}
          onItemsPerPageChange={(val) => {
            setItemsPerPage(val);
            setCurrentPage(1);
          }}
          itemsPerPageOptions={[5, 10, 20, 50]}
        />
      </div>

      {/* User Modal */}
      <AnimatePresence>
        {isModalOpen && (
          <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setIsModalOpen(false)}
              className="absolute inset-0 bg-slate-900/40 backdrop-blur-sm"
            />
             <motion.div
              initial={{ opacity: 0, scale: 0.9, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.9, y: 20 }}
              className="relative w-full max-w-lg bg-white rounded-[2.5rem] premium-shadow overflow-hidden flex flex-col max-h-[90vh]"
            >
              <form onSubmit={handleSubmit} className="flex flex-col overflow-hidden">
                <div className="p-8 bg-brand-navy text-white flex justify-between items-start shrink-0">
                  <div>
                    <h3 className="text-2xl font-black tracking-tight">
                      {editingUser ? 'Edit User' : 'Add New User'}
                    </h3>
                    <p className="text-white/60 text-xs font-medium mt-1">Configure institutional access credentials.</p>
                  </div>
                  <button 
                    type="button"
                    onClick={() => setIsModalOpen(false)}
                    className="p-2 hover:bg-white/10 rounded-xl transition-all"
                  >
                    <X className="w-6 h-6" />
                  </button>
                </div>

                <div className="p-8 space-y-5 overflow-y-auto custom-scrollbar flex-1 max-h-[65vh]">
                  <div>
                    <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-2 block">Full Name</label>
                    <div className="relative">
                      <Shield className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted" />
                      <input 
                        type="text"
                        required
                        value={formData.fullName}
                        onChange={(e) => setFormData({...formData, fullName: e.target.value})}
                        placeholder="E.g. Dr. Jane Smith"
                        className="w-full bg-slate-50 border-transparent rounded-xl py-3 pl-12 pr-4 text-sm focus:bg-white focus:border-brand-indigo transition-all"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-2 block">Email Address</label>
                    <div className="relative">
                      <Mail className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted" />
                      <input 
                        type="email"
                        required
                        value={formData.email}
                        onChange={(e) => setFormData({...formData, email: e.target.value})}
                        placeholder="jane.smith@rit.edu"
                        className="w-full bg-slate-50 border-transparent rounded-xl py-3 pl-12 pr-4 text-sm focus:bg-white focus:border-brand-indigo transition-all"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-2 block">Role</label>
                    <select 
                      value={formData.role}
                      onChange={(e) => {
                        const newRole = e.target.value;
                        setFormData({
                          ...formData,
                          role: newRole,
                          department: (newRole === 'HOD' || newRole === 'FACULTY' || newRole === 'STUDENT') ? formData.department : ''
                        });
                      }}
                      className="w-full bg-slate-50 border-transparent rounded-xl py-3 px-4 text-sm focus:bg-white focus:border-brand-indigo transition-all appearance-none"
                    >
                      <option value="FACULTY">Faculty</option>
                      <option value="HOD">HoD</option>
                      <option value="PRINCIPAL">Principal</option>
                      <option value="PLACEMENT">Placement</option>
                      <option value="ADMIN">Admin</option>
                      <option value="STUDENT">Student</option>
                    </select>
                  </div>

                  {(formData.role === 'HOD' || formData.role === 'FACULTY') && (
                    <motion.div 
                      initial={{ opacity: 0, height: 0 }}
                      animate={{ opacity: 1, height: 'auto' }}
                      className="space-y-3"
                    >
                      <label className="text-[10px] font-black uppercase tracking-widest text-text-muted block">Department(s)</label>
                      <div className="flex flex-wrap gap-2 p-4 bg-slate-50/50 rounded-2xl border border-slate-100 min-h-[60px]">
                        {[
                          "AI&DS", "AI&ML", "CSE", "CCE", "CSBS", "ECE", 
                          "MECH", "EE(VLSI)", "BIOTECH", "Placement Department", 
                          "H&S Dept", "Club", "Centre"
                        ].map(dept => {
                          const selectedDepts = formData.department ? formData.department.split(',').map(d => d.trim()).filter(Boolean) : [];
                          const isSelected = selectedDepts.includes(dept);
                          return (
                            <button
                              key={dept}
                              type="button"
                              onClick={() => {
                                let updated: string[];
                                if (isSelected) {
                                  updated = selectedDepts.filter(d => d !== dept);
                                } else {
                                  updated = [...selectedDepts, dept];
                                }
                                setFormData({...formData, department: updated.join(', ')});
                              }}
                              className={cn(
                                "px-3 py-1.5 rounded-lg text-[9px] font-black uppercase tracking-widest transition-all border",
                                isSelected
                                  ? "bg-brand-navy text-white border-brand-navy premium-shadow-sm"
                                  : "bg-white text-text-muted border-slate-200 hover:border-brand-indigo/30"
                              )}
                            >
                              {dept}
                            </button>
                          );
                        })}
                      </div>
                    </motion.div>
                  )}

                  {formData.role === 'STUDENT' && (
                    <motion.div 
                      initial={{ opacity: 0, height: 0 }}
                      animate={{ opacity: 1, height: 'auto' }}
                      className="space-y-4 pt-2"
                    >
                      <h4 className="text-xs font-black text-brand-navy uppercase tracking-wider">Student Details</h4>
                      
                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-2 block">Department</label>
                          <select 
                            value={formData.department}
                            onChange={(e) => setFormData({...formData, department: e.target.value})}
                            className="w-full bg-slate-50 border-transparent rounded-xl py-3 px-4 text-sm focus:bg-white focus:border-brand-indigo transition-all appearance-none"
                          >
                            <option value="">Select Department</option>
                            {["AI&DS", "AI&ML", "CSE", "CCE", "CSBS", "ECE", "MECH", "EE(VLSI)", "BIOTECH", "H&S Dept", "Others"].map(d => (
                              <option key={d} value={d}>{d}</option>
                            ))}
                          </select>
                        </div>
                        
                        <div>
                          <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-2 block">Academic Year</label>
                          <select 
                            value={formData.year}
                            onChange={(e) => setFormData({...formData, year: e.target.value})}
                            className="w-full bg-slate-50 border-transparent rounded-xl py-3 px-4 text-sm focus:bg-white focus:border-brand-indigo transition-all appearance-none"
                          >
                            <option value="">Select Year</option>
                            {["1st Year", "2nd Year", "3rd Year", "4th Year", "N/A"].map(y => (
                              <option key={y} value={y}>{y}</option>
                            ))}
                          </select>
                        </div>
                      </div>

                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-2 block">Section</label>
                          <select 
                            value={formData.section}
                            onChange={(e) => setFormData({...formData, section: e.target.value})}
                            className="w-full bg-slate-50 border-transparent rounded-xl py-3 px-4 text-sm focus:bg-white focus:border-brand-indigo transition-all appearance-none"
                          >
                            <option value="">Select Section</option>
                            {["A", "B", "C", "D", "E", "F", "N/A"].map(s => (
                              <option key={s} value={s}>{s}</option>
                            ))}
                          </select>
                        </div>
                        
                        <div>
                          <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-2 block">Register Number</label>
                          <input 
                            type="text"
                            value={formData.regNo}
                            onChange={(e) => setFormData({...formData, regNo: e.target.value})}
                            placeholder="E.g. 211822104001"
                            className="w-full bg-slate-50 border-transparent rounded-xl py-3 px-4 text-sm focus:bg-white focus:border-brand-indigo transition-all"
                          />
                        </div>
                      </div>

                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-2 block">Gender</label>
                          <select 
                            value={formData.gender}
                            onChange={(e) => setFormData({...formData, gender: e.target.value})}
                            className="w-full bg-slate-50 border-transparent rounded-xl py-3 px-4 text-sm focus:bg-white focus:border-brand-indigo transition-all appearance-none"
                          >
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                            <option value="Other">Other</option>
                          </select>
                        </div>
                        
                        <div>
                          <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-2 block">Phone Number</label>
                          <input 
                            type="text"
                            value={formData.phone}
                            onChange={(e) => setFormData({...formData, phone: e.target.value})}
                            placeholder="E.g. 9876543210"
                            className="w-full bg-slate-50 border-transparent rounded-xl py-3 px-4 text-sm focus:bg-white focus:border-brand-indigo transition-all"
                          />
                        </div>
                      </div>

                      <div>
                        <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-2 block">College Name</label>
                        <input 
                          type="text"
                          value={formData.collegeName}
                          onChange={(e) => setFormData({...formData, collegeName: e.target.value})}
                          placeholder="E.g. Rajalakshmi Institute of Technology"
                          className="w-full bg-slate-50 border-transparent rounded-xl py-3 px-4 text-sm focus:bg-white focus:border-brand-indigo transition-all"
                        />
                      </div>
                    </motion.div>
                  )}

                  <div>
                    <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-2 block">
                      {editingUser ? 'New Password (Optional)' : 'Password'}
                    </label>
                    <div className="relative">
                      <Lock className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted" />
                      <input 
                        type="password"
                        required={!editingUser}
                        value={formData.password}
                        onChange={(e) => setFormData({...formData, password: e.target.value})}
                        placeholder="••••••••"
                        className="w-full bg-slate-50 border-transparent rounded-xl py-3 pl-12 pr-4 text-sm focus:bg-white focus:border-brand-indigo transition-all"
                      />
                    </div>
                  </div>

                    <div className="pt-2 grid grid-cols-2 gap-4">
                      <div className="flex items-center justify-between p-4 bg-slate-50/50 rounded-2xl border border-slate-100">
                        <div className="flex items-center gap-3">
                          <div className={cn(
                            "w-10 h-10 rounded-xl flex items-center justify-center transition-all",
                            formData.isClubCoordinator ? "bg-brand-indigo text-white" : "bg-slate-200 text-text-muted"
                          )}>
                            <Shield className="w-5 h-5" />
                          </div>
                          <div>
                            <p className="text-[11px] font-black text-text-dark leading-tight">Club Coordinator</p>
                            <p className="text-[9px] font-bold text-text-muted">Proposals Permission</p>
                          </div>
                        </div>
                        <button
                          type="button"
                          onClick={() => setFormData({...formData, isClubCoordinator: !formData.isClubCoordinator})}
                          className={cn(
                            "w-10 h-5 rounded-full p-1 transition-all duration-300",
                            formData.isClubCoordinator ? "bg-brand-indigo" : "bg-slate-300"
                          )}
                        >
                          <div className={cn(
                            "w-3 h-3 bg-white rounded-full transition-all duration-300 transform",
                            formData.isClubCoordinator ? "translate-x-5" : "translate-x-0"
                          )} />
                        </button>
                      </div>

                      <div className="flex items-center justify-between p-4 bg-slate-50/50 rounded-2xl border border-slate-100">
                        <div className="flex items-center gap-3">
                          <div className={cn(
                            "w-10 h-10 rounded-xl flex items-center justify-center transition-all",
                            formData.isPlacementStaff ? "bg-brand-indigo text-white" : "bg-slate-200 text-text-muted"
                          )}>
                            <Zap className="w-5 h-5" />
                          </div>
                          <div>
                            <p className="text-[11px] font-black text-text-dark leading-tight">Placement Coordinator</p>
                            <p className="text-[9px] font-bold text-text-muted">High Priority Access</p>
                          </div>
                        </div>
                        <button
                          type="button"
                          onClick={() => setFormData({...formData, isPlacementStaff: !formData.isPlacementStaff})}
                          className={cn(
                            "w-10 h-5 rounded-full p-1 transition-all duration-300",
                            formData.isPlacementStaff ? "bg-brand-indigo" : "bg-slate-300"
                          )}
                        >
                          <div className={cn(
                            "w-3 h-3 bg-white rounded-full transition-all duration-300 transform",
                            formData.isPlacementStaff ? "translate-x-5" : "translate-x-0"
                          )} />
                        </button>
                      </div>
                    </div>

                    {formData.role === 'FACULTY' && (
                      <div className="pt-2">
                        <div className="flex items-center justify-between p-4 bg-slate-50/50 rounded-2xl border border-slate-100">
                          <div className="flex items-center gap-3">
                            <div className={cn(
                              "w-10 h-10 rounded-xl flex items-center justify-center transition-all",
                              formData.isClassIncharge ? "bg-brand-indigo text-white" : "bg-slate-200 text-text-muted"
                            )}>
                              <GraduationCap className="w-5 h-5" />
                            </div>
                            <div>
                              <p className="text-[11px] font-black text-text-dark leading-tight">Class Incharge</p>
                              <p className="text-[9px] font-bold text-text-muted">Manage Class Operations</p>
                            </div>
                          </div>
                          <button
                            type="button"
                            onClick={() => setFormData({...formData, isClassIncharge: !formData.isClassIncharge})}
                            className={cn(
                              "w-10 h-5 rounded-full p-1 transition-all duration-300",
                              formData.isClassIncharge ? "bg-brand-indigo" : "bg-slate-300"
                            )}
                          >
                            <div className={cn(
                              "w-3 h-3 bg-white rounded-full transition-all duration-300 transform",
                              formData.isClassIncharge ? "translate-x-5" : "translate-x-0"
                            )} />
                          </button>
                        </div>
                        
                        {formData.isClassIncharge && (
                          <motion.div 
                            initial={{ opacity: 0, height: 0 }}
                            animate={{ opacity: 1, height: 'auto' }}
                            className="mt-4 space-y-4"
                          >
                            <div>
                              <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-2 block">Class / Department</label>
                              <select 
                                required={formData.isClassIncharge}
                                value={formData.inchargeClass}
                                onChange={(e) => setFormData({...formData, inchargeClass: e.target.value, inchargeBatch: '', inchargeSection: ''})}
                                className="w-full bg-slate-50 border-transparent rounded-xl py-3 px-4 text-sm focus:bg-white focus:border-brand-indigo transition-all appearance-none"
                              >
                                <option value="">Select Class</option>
                                {Array.from(new Set(classes.map(c => c.department))).map(dept => (
                                  <option key={dept as string} value={dept as string}>{dept as string}</option>
                                ))}
                              </select>
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                              <div>
                                <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-2 block">Batch / Year</label>
                                <select 
                                  required={formData.isClassIncharge}
                                  value={formData.inchargeBatch}
                                  onChange={(e) => setFormData({...formData, inchargeBatch: e.target.value, inchargeSection: ''})}
                                  className="w-full bg-slate-50 border-transparent rounded-xl py-3 px-4 text-sm focus:bg-white focus:border-brand-indigo transition-all appearance-none"
                                >
                                  <option value="">Select Batch</option>
                                  {Array.from(new Set(classes.filter(c => c.department === formData.inchargeClass).map(c => c.academicYear))).map(year => (
                                    <option key={year as string} value={year as string}>{year as string}</option>
                                  ))}
                                </select>
                              </div>
                              <div>
                                <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-2 block">Section</label>
                                <select 
                                  required={formData.isClassIncharge}
                                  value={formData.inchargeSection}
                                  onChange={(e) => setFormData({...formData, inchargeSection: e.target.value})}
                                  className="w-full bg-slate-50 border-transparent rounded-xl py-3 px-4 text-sm focus:bg-white focus:border-brand-indigo transition-all appearance-none"
                                >
                                  <option value="">Select Section</option>
                                  {(classes.find(c => c.department === formData.inchargeClass && c.academicYear === formData.inchargeBatch)?.sections || []).map((sec: string) => (
                                    <option key={sec} value={sec}>{sec}</option>
                                  ))}
                                </select>
                              </div>
                            </div>
                          </motion.div>
                        )}
                      </div>
                    )}

                    {formData.isClubCoordinator && (
                      <motion.div 
                        initial={{ opacity: 0, height: 0 }}
                        animate={{ opacity: 1, height: 'auto' }}
                        className="mt-4 space-y-3"
                      >
                        <label className="text-[10px] font-black uppercase tracking-widest text-text-muted block">Assigned Clubs</label>
                        <div className="flex flex-wrap gap-2 p-4 bg-slate-50/50 rounded-2xl border border-slate-100 min-h-[60px]">
                          {CLUBS.map(club => (
                            <button
                              key={club}
                              type="button"
                              onClick={() => {
                                const updated = formData.assignedClubs.includes(club)
                                  ? formData.assignedClubs.filter(c => c !== club)
                                  : [...formData.assignedClubs, club];
                                setFormData({...formData, assignedClubs: updated});
                              }}
                              className={cn(
                                "px-3 py-1.5 rounded-lg text-[9px] font-black uppercase tracking-widest transition-all border",
                                formData.assignedClubs.includes(club)
                                  ? "bg-brand-navy text-white border-brand-navy premium-shadow-sm"
                                  : "bg-white text-text-muted border-slate-200 hover:border-brand-indigo/30"
                              )}
                            >
                              {club}
                            </button>
                          ))}
                        </div>
                      </motion.div>
                    )}
                </div>

                <div className="shrink-0 w-full">
                  <button 
                    type="submit"
                    className="w-full bg-brand-navy hover:bg-[#0c365c] text-white py-5 font-black text-xs uppercase tracking-[0.2em] transition-all flex items-center justify-center"
                  >
                    {editingUser ? 'Update User Credentials' : 'Create System User'}
                  </button>
                </div>
              </form>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </div>
  );
};
