import { useState, useEffect } from 'react';
import api from '../store/auth';
import { Avatar } from '../components/Avatar';
import { Modal, ModalBody } from '../components/ui/Modal';
import { 
  UserPlus, Trash2, Search, X,
  ChevronRight, Download, Sparkles,
  GraduationCap, Users, BookOpen, LayoutGrid,
  CheckCircle2, AlertCircle, Phone, Mail,
  CreditCard, TrendingUp, ShieldCheck, Key, Info
} from 'lucide-react';

type Gender = 'male' | 'female' | 'other';

interface Student {
  id: number;
  first_name: string;
  last_name: string;
  email: string;
  phone?: string;
  gender?: Gender | null;
  created_at: string;
  class_name?: string;
  section?: string;
  roll_number?: string;
  status?: 'active' | 'inactive';
}

export default function Students() {
  const [students, setStudents] = useState<Student[]>([]);
  const [classes, setClasses] = useState<any[]>([]);
  const [filteredStudents, setFilteredStudents] = useState<Student[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [showBulkAssign, setShowBulkAssign] = useState(false);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  
  const [form, setForm] = useState({ 
    email: '', 
    password: '', 
    first_name: '', 
    last_name: '', 
    phone: '',
    gender: '' as Gender | ''
  });
  
  const [enrollForm, setEnrollForm] = useState({ 
    student_id: '', 
    class_id: '', 
    roll_number: '' 
  });

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

  useEffect(() => {
    const filtered = students.filter(s => 
      `${s.first_name} ${s.last_name}`.toLowerCase().includes(searchQuery.toLowerCase()) ||
      s.email.toLowerCase().includes(searchQuery.toLowerCase()) ||
      s.class_name?.toLowerCase().includes(searchQuery.toLowerCase())
    );
    setFilteredStudents(filtered);
  }, [searchQuery, students]);

  const loadData = async () => {
    setLoading(true);
    try {
      const [userRes, classRes] = await Promise.all([
        api.get('/users?role=student'),
        api.get('/classes')
      ]);
      
      const rawStudents = userRes.data.users || userRes.data;
      const studentList = Array.isArray(rawStudents) ? rawStudents : [];
      // Defensive dedupe: tests / imports occasionally produce rows with
      // the same numeric id; the table row key must be unique.
      const dedupedById = new Map<number, any>();
      studentList.forEach((s: any) => { if (!dedupedById.has(s.id)) dedupedById.set(s.id, s); });
      setStudents(Array.from(dedupedById.values()).map((s: any) => ({
        ...s,
        class_name: s.enrollment?.class_name || 'Unassigned',
        section: s.enrollment?.section || '-',
        roll_number: s.enrollment?.roll_number || 'N/A',
        status: s.status || 'active'
      })));
      setClasses(classRes.data);
    } catch (err) {
      console.error('Failed to load learner directory');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await api.post('/users', { ...form, role: 'student' });
      setShowModal(false);
      setForm({ email: '', password: '', first_name: '', last_name: '', phone: '', gender: '' });
      loadData();
    } catch (err: any) {
      alert(err.response?.data?.error || 'Error creating learner record');
    }
  };

  const handleEnroll = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await api.post('/enrollments', enrollForm);
      setEnrollForm({ student_id: '', class_id: '', roll_number: '' });
      loadData();
      alert('Learner enrolled successfully!');
    } catch (err) {
      alert('Enrollment protocol failed');
    }
  };

  const deleteStudent = async (id: number) => {
    if (!confirm('Archive this learner record? Institutional data will be preserved but access restricted.')) return;
    try {
      await api.delete(`/users/${id}`);
      loadData();
    } catch (err) {
      alert('Failed to archive record');
    }
  };

  const stats = [
    { label: 'Active Learners', value: students.length, icon: GraduationCap, color: 'blue', trend: 'Records' },
    { label: 'Total Sections', value: classes.length, icon: LayoutGrid, color: 'emerald', trend: 'Active' },
    { label: 'New Enrollees', value: students.filter(s => new Date(s.created_at) > new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)).length, icon: Sparkles, color: 'purple', trend: '30 Days' },
    { label: 'Pending Fee', value: '12', icon: CreditCard, color: 'orange', trend: 'Follow-up' },
  ];

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Header Section */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight text-capitalize uppercase">Learner Index</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">Academic Directory</span>
          </nav>
        </div>
        <div className="flex gap-3">
          <button 
            onClick={() => {
                if (students.length === 0) return;
                const headers = ['ID', 'Name', 'Email', 'Phone', 'Section', 'Gender'];
                const rows = students.map(s => [s.id, `${s.first_name} ${s.last_name}`, s.email, s.phone || '', `${s.class_name} ${s.section}`, s.gender || '']);
                const csv = [headers, ...rows].map(r => r.map(c => `"${String(c).replace(/"/g, '""')}"`).join(',')).join('\n');
                const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url; a.download = 'learner_directory.csv';
                document.body.appendChild(a); a.click();
                document.body.removeChild(a); URL.revokeObjectURL(url);
            }}
            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-background-alt transition-all shadow-sm active:scale-95"
          >
            <Download size={18} />
            Export Records
          </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-background-alt transition-all shadow-sm active:scale-95"
            onClick={() => setShowBulkAssign(true)}
            title="Bulk assign selected students to a class"
          >
            <Users size={18} />
            Bulk Assign
          </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-dark transition-all shadow-lg shadow-primary/10 active:scale-95"
            onClick={() => setShowModal(true)}
          >
            <UserPlus size={18} />
            Onboard Learner
          </button>
        </div>
      </div>

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

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Enrollment Protocol (Left 1/3) */}
        <div className="lg:col-span-1">
            <div className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm h-full">
                <div className="flex items-center gap-3 mb-8">
                    <div className="w-10 h-10 rounded-xl bg-accent/10 flex items-center justify-center text-accent shadow-sm">
                        <TrendingUp size={20} />
                    </div>
                    <div>
                        <h3 className="text-lg font-black text-text tracking-tight uppercase">Enrollment</h3>
                        <p className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">Section Assignment</p>
                    </div>
                </div>

                <form onSubmit={handleEnroll} className="space-y-6">
                    <div className="space-y-1.5">
                        <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Select Learner</label>
                        <select 
                            className="form-input appearance-none cursor-pointer" 
                            value={enrollForm.student_id} 
                            onChange={e => setEnrollForm({...enrollForm, student_id: e.target.value})} 
                            required
                        >
                            <option value="">Choose directory entry...</option>
                            {students.map(s => (
                                <option key={s.id} value={s.id}>{s.first_name} {s.last_name}</option>
                            ))}
                        </select>
                    </div>

                    <div className="space-y-1.5">
                        <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Academic Section</label>
                        <select 
                            className="form-input appearance-none cursor-pointer" 
                            value={enrollForm.class_id} 
                            onChange={e => setEnrollForm({...enrollForm, class_id: e.target.value})} 
                            required
                        >
                            <option value="">Select class section...</option>
                            {classes.map(c => (
                                <option key={c.id} value={c.id}>{c.name} {c.section}</option>
                            ))}
                        </select>
                    </div>

                    <div className="space-y-1.5">
                        <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Roll Identifier</label>
                        <input 
                            className="form-input" 
                            placeholder="e.g. 2024-001"
                            value={enrollForm.roll_number} 
                            onChange={e => setEnrollForm({...enrollForm, roll_number: e.target.value})} 
                        />
                    </div>

                    <button type="submit" className="w-full py-4 bg-slate-900 dark:bg-slate-800 hover:bg-black 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-3">
                        <CheckCircle2 size={18} />
                        Execute Enrollment
                    </button>
                </form>
            </div>
        </div>

        {/* Directory Ledger (Right 2/3) */}
        <div className="lg:col-span-2 space-y-6">
            <div className="bg-card border border-border rounded-[2rem] p-2 shadow-sm flex flex-col sm:flex-row items-stretch sm:items-center gap-4">
                <div className="relative group flex-1">
                    <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
                    <input 
                        type="text" 
                        className="w-full bg-muted/50 border border-border rounded-2xl pl-11 pr-4 py-3.5 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all dark:bg-background/50"
                        placeholder="Search by name, email or section..."
                        value={searchQuery}
                        onChange={e => setSearchQuery(e.target.value)}
                    />
                </div>
            </div>

            <div className="bg-card border border-border rounded-[2.5rem] shadow-sm overflow-hidden border-collapse">
                <div className="overflow-x-auto">
                    <table className="w-full text-left">
                        <thead>
                            <tr className="bg-muted/50 border-b border-border">
                                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Learner</th>
                                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Gender</th>
                                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Section</th>
                                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Contact Info</th>
                                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-border/50">
                            {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]">Loading...</p>
                                    </td>
                                </tr>
                            ) : filteredStudents.length === 0 ? (
                                <tr>
                                    <td colSpan={5} className="py-24 text-center">
                                        <Users size={48} className="mx-auto text-text-muted/30 mb-4" />
                                        <p className="text-text-muted font-bold uppercase tracking-widest text-[0.65rem]">No matching learner records</p>
                                    </td>
                                </tr>
                            ) : filteredStudents.map((student) => (
                                <tr key={student.id} className="hover:bg-background-alt/40 transition-colors group cursor-default">
                                    <td className="px-8 py-5">
                                        <div className="flex items-center gap-4">
                                            <div className="w-12 h-12 rounded-2xl bg-background-alt 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=${student.id}`} 
                                                  firstName={student.first_name} 
                                                  lastName={student.last_name} 
                                                />
                                            </div>
                                            <div>
                                                <div className="text-[0.95rem] font-bold text-text group-hover:text-primary transition-colors">{student.first_name} {student.last_name}</div>
                                                <div className="text-[0.6rem] text-text-muted font-black tracking-tighter uppercase mt-0.5">Roll: {student.roll_number}</div>
                                            </div>
                                        </div>
                                    </td>
                                    <td className="px-8 py-5">
                                        <span className="text-[0.65rem] font-black uppercase tracking-widest text-text-secondary">
                                            {student.gender || 'Not specified'}
                                        </span>
                                    </td>
                                    <td className="px-8 py-5">
                                        <span className="px-3 py-1.5 rounded-xl bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border border-blue-100 dark:border-blue-900/30 text-[0.65rem] font-black uppercase tracking-widest">
                                            {student.class_name} {student.section}
                                        </span>
                                    </td>
                                    <td className="px-8 py-5">
                                        <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" />
                                                {student.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" />
                                                {student.phone || 'N/A'}
                                            </div>
                                        </div>
                                    </td>
                                    <td className="px-8 py-5 text-right">
                                        <div className="flex justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                            <button
                                                onClick={() => deleteStudent(student.id)}
                                                className="p-2.5 bg-card border border-border text-text-muted hover:text-rose-500 hover:border-rose-300 transition-all shadow-sm"
                                            >
                                                <Trash2 size={16} />
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
      </div>

      {/* Onboarding Modal */}
      {showModal && (
        <Modal
          open={true}
          onClose={() => setShowModal(false)}
          title="Learner Registry"
          icon={ShieldCheck}
          subtitle="Add new learner"
          maxWidth="max-w-xl"
          zIndex={150}
        >
          <ModalBody className="p-0 overflow-y-auto custom-scrollbar">
            <form id="students-onboard-form" onSubmit={handleSubmit} className="p-10 space-y-6">
              <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="form-input" value={form.first_name} onChange={e => setForm({...form, first_name: e.target.value})} placeholder="Given name" required />
                </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="form-input" value={form.last_name} onChange={e => setForm({...form, last_name: e.target.value})} placeholder="Surname" required />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">System Identifier (Email)</label>
                <div className="relative">
                    <Mail size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted/50" />
                    <input className="form-input pl-11" type="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})} placeholder="student@nextgen.edu" required />
                </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="form-input appearance-none cursor-pointer" 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>

              <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">Security Protocol</label>
                    <div className="relative">
                        <Key size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted/50" />
                        <input className="form-input pl-11" type="password" value={form.password} onChange={e => setForm({...form, password: e.target.value})} placeholder="••••••••" required />
                    </div>
                </div>
                <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Contact Link</label>
                    <div className="relative">
                        <Phone size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted/50" />
                        <input className="form-input pl-11" value={form.phone} onChange={e => setForm({...form, phone: e.target.value})} placeholder="+1 234..." />
                    </div>
                </div>
              </div>

              <div className="flex items-center gap-3 p-4 bg-primary/5 dark:bg-primary/10 rounded-2xl border border-primary/10">
                <div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary shadow-sm"><Info size={20} /></div>
                <div className="flex-1">
                    <p className="text-[0.65rem] font-black uppercase text-primary tracking-widest">Enrollment Readiness</p>
                    <p className="text-[0.6rem] font-bold text-text-muted">You can assign this learner to a section after onboarding.</p>
                </div>
              </div>

              <button 
                type="submit" 
                className="w-full py-5 bg-primary hover:bg-primary-dark text-white font-black uppercase tracking-widest text-xs rounded-2xl transition-all shadow-xl active:scale-95 flex items-center justify-center gap-3 shadow-primary/20"
              >
                <Sparkles size={18} />
                Finalize Registry Entry
              </button>
            </form>
          </ModalBody>
        </Modal>
      )}

      {/* Phase 1 PR 3 — Bulk assign students to a class */}
      {showBulkAssign && (
        <BulkAssignStudentsModal
          students={filteredStudents}
          classes={classes}
          onClose={() => setShowBulkAssign(false)}
          onAssigned={() => { loadData(); setShowBulkAssign(false); }}
        />
      )}

      <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; }
      `}</style>
    </div>
  );
}

// Phase 1 PR 3 — Bulk assign students modal.
// Lets admin pick a target class + check the students to add. Calls
// POST /api/students/bulk-enroll (idempotent — existing rows are
// reported as `skipped`, not double-inserted).
function BulkAssignStudentsModal({
  students, classes, onClose, onAssigned,
}: {
  students: { id: number; first_name: string; last_name: string; email: string }[];
  classes: { id: number; name: string; section?: string }[];
  onClose: () => void;
  onAssigned: () => void;
}) {
  const [classId, setClassId] = useState<number | ''>('');
  const [selected, setSelected] = useState<Set<number>>(new Set());
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState('');

  const filtered = students.filter((s) => {
    if (!search) return true;
    const q = search.toLowerCase();
    return (
      s.first_name?.toLowerCase().includes(q) ||
      s.last_name?.toLowerCase().includes(q) ||
      s.email?.toLowerCase().includes(q)
    );
  });

  const handleSubmit = async () => {
    setError(null);
    if (!classId) return setError('Pick a target class');
    if (selected.size === 0) return setError('Select at least one student');
    setSubmitting(true);
    try {
      const { data } = await api.post('/students/bulk-enroll', {
        classId: Number(classId),
        studentIds: Array.from(selected),
      });
      const summary = `Added ${data.added.length}, skipped ${data.skipped.length}, errors ${data.errors.length}`;
      alert(summary);
      onAssigned();
    } catch (err: any) {
      setError(err.response?.data?.error || err.message || 'Bulk assign failed');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4" onClick={onClose}>
      <div
        className="bg-card border border-border rounded-2xl shadow-2xl w-full max-w-2xl p-6 relative max-h-[90vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        <button
          onClick={onClose}
          className="absolute top-4 right-4 text-text-muted hover:text-text"
          title="Close"
        >
          <X size={18} />
        </button>
        <h2 className="text-lg font-black text-text mb-1">Bulk assign students</h2>
        <p className="text-xs text-text-muted mb-4">Pick the target class, then tick the students to enrol. Existing enrolments are reported as skipped.</p>

        <div className="mb-4">
          <label className="block text-xs font-bold uppercase tracking-wider text-text-muted mb-1">Target class</label>
          <select
            value={classId}
            onChange={(e) => setClassId(e.target.value ? Number(e.target.value) : '')}
            className="w-full px-3 py-2 rounded-xl border border-border bg-background text-text text-sm"
          >
            <option value="">— Select a class —</option>
            {classes.map((c) => (
              <option key={c.id} value={c.id}>
                {c.name}{c.section ? ` ${c.section}` : ''}
              </option>
            ))}
          </select>
        </div>

        <input
          type="text"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Search students…"
          className="w-full px-3 py-2 rounded-xl border border-border bg-background text-text text-sm mb-2"
        />
        <div className="max-h-80 overflow-y-auto border border-border rounded-xl divide-y divide-border/50">
          {filtered.length === 0 ? (
            <div className="p-4 text-center text-text-muted text-sm">No matching students.</div>
          ) : (
            filtered.map((s) => {
              const checked = selected.has(s.id);
              return (
                <label key={s.id} className="flex items-center gap-3 p-2 hover:bg-background-alt cursor-pointer">
                  <input
                    type="checkbox"
                    checked={checked}
                    onChange={(e) => {
                      const next = new Set(selected);
                      if (e.target.checked) next.add(s.id);
                      else next.delete(s.id);
                      setSelected(next);
                    }}
                    className="w-4 h-4"
                  />
                  <div className="min-w-0 flex-1">
                    <div className="font-bold text-sm text-text truncate">
                      {s.first_name} {s.last_name}
                    </div>
                    <div className="text-xs text-text-muted truncate">{s.email}</div>
                  </div>
                </label>
              );
            })
          )}
        </div>

        {error && <div className="text-sm text-rose-500 mt-2">{error}</div>}

        <div className="flex items-center justify-end gap-2 mt-4">
          <span className="text-xs text-text-muted mr-auto">{selected.size} selected</span>
          <button
            onClick={onClose}
            className="px-4 py-2 rounded-xl text-sm font-bold text-text-secondary hover:bg-background-alt"
          >
            Cancel
          </button>
          <button
            onClick={handleSubmit}
            disabled={submitting || !classId || selected.size === 0}
            className="px-4 py-2 rounded-xl text-sm font-bold bg-primary text-white disabled:opacity-50"
          >
            {submitting ? 'Assigning…' : `Assign ${selected.size}`}
          </button>
        </div>
      </div>
    </div>
  );
}