/**
 * Enrollments Page
 *
 * Role-aware:
 *   - Student:  list own enrollments + button to request a new one
 *               (with class picker). Can withdraw pending/approved rows.
 *   - Admin/teacher/principal:
 *               list pending requests with approve/reject buttons.
 *               Mass approvals & bulk rejections with multi-select checkboxes.
 *               Student row + admin/teacher share the same page component;
 *               the API filters by role (students see own, staff see all).
 */

import { useEffect, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import { useAuthStore } from '../../store/auth';
import {
  useEnrollmentStore,
  Enrollment,
} from '../../store/enrollments';
import {
  Plus, ChevronRight, CheckCircle2, XCircle, Clock,
  Trash2, BookOpen, Users as UsersIcon, X, AlertTriangle,
  Search, CheckCheck, Filter, CheckSquare, Square, RefreshCw, Check
} from 'lucide-react';

const STAFF_ROLES = ['school_admin', 'systems_admin', 'principal', 'teacher'];

function statusBadge(status: string | null | undefined) {
  switch (status) {
    case 'approved':
    case 'active':
      return 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-950/20 dark:text-emerald-400 dark:border-emerald-900/30';
    case 'pending':
      return 'bg-amber-50 text-amber-600 border-amber-100 dark:bg-amber-950/20 dark:text-amber-400 dark:border-amber-900/30';
    case 'rejected':
      return 'bg-rose-50 text-rose-600 border-rose-100 dark:bg-rose-950/20 dark:text-rose-400 dark:border-rose-900/30';
    case 'withdrawn':
    case 'inactive':
      return 'bg-muted text-text-muted/60 border-border';
    default:
      return 'bg-muted text-text-muted border-border';
  }
}

export function EnrollmentsPage() {
  const { user } = useAuthStore();
  const isStaff = useMemo(
    () => STAFF_ROLES.includes(user?.role || ''),
    [user?.role],
  );

  const {
    myEnrollments,
    pendingApprovals,
    classes,
    isLoading,
    isSubmitting,
    error,
    fetchMyEnrollments,
    fetchPending,
    fetchClasses,
    requestEnrollment,
    approveEnrollment,
    rejectEnrollment,
    withdrawEnrollment,
    deleteEnrollment,
    bulkApproveEnrollments,
    bulkRejectEnrollments,
  } = useEnrollmentStore();

  const [showRequest, setShowRequest] = useState(false);
  const [rejectTarget, setRejectTarget] = useState<Enrollment | null>(null);
  const [rejectReason, setRejectReason] = useState('');
  const [deleteTarget, setDeleteTarget] = useState<Enrollment | null>(null);

  // Mass Approval state
  const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());
  const [showBulkRejectModal, setShowBulkRejectModal] = useState(false);
  const [bulkRejectReason, setBulkRejectReason] = useState('');
  const [search, setSearch] = useState('');
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  useEffect(() => {
    fetchMyEnrollments();
    fetchClasses();
    if (isStaff) {
      fetchPending();
    }
  }, [fetchMyEnrollments, fetchPending, fetchClasses, isStaff]);

  // Filtered pending approvals
  const filteredPending = useMemo(() => {
    if (!search.trim()) return pendingApprovals;
    const s = search.toLowerCase();
    return pendingApprovals.filter(
      (r) =>
        `${r.student_first_name || ''} ${r.student_last_name || ''}`.toLowerCase().includes(s) ||
        (r.student_email || '').toLowerCase().includes(s) ||
        (r.class_name || '').toLowerCase().includes(s) ||
        (r.class_section || '').toLowerCase().includes(s)
    );
  }, [pendingApprovals, search]);

  // Filtered all enrollments
  const filteredAll = useMemo(() => {
    if (!search.trim()) return myEnrollments;
    const s = search.toLowerCase();
    return myEnrollments.filter(
      (r) =>
        (r.class_name || '').toLowerCase().includes(s) ||
        (r.section || '').toLowerCase().includes(s) ||
        (r.academic_year || '').toLowerCase().includes(s) ||
        (r.roll_number || '').toLowerCase().includes(s) ||
        (r.status || '').toLowerCase().includes(s) ||
        (r.request_status || '').toLowerCase().includes(s)
    );
  }, [myEnrollments, search]);

  // Multi-select handlers
  const toggleSelectAll = () => {
    if (selectedIds.size === filteredPending.length && filteredPending.length > 0) {
      setSelectedIds(new Set());
    } else {
      setSelectedIds(new Set(filteredPending.map((r) => r.id)));
    }
  };

  const toggleSelect = (id: number) => {
    const next = new Set(selectedIds);
    if (next.has(id)) {
      next.delete(id);
    } else {
      next.add(id);
    }
    setSelectedIds(next);
  };

  const handleMassApprove = async () => {
    if (selectedIds.size === 0) return;
    try {
      const idsArray = Array.from(selectedIds);
      const count = await bulkApproveEnrollments(idsArray);
      setSuccessMessage(`Successfully mass approved ${count} enrollment request(s).`);
      setSelectedIds(new Set());
      setTimeout(() => setSuccessMessage(null), 5000);
    } catch (e) {
      // error in store
    }
  };

  const handleMassReject = async () => {
    if (selectedIds.size === 0) return;
    try {
      const idsArray = Array.from(selectedIds);
      const count = await bulkRejectEnrollments(idsArray, bulkRejectReason || undefined);
      setSuccessMessage(`Successfully rejected ${count} enrollment request(s).`);
      setSelectedIds(new Set());
      setShowBulkRejectModal(false);
      setBulkRejectReason('');
      setTimeout(() => setSuccessMessage(null), 5000);
    } catch (e) {
      // error in store
    }
  };

  const handleRequest = async (classId: number) => {
    try {
      await requestEnrollment(classId);
      setShowRequest(false);
      setSuccessMessage('Enrollment request submitted successfully.');
      setTimeout(() => setSuccessMessage(null), 5000);
    } catch (e) {
      // error in store
    }
  };

  const handleApprove = async (id: number) => {
    try {
      await approveEnrollment(id);
      setSuccessMessage('Enrollment approved.');
      setTimeout(() => setSuccessMessage(null), 4000);
    } catch (e) {
      // error in store
    }
  };

  const handleReject = async () => {
    if (!rejectTarget) return;
    try {
      await rejectEnrollment(rejectTarget.id, rejectReason || undefined);
      setRejectTarget(null);
      setRejectReason('');
      setSuccessMessage('Enrollment request rejected.');
      setTimeout(() => setSuccessMessage(null), 4000);
    } catch (e) {
      // error in store
    }
  };

  const handleWithdraw = async (id: number) => {
    if (!confirm('Withdraw this enrollment? You can re-request it later.')) return;
    try {
      await withdrawEnrollment(id);
      setSuccessMessage('Enrollment withdrawn.');
      setTimeout(() => setSuccessMessage(null), 4000);
    } catch (e) {
      // error in store
    }
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      await deleteEnrollment(deleteTarget.id);
      setDeleteTarget(null);
      setSuccessMessage('Enrollment record removed.');
      setTimeout(() => setSuccessMessage(null), 4000);
    } catch (e) {
      // error in store
    }
  };

  return (
    <div className="space-y-8 animate-in fade-in duration-700 pb-10">
      {/* Header */}
      <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-6">
        <div>
          <h1 className="text-3xl font-black text-text tracking-tight uppercase">
            Class Enrollments
          </h1>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>{isStaff ? 'Administration' : 'Student Portal'}</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">
              {isStaff ? 'Approval Queue & Management' : 'My Classes'}
            </span>
          </nav>
        </div>

        <div className="flex items-center gap-3 w-full md:w-auto">
          {/* Search filter */}
          <div className="relative flex-1 md:w-64">
            <Search size={14} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" />
            <input
              type="text"
              placeholder="Search student or class..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full pl-9 pr-3 py-2.5 bg-card border border-border rounded-2xl text-xs font-medium text-text focus:outline-none focus:ring-2 focus:ring-primary/20 shadow-sm"
            />
          </div>

          {!isStaff && (
            <button
              onClick={() => setShowRequest(true)}
              className="flex items-center gap-2 px-6 py-3 bg-primary text-white rounded-2xl font-black text-[0.7rem] uppercase tracking-widest hover:bg-primary/90 transition-all shadow-lg shadow-blue-900/10 active:scale-95 shrink-0 cursor-pointer"
            >
              <Plus size={18} /> Request Enrollment
            </button>
          )}
        </div>
      </div>

      {/* Success Notification */}
      {successMessage && (
        <div className="bg-emerald-50 dark:bg-emerald-950/30 border border-emerald-200 dark:border-emerald-900/40 rounded-2xl p-4 flex items-center justify-between gap-4 animate-in slide-in-from-top-2 duration-300">
          <div className="flex items-center gap-3 text-emerald-700 dark:text-emerald-400 font-bold text-xs">
            <CheckCircle2 size={18} className="shrink-0" />
            <span>{successMessage}</span>
          </div>
          <button
            onClick={() => setSuccessMessage(null)}
            className="text-emerald-700 dark:text-emerald-400 hover:opacity-75"
          >
            <X size={16} />
          </button>
        </div>
      )}

      {/* Error Notification */}
      {error && (
        <div className="bg-rose-50 dark:bg-rose-950/30 border border-rose-200 dark:border-rose-900/40 rounded-2xl p-4 flex items-center gap-4">
          <XCircle className="text-rose-600 dark:text-rose-400 shrink-0" size={20} />
          <span className="text-rose-700 dark:text-rose-300 font-bold text-xs">{error}</span>
        </div>
      )}

      {/* Staff: pending approvals */}
      {isStaff && (
        <section className="bg-card border border-border rounded-[2rem] overflow-hidden shadow-sm">
          {/* Header & Mass Action Toolbar */}
          <div className="p-5 bg-muted/30 border-b border-border flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-amber-50 dark:bg-amber-950/30 rounded-xl text-amber-600 border border-amber-200 dark:border-amber-900/40">
                <Clock size={18} />
              </div>
              <div>
                <h2 className="text-sm font-black uppercase tracking-widest text-text">
                  Pending Approvals
                </h2>
                <p className="text-[0.65rem] font-bold text-text-muted mt-0.5">
                  {pendingApprovals.length} pending request{pendingApprovals.length === 1 ? '' : 's'} waiting for review
                </p>
              </div>
            </div>

            {/* Mass action buttons when rows selected */}
            {selectedIds.size > 0 ? (
              <div className="flex flex-wrap items-center gap-2 animate-in fade-in duration-200 w-full sm:w-auto">
                <span className="text-xs font-bold text-primary mr-1">
                  {selectedIds.size} selected
                </span>
                <button
                  onClick={handleMassApprove}
                  disabled={isSubmitting}
                  className="flex items-center gap-1.5 px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl text-xs font-black uppercase tracking-widest transition-all shadow-md active:scale-95 disabled:opacity-50 cursor-pointer"
                >
                  <CheckCheck size={16} /> Approve Selected ({selectedIds.size})
                </button>
                <button
                  onClick={() => setShowBulkRejectModal(true)}
                  disabled={isSubmitting}
                  className="flex items-center gap-1.5 px-4 py-2 bg-rose-50 dark:bg-rose-950/40 hover:bg-rose-100 text-rose-600 border border-rose-200 dark:border-rose-900/40 rounded-xl text-xs font-black uppercase tracking-widest transition-all active:scale-95 disabled:opacity-50 cursor-pointer"
                >
                  <XCircle size={16} /> Reject Selected ({selectedIds.size})
                </button>
                <button
                  onClick={() => setSelectedIds(new Set())}
                  className="p-2 text-text-muted hover:text-text rounded-lg transition-colors text-xs font-medium"
                  title="Clear Selection"
                >
                  Clear
                </button>
              </div>
            ) : (
              <div className="flex items-center gap-2">
                <button
                  onClick={() => fetchPending()}
                  disabled={isLoading}
                  className="p-2 text-text-muted hover:text-primary rounded-xl hover:bg-muted/50 transition-colors"
                  title="Refresh Queue"
                >
                  <RefreshCw size={16} className={isLoading ? 'animate-spin' : ''} />
                </button>
              </div>
            )}
          </div>

          {isLoading ? (
            <div className="flex justify-center py-12">
              <div className="w-8 h-8 border-4 border-primary border-t-transparent rounded-full animate-spin" />
            </div>
          ) : filteredPending.length === 0 ? (
            <div className="text-center py-12 opacity-60">
              <CheckCircle2 size={40} className="mx-auto text-emerald-500 mb-3" />
              <p className="font-black uppercase tracking-widest text-[0.7rem] text-text-muted">
                {search ? 'No matching pending requests' : 'No pending requests — you\'re all caught up'}
              </p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-left border-collapse">
                <thead>
                  <tr className="bg-muted/50 border-b border-border">
                    <th className="px-4 py-3 w-12 text-center">
                      <input
                        type="checkbox"
                        checked={selectedIds.size === filteredPending.length && filteredPending.length > 0}
                        onChange={toggleSelectAll}
                        className="w-4 h-4 rounded border-border text-primary focus:ring-primary/20 cursor-pointer"
                      />
                    </th>
                    <th className="px-6 py-3 text-[0.6rem] font-black text-primary uppercase tracking-widest">
                      Student
                    </th>
                    <th className="px-6 py-3 text-[0.6rem] font-black text-primary uppercase tracking-widest">
                      Requested Class
                    </th>
                    <th className="px-6 py-3 text-[0.6rem] font-black text-primary uppercase tracking-widest">
                      Date Requested
                    </th>
                    <th className="px-6 py-3 text-[0.6rem] font-black text-primary uppercase tracking-widest text-right">
                      Actions
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {filteredPending.map((row) => {
                    const isChecked = selectedIds.has(row.id);
                    return (
                      <tr key={row.id} className={`hover:bg-muted/30 transition-colors ${isChecked ? 'bg-primary/5' : ''}`}>
                        <td className="px-4 py-3 text-center">
                          <input
                            type="checkbox"
                            checked={isChecked}
                            onChange={() => toggleSelect(row.id)}
                            className="w-4 h-4 rounded border-border text-primary focus:ring-primary/20 cursor-pointer"
                          />
                        </td>
                        <td className="px-6 py-3">
                          <p className="text-sm font-bold text-text">
                            {row.student_first_name} {row.student_last_name}
                          </p>
                          <p className="text-[0.65rem] text-text-muted">
                            {row.student_email}
                          </p>
                        </td>
                        <td className="px-6 py-3 text-sm text-text-secondary font-medium">
                          {row.class_name}
                          {row.class_section && (
                            <span className="text-[0.65rem] text-text-muted ml-1.5 font-normal">
                              [{row.class_section}]
                            </span>
                          )}
                        </td>
                        <td className="px-6 py-3 text-[0.7rem] text-text-muted font-medium">
                          {row.requested_at
                            ? new Date(row.requested_at).toLocaleDateString(undefined, { dateStyle: 'medium' })
                            : '—'}
                        </td>
                        <td className="px-6 py-3 text-right">
                          <div className="inline-flex gap-2">
                            <button
                              onClick={() => handleApprove(row.id)}
                              disabled={isSubmitting}
                              className="flex items-center gap-1.5 px-3 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-[0.6rem] font-black uppercase tracking-widest transition-all active:scale-95 disabled:opacity-50 cursor-pointer"
                            >
                              <CheckCircle2 size={13} /> Approve
                            </button>
                            <button
                              onClick={() => setRejectTarget(row)}
                              disabled={isSubmitting}
                              className="flex items-center gap-1.5 px-3 py-1.5 bg-rose-50 dark:bg-rose-950/40 hover:bg-rose-100 text-rose-600 border border-rose-200 dark:border-rose-900/40 rounded-lg text-[0.6rem] font-black uppercase tracking-widest transition-all active:scale-95 disabled:opacity-50 cursor-pointer"
                            >
                              <XCircle size={13} /> Reject
                            </button>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </section>
      )}

      {/* All enrollments (both roles) */}
      <section className="bg-card border border-border rounded-[2rem] overflow-hidden shadow-sm">
        <div className="p-5 bg-muted/30 border-b border-border flex items-center justify-between">
          <h2 className="text-sm font-black uppercase tracking-widest text-primary flex items-center gap-2">
            <BookOpen size={16} /> {isStaff ? 'All Academic Enrollments' : 'My Enrollments'}
          </h2>
          <span className="text-[0.65rem] font-black text-text-muted">
            {filteredAll.length} record{filteredAll.length === 1 ? '' : 's'}
          </span>
        </div>
        {filteredAll.length === 0 ? (
          <div className="text-center py-16 opacity-50 space-y-3">
            <UsersIcon size={42} className="mx-auto text-text-muted/30" />
            <p className="font-black uppercase tracking-widest text-[0.65rem] text-text-muted">
              {isStaff
                ? search ? 'No enrollments match your search' : 'No enrollments on record'
                : 'You have no enrollments yet — request one above!'}
            </p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="bg-muted/50 border-b border-border">
                  <th className="px-6 py-3 text-[0.6rem] font-black text-primary uppercase tracking-widest">
                    Class & Section
                  </th>
                  <th className="px-6 py-3 text-[0.6rem] font-black text-primary uppercase tracking-widest">
                    Academic Year
                  </th>
                  <th className="px-6 py-3 text-[0.6rem] font-black text-primary uppercase tracking-widest">
                    Status
                  </th>
                  <th className="px-6 py-3 text-[0.6rem] font-black text-primary uppercase tracking-widest">
                    Request Status
                  </th>
                  <th className="px-6 py-3 text-[0.6rem] font-black text-primary uppercase tracking-widest text-right">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {filteredAll.map((row) => (
                  <tr key={row.id} className="hover:bg-muted/30 transition-colors">
                    <td className="px-6 py-3">
                      <p className="text-sm font-bold text-text">
                        {row.class_name || `Class #${row.class_id}`}
                      </p>
                      {row.section && (
                        <p className="text-[0.65rem] text-text-muted mt-0.5">
                          Section {row.section}
                          {row.roll_number && ` · Roll ${row.roll_number}`}
                        </p>
                      )}
                    </td>
                    <td className="px-6 py-3 text-xs text-text-secondary font-semibold">
                      {row.academic_year || 'Current Term'}
                    </td>
                    <td className="px-6 py-3">
                      <span
                        className={`inline-block px-2.5 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-widest border ${statusBadge(row.status)}`}
                      >
                        {row.status}
                      </span>
                    </td>
                    <td className="px-6 py-3">
                      <span
                        className={`inline-block px-2.5 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-widest border ${statusBadge(row.request_status)}`}
                      >
                        {row.request_status || '—'}
                      </span>
                      {row.rejection_reason && (
                        <p className="text-[0.65rem] text-rose-600 dark:text-rose-400 mt-1 italic font-medium">
                          “{row.rejection_reason}”
                        </p>
                      )}
                    </td>
                    <td className="px-6 py-3 text-right">
                      <div className="inline-flex gap-2 justify-end">
                        {/* If staff and status is pending, show quick approve/reject */}
                        {isStaff && row.request_status === 'pending' && (
                          <>
                            <button
                              onClick={() => handleApprove(row.id)}
                              disabled={isSubmitting}
                              className="px-2.5 py-1 bg-emerald-600 text-white rounded-lg text-[0.6rem] font-black uppercase tracking-widest hover:bg-emerald-700 transition-all cursor-pointer"
                            >
                              Approve
                            </button>
                            <button
                              onClick={() => setRejectTarget(row)}
                              disabled={isSubmitting}
                              className="px-2.5 py-1 bg-rose-50 dark:bg-rose-950/40 text-rose-600 border border-rose-200 dark:border-rose-900/40 rounded-lg text-[0.6rem] font-black uppercase tracking-widest hover:bg-rose-100 transition-all cursor-pointer"
                            >
                              Reject
                            </button>
                          </>
                        )}
                        {/* Student withdraw option */}
                        {!isStaff && row.request_status !== 'withdrawn' && (
                          <button
                            onClick={() => handleWithdraw(row.id)}
                            disabled={isSubmitting}
                            className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-card border border-border text-text-muted hover:text-rose-500 hover:border-rose-200 rounded-lg text-[0.6rem] font-black uppercase tracking-widest transition-all disabled:opacity-50 cursor-pointer"
                          >
                            <Trash2 size={12} /> Withdraw
                          </button>
                        )}
                        {/* Staff delete row */}
                        {isStaff && (
                          <button
                            onClick={() => setDeleteTarget(row)}
                            disabled={isSubmitting}
                            className="p-1.5 text-text-muted hover:text-rose-500 rounded-lg transition-colors cursor-pointer"
                            title="Delete Record"
                          >
                            <Trash2 size={14} />
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>

      {/* Request modal (student only) */}
      {showRequest && (
        <RequestClassModal
          classes={classes}
          myEnrollments={myEnrollments}
          onClose={() => setShowRequest(false)}
          onSubmit={handleRequest}
          isSubmitting={isSubmitting}
        />
      )}

      {/* Single Reject modal */}
      {rejectTarget && createPortal(
        <div className="fixed inset-0 bg-[#002147]/80 backdrop-blur-md z-[200] flex items-center justify-center p-4" onClick={() => setRejectTarget(null)}>
          <div className="bg-card border border-border rounded-[2rem] w-full max-w-md shadow-2xl" onClick={(e) => e.stopPropagation()}>
            <div className="px-6 py-5 bg-muted/50 border-b border-border flex items-center justify-between">
              <h2 className="text-base font-black text-text uppercase tracking-tight">
                Reject Enrollment
              </h2>
              <button
                onClick={() => setRejectTarget(null)}
                className="w-8 h-8 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 cursor-pointer"
              >
                <X size={16} />
              </button>
            </div>
            <div className="p-6 space-y-4">
              <div className="bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-900/40 rounded-2xl p-4 flex items-start gap-3">
                <AlertTriangle className="text-amber-600 dark:text-amber-400 shrink-0" size={18} />
                <p className="text-[0.7rem] text-amber-700 dark:text-amber-300 font-bold">
                  Rejecting request for{' '}
                  <span className="font-black">
                    {rejectTarget.student_first_name
                      ? `${rejectTarget.student_first_name} ${rejectTarget.student_last_name}`
                      : rejectTarget.class_name}
                  </span>.
                </p>
              </div>
              <div>
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1 mb-1.5 block">
                  Reason (optional, visible to student)
                </label>
                <textarea
                  rows={3}
                  className="w-full p-3 bg-muted border border-border rounded-xl text-xs font-medium text-text focus:outline-none focus:ring-2 focus:ring-primary/20"
                  value={rejectReason}
                  onChange={(e) => setRejectReason(e.target.value)}
                  placeholder="e.g., Class capacity reached for this term"
                />
              </div>
              <div className="flex justify-end gap-3 pt-2">
                <button
                  onClick={() => setRejectTarget(null)}
                  className="px-5 py-2.5 bg-card border border-border text-text-muted rounded-xl font-black text-[0.65rem] uppercase tracking-widest hover:bg-muted cursor-pointer"
                >
                  Cancel
                </button>
                <button
                  onClick={handleReject}
                  disabled={isSubmitting}
                  className="px-5 py-2.5 bg-rose-600 hover:bg-rose-700 text-white rounded-xl font-black text-[0.65rem] uppercase tracking-widest shadow-lg active:scale-95 disabled:opacity-50 cursor-pointer"
                >
                  Confirm Reject
                </button>
              </div>
            </div>
          </div>
        </div>,
        document.body
      )}

      {/* Bulk Reject modal */}
      {showBulkRejectModal && createPortal(
        <div className="fixed inset-0 bg-[#002147]/80 backdrop-blur-md z-[200] flex items-center justify-center p-4" onClick={() => setShowBulkRejectModal(false)}>
          <div className="bg-card border border-border rounded-[2rem] w-full max-w-md shadow-2xl" onClick={(e) => e.stopPropagation()}>
            <div className="px-6 py-5 bg-muted/50 border-b border-border flex items-center justify-between">
              <h2 className="text-base font-black text-text uppercase tracking-tight">
                Mass Reject ({selectedIds.size} Requests)
              </h2>
              <button
                onClick={() => setShowBulkRejectModal(false)}
                className="w-8 h-8 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 cursor-pointer"
              >
                <X size={16} />
              </button>
            </div>
            <div className="p-6 space-y-4">
              <div className="bg-rose-50 dark:bg-rose-950/30 border border-rose-200 dark:border-rose-900/40 rounded-2xl p-4 flex items-start gap-3">
                <AlertTriangle className="text-rose-600 dark:text-rose-400 shrink-0" size={18} />
                <p className="text-[0.7rem] text-rose-700 dark:text-rose-300 font-bold">
                  You are about to mass reject <span className="font-black">{selectedIds.size} selected enrollment requests</span>.
                </p>
              </div>
              <div>
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1 mb-1.5 block">
                  Rejection Reason (Applied to all selected)
                </label>
                <textarea
                  rows={3}
                  className="w-full p-3 bg-muted border border-border rounded-xl text-xs font-medium text-text focus:outline-none focus:ring-2 focus:ring-primary/20"
                  value={bulkRejectReason}
                  onChange={(e) => setBulkRejectReason(e.target.value)}
                  placeholder="e.g., Enrollment deadline expired"
                />
              </div>
              <div className="flex justify-end gap-3 pt-2">
                <button
                  onClick={() => setShowBulkRejectModal(false)}
                  className="px-5 py-2.5 bg-card border border-border text-text-muted rounded-xl font-black text-[0.65rem] uppercase tracking-widest hover:bg-muted cursor-pointer"
                >
                  Cancel
                </button>
                <button
                  onClick={handleMassReject}
                  disabled={isSubmitting}
                  className="px-5 py-2.5 bg-rose-600 hover:bg-rose-700 text-white rounded-xl font-black text-[0.65rem] uppercase tracking-widest shadow-lg active:scale-95 disabled:opacity-50 cursor-pointer"
                >
                  Confirm Mass Reject
                </button>
              </div>
            </div>
          </div>
        </div>,
        document.body
      )}

      {/* Delete Record Confirmation modal */}
      {deleteTarget && createPortal(
        <div className="fixed inset-0 bg-[#002147]/80 backdrop-blur-md z-[200] flex items-center justify-center p-4" onClick={() => setDeleteTarget(null)}>
          <div className="bg-card border border-border rounded-[2rem] w-full max-w-md shadow-2xl" onClick={(e) => e.stopPropagation()}>
            <div className="px-6 py-5 bg-muted/50 border-b border-border flex items-center justify-between">
              <h2 className="text-base font-black text-text uppercase tracking-tight">
                Delete Enrollment Record
              </h2>
              <button
                onClick={() => setDeleteTarget(null)}
                className="w-8 h-8 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 cursor-pointer"
              >
                <X size={16} />
              </button>
            </div>
            <div className="p-6 space-y-4">
              <p className="text-xs text-text-secondary font-medium leading-relaxed">
                Are you sure you want to delete enrollment record <span className="font-bold text-text">#{deleteTarget.id}</span> ({deleteTarget.class_name || 'Class'})?
              </p>
              <div className="flex justify-end gap-3 pt-2">
                <button
                  onClick={() => setDeleteTarget(null)}
                  className="px-5 py-2.5 bg-card border border-border text-text-muted rounded-xl font-black text-[0.65rem] uppercase tracking-widest hover:bg-muted cursor-pointer"
                >
                  Cancel
                </button>
                <button
                  onClick={handleDelete}
                  disabled={isSubmitting}
                  className="px-5 py-2.5 bg-rose-600 hover:bg-rose-700 text-white rounded-xl font-black text-[0.65rem] uppercase tracking-widest shadow-lg active:scale-95 disabled:opacity-50 cursor-pointer"
                >
                  Confirm Delete
                </button>
              </div>
            </div>
          </div>
        </div>,
        document.body
      )}
    </div>
  );
}

// ---------- request modal ----------

function RequestClassModal({
  classes,
  myEnrollments,
  onClose,
  onSubmit,
  isSubmitting,
}: {
  classes: any[];
  myEnrollments: Enrollment[];
  onClose: () => void;
  onSubmit: (classId: number) => Promise<void>;
  isSubmitting: boolean;
}) {
  const enrolledClassIds = useMemo(
    () => new Set(myEnrollments.filter((e) => e.request_status !== 'withdrawn' && e.request_status !== 'rejected').map((e) => e.class_id)),
    [myEnrollments],
  );

  return createPortal(
    <div className="fixed inset-0 bg-[#002147]/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4" onClick={onClose}>
      <div className="bg-card border border-border rounded-[2rem] w-full max-w-lg max-h-[90vh] overflow-hidden flex flex-col shadow-2xl" onClick={(e) => e.stopPropagation()}>
        <div className="px-6 py-5 bg-muted/50 border-b border-border flex items-center justify-between shrink-0">
          <h2 className="text-base font-black text-text uppercase tracking-tight">
            Request Class Enrollment
          </h2>
          <button
            onClick={onClose}
            className="w-8 h-8 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 cursor-pointer"
          >
            <X size={16} />
          </button>
        </div>
        <div className="p-6 overflow-y-auto flex-1">
          <p className="text-[0.7rem] text-text-muted mb-4">
            Pick a class to request. Your request will be reviewed by an admin or
            teacher before it’s approved.
          </p>
          {classes.length === 0 ? (
            <p className="text-center py-10 text-text-muted text-sm">
              No classes available right now.
            </p>
          ) : (
            <div className="space-y-2">
              {classes.map((c: any) => {
                const alreadyEnrolled = enrolledClassIds.has(c.id);
                return (
                  <button
                    key={c.id}
                    disabled={alreadyEnrolled || isSubmitting}
                    onClick={() => onSubmit(c.id)}
                    className="w-full flex items-center justify-between gap-4 p-4 bg-muted/30 border border-border rounded-2xl hover:border-primary hover:bg-primary/5 transition-all disabled:opacity-50 disabled:cursor-not-allowed text-left cursor-pointer"
                  >
                    <div className="min-w-0">
                      <p className="text-sm font-bold text-text truncate">
                        {c.name}
                        {c.section && (
                          <span className="text-[0.65rem] text-text-muted ml-1.5">
                            [{c.section}]
                          </span>
                        )}
                      </p>
                      <p className="text-[0.65rem] text-text-muted truncate">
                        {c.academic_year || ''}
                        {c.grade_level && ` · Grade ${c.grade_level}`}
                      </p>
                    </div>
                    <span className="shrink-0 text-[0.6rem] font-black uppercase tracking-widest text-primary">
                      {alreadyEnrolled ? 'Already Enrolled' : 'Request →'}
                    </span>
                  </button>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>,
    document.body
  );
}

export default EnrollmentsPage;
