"use client";

import React, { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import {
  Search,
  RotateCcw,
  Plus,
  Eye,
  Edit2,
  Trash2,
  ChevronLeft,
  ChevronRight,
  FileSpreadsheet,
  Upload,
  Users,
  Mail,
  Phone,
  Sparkles,
  X,
  RefreshCw,
  Loader2,
  AlertCircle,
  GraduationCap,
} from "lucide-react";
import { toast } from "sonner";
import { apiClient } from "@/lib/api-client";

interface StudentDbItem {
  id: string;
  userId: string;
  nchmctRollNo: string;
  regNo?: string | null;
  admissionYear: number;
  gender?: string | null;
  status: "ACTIVE" | "INACTIVE" | "SUSPENDED" | "DETAINED";
  user: {
    id: string;
    email: string;
    fullName: string;
    phone?: string | null;
    status: string;
  };
  course?: {
    id: string;
    code: string;
    name: string;
  } | null;
  semester?: {
    id: string;
    name: string;
    semesterNumber: number;
  } | null;
  studentGroup?: {
    id: string;
    name: string;
  } | null;
  _count?: {
    enrollments?: number;
    attendanceRecords?: number;
  };
}

interface SemesterOption {
  id: string;
  name: string;
  semesterNumber: number;
}

export default function StudentsDirectoryPage() {
  const [students, setStudents] = useState<StudentDbItem[]>([]);
  const [semestersList, setSemestersList] = useState<SemesterOption[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isError, setIsError] = useState(false);
  const [totalStudents, setTotalStudents] = useState(0);

  // Filters & Search
  const [selectedSemester, setSelectedSemester] = useState("All Semesters");
  const [selectedBatch, setSelectedBatch] = useState("All Batches");
  const [selectedStatus, setSelectedStatus] = useState("All Status");
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedRows, setSelectedRows] = useState<string[]>([]);
  const [pageSize, setPageSize] = useState("10");
  const [currentPage, setCurrentPage] = useState(1);

  // Modals & Actions
  const [isImportModalOpen, setIsImportModalOpen] = useState(false);
  const [viewingStudent, setViewingStudent] = useState<StudentDbItem | null>(null);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [isUploading, setIsUploading] = useState(false);

  // 1. Fetch Students from DB
  const fetchStudents = useCallback(async (isManualRefresh = false) => {
    try {
      if (isManualRefresh) setIsRefreshing(true);
      else setIsLoading(true);
      setIsError(false);

      const params: Record<string, string | number> = {
        page: currentPage,
        limit: parseInt(pageSize, 10),
      };

      if (searchQuery.trim()) {
        params.search = searchQuery.trim();
      }

      if (selectedStatus !== "All Status") {
        params.status = selectedStatus;
      }

      const res = await apiClient.get<{
        success: boolean;
        data: StudentDbItem[];
        meta?: { total: number; page: number; limit: number; totalPages: number };
      }>("/students", { params });

      if (res.data?.success && Array.isArray(res.data.data)) {
        setStudents(res.data.data);
        setTotalStudents(res.data.meta?.total ?? res.data.data.length);
        if (isManualRefresh) {
          toast.success("Student directory refreshed from database!");
        }
      }
    } catch (err) {
      console.error("Failed to load students:", err);
      setIsError(true);
      toast.error("Failed to fetch students from database.");
    } finally {
      setIsLoading(false);
      setIsRefreshing(false);
    }
  }, [currentPage, pageSize, searchQuery, selectedStatus]);

  // 2. Fetch Semester options from DB
  const fetchSemesters = useCallback(async () => {
    try {
      const res = await apiClient.get<{
        success: boolean;
        data: SemesterOption[];
      }>("/courses/semesters");
      if (res.data?.success && Array.isArray(res.data.data)) {
        setSemestersList(res.data.data);
      }
    } catch {
      // Non-critical: semester filter will fallback to client-extracted options
    }
  }, []);

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

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

  // Dynamic distinct batches derived from current database students
  const availableBatches = Array.from(
    new Set(
      students
        .map((s) => s.studentGroup?.name)
        .filter((b): b is string => Boolean(b))
    )
  );

  // Client-side filtering for semester and batch
  const filteredStudents = students.filter((s) => {
    const matchesSem =
      selectedSemester === "All Semesters" ||
      s.semester?.name === selectedSemester ||
      s.semester?.id === selectedSemester;
    const matchesBatch =
      selectedBatch === "All Batches" ||
      s.studentGroup?.name === selectedBatch;
    return matchesSem && matchesBatch;
  });

  const handleSelectAll = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.checked) {
      setSelectedRows(filteredStudents.map((s) => s.id));
    } else {
      setSelectedRows([]);
    }
  };

  const handleRowSelect = (id: string) => {
    setSelectedRows((prev) =>
      prev.includes(id) ? prev.filter((r) => r !== id) : [...prev, id]
    );
  };

  const handleResetFilters = () => {
    setSelectedSemester("All Semesters");
    setSelectedBatch("All Batches");
    setSelectedStatus("All Status");
    setSearchQuery("");
    setCurrentPage(1);
    toast.info("Filters reset to default");
  };

  // Delete student directly from database
  const handleDeleteStudent = async (id: string, name: string) => {
    if (!confirm(`Are you sure you want to remove student "${name}" from the database?`)) {
      return;
    }
    try {
      setDeletingId(id);
      await apiClient.delete(`/students/${id}`);
      toast.success(`Student "${name}" deleted from database.`);
      fetchStudents(true);
    } catch (err: unknown) {
      console.error("Delete failed:", err);
      toast.error("Failed to delete student from database.");
    } finally {
      setDeletingId(null);
    }
  };

  // Export visible students to CSV
  const handleExportCSV = () => {
    if (filteredStudents.length === 0) {
      toast.error("No student records available to export.");
      return;
    }
    const headers = [
      "NCHM Roll No",
      "Full Name",
      "Gender",
      "Course",
      "Semester",
      "Batch Group",
      "Email",
      "Mobile",
      "Status",
    ];
    const rows = filteredStudents.map((s) => [
      `"${s.nchmctRollNo}"`,
      `"${s.user?.fullName || ""}"`,
      `"${s.gender || ""}"`,
      `"${s.course?.name || s.course?.code || ""}"`,
      `"${s.semester?.name || ""}"`,
      `"${s.studentGroup?.name || "General"}"`,
      `"${s.user?.email || ""}"`,
      `"${s.user?.phone || ""}"`,
      `"${s.status}"`,
    ]);

    const csvContent =
      "data:text/csv;charset=utf-8," +
      [headers.join(","), ...rows.map((e) => e.join(","))].join("\n");

    const encodedUri = encodeURI(csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", `ihm_students_roster_${new Date().toISOString().slice(0, 10)}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    toast.success("Student directory exported to CSV!");
  };

  // Handle Excel File Upload
  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const formData = new FormData();
    formData.append("file", file);

    try {
      setIsUploading(true);
      const res = await apiClient.post<{
        success: boolean;
        data?: {
          validRows?: Array<{
            nchmctRollNo: string;
            fullName: string;
            email: string;
            phone?: string;
            gender?: string;
            courseId: string;
            semesterId: string;
            studentGroupId?: string;
            admissionYear: number;
          }>;
        };
        message: string;
      }>("/students/import/preview", formData, {
        headers: { "Content-Type": "multipart/form-data" },
      });

      if (res.data?.success && res.data.data?.validRows && res.data.data.validRows.length > 0) {
        // Commit valid rows
        const commitRes = await apiClient.post<{ success: boolean; message: string }>(
          "/students/import/commit",
          { students: res.data.data.validRows }
        );
        toast.success(commitRes.data?.message || "Students roster successfully imported!");
        setIsImportModalOpen(false);
        fetchStudents(true);
      } else {
        toast.info("File validated but no valid new student rows detected.");
      }
    } catch (err: unknown) {
      console.error("Import failed:", err);
      toast.error("Failed to parse and import Excel file. Check file format.");
    } finally {
      setIsUploading(false);
    }
  };

  return (
    <div className="space-y-6 pb-12 font-sans bg-[#F8FAFC] min-h-screen">
      {/* 1. Header Bar */}
      <div>
        <nav className="flex items-center gap-1.5 text-[13px] text-[#64748B] mb-2 font-medium">
          <Link href="/admin/dashboard" className="hover:text-[#1769E8] hover:underline">
            Home
          </Link>
          <ChevronRight className="w-3.5 h-3.5 text-[#94A3B8]" />
          <Link href="/admin/people/students" className="hover:text-[#1769E8] hover:underline">
            Student Management
          </Link>
          <ChevronRight className="w-3.5 h-3.5 text-[#94A3B8]" />
          <span className="text-[#071A4D] font-semibold">All Students</span>
        </nav>

        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div>
            <h1 className="text-3xl font-bold font-heading text-[#071A4D] tracking-tight">
              All Students
            </h1>
            <p className="text-[15px] text-[#64748B] mt-1 font-normal">
              Manage student registrations, NCHM roll numbers, semester enrolments, and practical batch groups.
            </p>
          </div>

          <div className="flex items-center gap-2.5 shrink-0 flex-wrap">
            <button
              onClick={() => fetchStudents(true)}
              disabled={isRefreshing}
              className="h-10 w-10 inline-flex items-center justify-center shrink-0 bg-white border border-[#E2E8F0] rounded-lg text-[#334155] hover:text-[#1769E8] hover:bg-slate-50 transition-colors shadow-xs cursor-pointer"
              title="Refresh student records live from database"
            >
              <RefreshCw className={`w-4 h-4 ${isRefreshing ? "animate-spin text-[#1769E8]" : ""}`} />
            </button>
            <button
              onClick={handleExportCSV}
              className="h-10 px-4 inline-flex items-center justify-center gap-2 bg-white border border-[#E2E8F0] rounded-lg text-sm font-semibold text-[#334155] hover:bg-slate-50 transition-colors shadow-xs cursor-pointer shrink-0 whitespace-nowrap"
            >
              <FileSpreadsheet className="w-4 h-4 text-emerald-600" />
              <span>Export CSV</span>
            </button>
            <button
              onClick={() => setIsImportModalOpen(true)}
              className="h-10 px-4 inline-flex items-center justify-center gap-2 bg-white border border-[#E2E8F0] rounded-lg text-sm font-semibold text-[#334155] hover:bg-slate-50 transition-colors shadow-xs cursor-pointer shrink-0 whitespace-nowrap"
            >
              <Upload className="w-4 h-4 text-[#1769E8]" />
              <span>Bulk Import</span>
            </button>
            <Link
              href="/admin/people/students/register"
              className="h-10 px-4 inline-flex items-center justify-center gap-2 bg-[#1769E8] hover:bg-[#1255be] text-white rounded-lg text-sm font-semibold shadow-sm transition-colors cursor-pointer shrink-0 whitespace-nowrap"
            >
              <Plus className="w-4 h-4" />
              <span>New Registration</span>
            </Link>
          </div>
        </div>
      </div>

      {/* 2. Filter Bar */}
      <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs p-4">
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-12 gap-3.5 items-end">
          {/* Semester Filter */}
          <div className="lg:col-span-3">
            <label className="block text-[11px] font-semibold text-[#64748B] uppercase tracking-wider mb-1.5">
              Academic Semester
            </label>
            <select
              value={selectedSemester}
              onChange={(e) => setSelectedSemester(e.target.value)}
              className="w-full h-10 bg-white border border-[#E2E8F0] text-sm text-[#0F172A] rounded-lg px-3 font-medium focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all cursor-pointer"
            >
              <option>All Semesters</option>
              {semestersList.length > 0 ? (
                semestersList.map((sem) => (
                  <option key={sem.id} value={sem.name}>
                    {sem.name}
                  </option>
                ))
              ) : (
                <>
                  <option>Semester I</option>
                  <option>Semester III</option>
                  <option>Semester V (2026-2027)</option>
                </>
              )}
            </select>
          </div>

          {/* Practical Batch Filter */}
          <div className="lg:col-span-2">
            <label className="block text-[11px] font-semibold text-[#64748B] uppercase tracking-wider mb-1.5">
              Practical Batch
            </label>
            <select
              value={selectedBatch}
              onChange={(e) => setSelectedBatch(e.target.value)}
              className="w-full h-10 bg-white border border-[#E2E8F0] text-sm text-[#0F172A] rounded-lg px-3 font-medium focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all cursor-pointer"
            >
              <option>All Batches</option>
              {availableBatches.length > 0 ? (
                availableBatches.map((batch) => (
                  <option key={batch} value={batch}>
                    {batch}
                  </option>
                ))
              ) : (
                <>
                  <option>Batch A</option>
                  <option>Batch B</option>
                </>
              )}
            </select>
          </div>

          {/* Status Filter */}
          <div className="lg:col-span-2">
            <label className="block text-[11px] font-semibold text-[#64748B] uppercase tracking-wider mb-1.5">
              Status
            </label>
            <select
              value={selectedStatus}
              onChange={(e) => setSelectedStatus(e.target.value)}
              className="w-full h-10 bg-white border border-[#E2E8F0] text-sm text-[#0F172A] rounded-lg px-3 font-medium focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all cursor-pointer"
            >
              <option>All Status</option>
              <option value="ACTIVE">Active</option>
              <option value="INACTIVE">Inactive</option>
              <option value="SUSPENDED">Suspended</option>
            </select>
          </div>

          {/* Search Query */}
          <div className="lg:col-span-3">
            <label className="block text-[11px] font-semibold text-[#64748B] uppercase tracking-wider mb-1.5">
              Search
            </label>
            <div className="relative">
              <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-[#94A3B8]" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && fetchStudents()}
                placeholder="Search name, NCHM roll, email..."
                className="w-full h-10 pl-9 pr-3 bg-white border border-[#E2E8F0] text-sm text-[#0F172A] placeholder:text-[#94A3B8] rounded-lg focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all"
              />
            </div>
          </div>

          {/* Filter Action Buttons */}
          <div className="lg:col-span-2 flex items-center gap-2">
            <button
              onClick={() => fetchStudents()}
              className="flex-1 h-10 bg-[#1769E8] hover:bg-[#1255be] text-white rounded-lg text-sm font-semibold transition-colors flex items-center justify-center gap-1.5 shadow-xs cursor-pointer whitespace-nowrap"
            >
              <Search className="w-4 h-4" />
              <span>Search</span>
            </button>
            <button
              onClick={handleResetFilters}
              className="h-10 w-10 border border-[#E2E8F0] hover:bg-slate-50 text-[#64748B] rounded-lg text-sm font-medium transition-colors flex items-center justify-center cursor-pointer shrink-0"
              title="Reset Filters"
            >
              <RotateCcw className="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>

      {/* 3. Error Banner */}
      {isError && (
        <div className="p-4 rounded-xl bg-rose-50 border border-rose-200 text-rose-800 flex items-center justify-between gap-4 text-xs">
          <div className="flex items-center gap-2">
            <AlertCircle className="w-4 h-4 text-rose-600 shrink-0" />
            <span>Could not load students from database. Please verify backend server is running on port 5000.</span>
          </div>
          <button
            onClick={() => fetchStudents(true)}
            className="px-3 py-1 bg-rose-600 text-white rounded-md font-semibold hover:bg-rose-700 transition-colors cursor-pointer"
          >
            Retry
          </button>
        </div>
      )}

      {/* 4. Students Table (Full Width) */}
      <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs overflow-hidden">
        <div className="p-4 border-b border-[#E5EAF0] flex items-center justify-between">
          <div className="flex items-center gap-2.5">
            <Users className="w-5 h-5 text-[#1769E8]" />
            <h2 className="font-heading font-bold text-lg text-[#071A4D]">
              Students Roster ({filteredStudents.length} of {totalStudents})
            </h2>
          </div>
          <div className="flex items-center gap-2">
            <select
              value={pageSize}
              onChange={(e) => {
                setPageSize(e.target.value);
                setCurrentPage(1);
              }}
              className="text-xs bg-white border border-[#E2E8F0] rounded-lg px-2.5 py-1.5 font-medium text-[#475569] outline-none cursor-pointer"
            >
              <option value="10">10 per page</option>
              <option value="25">25 per page</option>
              <option value="50">50 per page</option>
            </select>
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs border-collapse">
            <thead>
              <tr className="bg-[#F8FAFC] border-b border-[#E5EAF0] text-[#64748B] uppercase tracking-wider font-bold text-[11px]">
                <th className="py-3 px-3.5 w-10 text-center">
                  <input
                    type="checkbox"
                    checked={
                      selectedRows.length === filteredStudents.length &&
                      filteredStudents.length > 0
                    }
                    onChange={handleSelectAll}
                    className="rounded border-[#CBD5E1] text-[#1769E8] focus:ring-0 cursor-pointer"
                  />
                </th>
                <th className="py-3 px-2 w-8 text-center text-[#64748B]">#</th>
                <th className="py-3 px-3 font-bold text-[#071A4D] whitespace-nowrap">NCHM Roll No.</th>
                <th className="py-3 px-3 font-bold text-[#071A4D] whitespace-nowrap">Student Name</th>
                <th className="py-3 px-3 font-bold text-[#071A4D] whitespace-nowrap">Gender</th>
                <th className="py-3 px-3 font-bold text-[#071A4D] whitespace-nowrap">Course</th>
                <th className="py-3 px-3 font-bold text-[#071A4D] whitespace-nowrap">Semester</th>
                <th className="py-3 px-3 font-bold text-[#071A4D] whitespace-nowrap">Batch Group</th>
                <th className="py-3 px-3 font-bold text-[#071A4D] whitespace-nowrap">Email</th>
                <th className="py-3 px-3 font-bold text-[#071A4D] whitespace-nowrap">Mobile</th>
                <th className="py-3 px-3 font-bold text-[#071A4D] text-center whitespace-nowrap">Status</th>
                <th className="py-3 px-4 font-bold text-[#071A4D] text-right whitespace-nowrap">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#E5EAF0]">
              {isLoading && !students.length ? (
                <tr>
                  <td colSpan={12} className="py-12 text-center text-slate-500">
                    <div className="flex flex-col items-center justify-center gap-2">
                      <Loader2 className="w-6 h-6 animate-spin text-[#1769E8]" />
                      <span className="text-xs font-semibold">Loading student records live from database...</span>
                    </div>
                  </td>
                </tr>
              ) : filteredStudents.length === 0 ? (
                <tr>
                  <td colSpan={12} className="py-12 text-center text-slate-400">
                    No students found matching your filter criteria in database.
                  </td>
                </tr>
              ) : (
                filteredStudents.map((s, idx) => (
                  <tr
                    key={s.id}
                    className={`hover:bg-[#F8FAFC] transition-colors ${
                      selectedRows.includes(s.id) ? "bg-[#EFF6FF]/40" : ""
                    }`}
                  >
                    <td className="py-3 px-3.5 text-center whitespace-nowrap">
                      <input
                        type="checkbox"
                        checked={selectedRows.includes(s.id)}
                        onChange={() => handleRowSelect(s.id)}
                        className="rounded border-[#CBD5E1] text-[#1769E8] focus:ring-0 cursor-pointer"
                      />
                    </td>
                    <td className="py-3 px-2 text-center text-[#94A3B8] font-medium whitespace-nowrap">
                      {(currentPage - 1) * parseInt(pageSize, 10) + idx + 1}
                    </td>
                    <td className="py-3 px-3 font-mono font-bold text-xs whitespace-nowrap">
                      <span className="bg-[#F1F6FC] text-[#1769E8] px-2 py-0.5 rounded border border-[#D0E2FF]">
                        {s.nchmctRollNo}
                      </span>
                    </td>
                    <td className="py-3 px-3 whitespace-nowrap">
                      <Link
                        href={`/admin/people/students/details?id=${s.id}`}
                        className="font-bold text-[#071A4D] hover:text-[#1769E8] text-xs text-left cursor-pointer transition-colors"
                        title="View Student Details"
                      >
                        {s.user?.fullName || "Unnamed Student"}
                      </Link>
                    </td>
                    <td className="py-3 px-3 text-[#64748B] text-xs whitespace-nowrap">
                      {s.gender || "—"}
                    </td>
                    <td className="py-3 px-3 font-medium text-[#334155] text-xs whitespace-nowrap">
                      {s.course?.code || s.course?.name || "BHM"}
                    </td>
                    <td className="py-3 px-3 text-[#64748B] text-xs whitespace-nowrap">
                      {s.semester?.name || "Semester V"}
                    </td>
                    <td className="py-3 px-3 whitespace-nowrap">
                      <span className="inline-flex px-2 py-0.5 rounded font-bold text-[11px] bg-slate-100 text-slate-700 border border-slate-200">
                        {s.studentGroup?.name || "Batch A"}
                      </span>
                    </td>
                    <td className="py-3 px-3 text-[#64748B] text-xs font-mono whitespace-nowrap">
                      {s.user?.email || "—"}
                    </td>
                    <td className="py-3 px-3 text-[#64748B] text-xs font-mono whitespace-nowrap">
                      {s.user?.phone || "—"}
                    </td>
                    <td className="py-3 px-3 text-center whitespace-nowrap">
                      <span
                        className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-[11px] font-bold border ${
                          s.status === "ACTIVE"
                            ? "bg-[#DCFCE7] text-[#15803D] border-[#BBF7D0]"
                            : "bg-[#FEE2E2] text-[#DC2626] border-[#FECACA]"
                        }`}
                      >
                        {s.status}
                      </span>
                    </td>
                    <td className="py-3 px-4 text-right whitespace-nowrap">
                      <div className="flex items-center justify-end gap-1.5">
                        <Link
                          href={`/admin/people/students/details?id=${s.id}`}
                          className="p-1.5 text-[#64748B] hover:text-[#1769E8] hover:bg-[#EFF6FF] rounded-md transition-colors cursor-pointer"
                          title="View Student Details"
                        >
                          <Eye className="w-3.5 h-3.5" />
                        </Link>
                        <Link
                          href={`/admin/people/students/edit?id=${s.id}`}
                          className="p-1.5 text-[#64748B] hover:text-[#1769E8] hover:bg-[#EFF6FF] rounded-md transition-colors cursor-pointer"
                          title="Edit Student"
                        >
                          <Edit2 className="w-3.5 h-3.5" />
                        </Link>
                        <button
                          onClick={() => handleDeleteStudent(s.id, s.user?.fullName || s.nchmctRollNo)}
                          disabled={deletingId === s.id}
                          className="p-1.5 text-[#64748B] hover:text-rose-600 hover:bg-rose-50 rounded-md transition-colors cursor-pointer"
                          title="Delete Student from DB"
                        >
                          {deletingId === s.id ? (
                            <Loader2 className="w-3.5 h-3.5 animate-spin text-rose-600" />
                          ) : (
                            <Trash2 className="w-3.5 h-3.5" />
                          )}
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        <div className="p-4 border-t border-[#E5EAF0] flex flex-col sm:flex-row items-center justify-between gap-3 text-xs text-[#64748B]">
          <div>
            Showing {filteredStudents.length > 0 ? (currentPage - 1) * parseInt(pageSize, 10) + 1 : 0} to{" "}
            {(currentPage - 1) * parseInt(pageSize, 10) + filteredStudents.length} of {totalStudents} enrolled students
          </div>
          <div className="flex items-center gap-1">
            <button
              onClick={() => setCurrentPage((p) => Math.max(p - 1, 1))}
              disabled={currentPage === 1}
              className="p-1.5 border border-[#E2E8F0] rounded-md hover:bg-slate-50 disabled:opacity-40 transition-colors cursor-pointer"
            >
              <ChevronLeft className="w-3.5 h-3.5" />
            </button>
            <span className="px-3 py-1 bg-[#1769E8] text-white font-bold rounded-md text-xs">
              {currentPage}
            </span>
            <button
              onClick={() => setCurrentPage((p) => p + 1)}
              disabled={filteredStudents.length < parseInt(pageSize, 10)}
              className="p-1.5 border border-[#E2E8F0] rounded-md hover:bg-slate-50 disabled:opacity-40 transition-colors cursor-pointer"
            >
              <ChevronRight className="w-3.5 h-3.5" />
            </button>
          </div>
        </div>
      </div>

      {/* Bulk Import Modal */}
      {isImportModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-xs p-4">
          <div className="bg-white rounded-2xl border border-[#E5EAF0] shadow-xl max-w-md w-full p-6 text-xs space-y-4">
            <div className="flex items-center justify-between pb-3 border-b border-[#E5EAF0]">
              <div className="flex items-center gap-2">
                <Upload className="w-4 h-4 text-[#1769E8]" />
                <h3 className="font-heading font-bold text-base text-[#071A4D]">
                  Bulk Import Students
                </h3>
              </div>
              <button
                onClick={() => setIsImportModalOpen(false)}
                className="p-1 rounded-md text-slate-400 hover:text-slate-600 hover:bg-slate-100 cursor-pointer"
              >
                <X className="w-4 h-4" />
              </button>
            </div>

            <p className="text-[#64748B]">
              Upload an Excel (.xlsx) file containing student roll numbers, full names, emails, and assigned batches to ingest directly into the database.
            </p>

            <label className="border-2 border-dashed border-[#CBD5E1] rounded-xl p-6 text-center hover:border-[#1769E8] transition-colors bg-[#F8FAFC] block cursor-pointer">
              <Upload className="w-8 h-8 text-[#94A3B8] mx-auto mb-2" />
              <p className="font-semibold text-[#071A4D]">
                {isUploading ? "Uploading & Ingesting..." : "Click to select Excel (.xlsx) file"}
              </p>
              <p className="text-[11px] text-[#94A3B8] mt-1">Automatic validation against courses &amp; batches</p>
              <input
                type="file"
                accept=".xlsx"
                onChange={handleFileUpload}
                disabled={isUploading}
                className="hidden"
              />
            </label>

            <div className="flex items-center justify-end gap-2 pt-3 border-t border-[#E5EAF0]">
              <button
                onClick={() => setIsImportModalOpen(false)}
                className="px-4 py-2 border border-[#E2E8F0] text-[#64748B] hover:bg-slate-50 rounded-lg font-semibold cursor-pointer"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Complete Student View Card Modal */}
      {viewingStudent && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-xs p-4 animate-in fade-in duration-150">
          <div className="bg-white rounded-2xl border border-[#E5EAF0] shadow-2xl max-w-lg w-full overflow-hidden">
            {/* Header with Dark Navy Institutional Aesthetic */}
            <div className="bg-[#071A4D] px-6 py-5 text-white relative">
              <div className="flex items-start justify-between">
                <div className="flex items-center gap-3.5">
                  <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-[#1769E8] to-[#0F4CBD] flex items-center justify-center text-white font-bold text-base shadow-sm border border-white/20">
                    {(viewingStudent.user?.fullName || "S")
                      .split(" ")
                      .map((n) => n[0])
                      .join("")
                      .substring(0, 2)}
                  </div>
                  <div>
                    <h3 className="font-heading font-bold text-lg text-white">
                      {viewingStudent.user?.fullName || "Student Profile"}
                    </h3>
                    <div className="flex items-center gap-2 mt-1">
                      <span className="font-mono text-xs bg-white/10 text-sky-200 px-2 py-0.5 rounded border border-white/15">
                        Roll: {viewingStudent.nchmctRollNo}
                      </span>
                      <span
                        className={`text-[10px] font-bold px-2 py-0.5 rounded-full border ${
                          viewingStudent.status === "ACTIVE"
                            ? "bg-emerald-500/20 text-emerald-300 border-emerald-400/30"
                            : "bg-rose-500/20 text-rose-300 border-rose-400/30"
                        }`}
                      >
                        {viewingStudent.status}
                      </span>
                    </div>
                  </div>
                </div>

                <button
                  onClick={() => setViewingStudent(null)}
                  className="p-1.5 rounded-lg text-slate-300 hover:text-white hover:bg-white/10 transition-colors cursor-pointer"
                  title="Close"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>
            </div>

            {/* Content Body */}
            <div className="p-6 space-y-4 text-xs">
              {/* Academic Enrollment Section */}
              <div className="bg-[#F8FAFC] border border-[#E2E8F0] rounded-xl p-4">
                <div className="flex items-center gap-2 font-bold text-[#071A4D] mb-3 pb-2 border-b border-[#E2E8F0]">
                  <Sparkles className="w-4 h-4 text-[#1769E8]" />
                  <span className="font-heading text-xs uppercase tracking-wider">
                    Academic Enrolment
                  </span>
                </div>
                <div className="grid grid-cols-2 gap-3 text-[#334155]">
                  <div>
                    <span className="text-[11px] text-[#64748B] block">Program:</span>
                    <span className="font-semibold text-xs text-[#071A4D]">
                      {viewingStudent.course?.name || viewingStudent.course?.code || "Hospitality Administration"}
                    </span>
                  </div>
                  <div>
                    <span className="text-[11px] text-[#64748B] block">Semester:</span>
                    <span className="font-semibold text-xs text-[#071A4D]">
                      {viewingStudent.semester?.name || "Semester V"}
                    </span>
                  </div>
                  <div>
                    <span className="text-[11px] text-[#64748B] block">Practical Batch:</span>
                    <span className="font-semibold text-xs text-[#071A4D]">
                      {viewingStudent.studentGroup?.name || "General Batch"}
                    </span>
                  </div>
                  <div>
                    <span className="text-[11px] text-[#64748B] block">Gender:</span>
                    <span className="font-semibold text-xs text-[#071A4D]">
                      {viewingStudent.gender || "Not Specified"}
                    </span>
                  </div>
                </div>
              </div>

              {/* Official Contact Section */}
              <div className="bg-[#F8FAFC] border border-[#E2E8F0] rounded-xl p-4">
                <div className="flex items-center gap-2 font-bold text-[#071A4D] mb-3 pb-2 border-b border-[#E2E8F0]">
                  <Users className="w-4 h-4 text-[#1769E8]" />
                  <span className="font-heading text-xs uppercase tracking-wider">
                    Official Contact &amp; Registry
                  </span>
                </div>
                <div className="space-y-2.5 text-[#334155]">
                  <div className="flex items-center justify-between">
                    <span className="text-[11px] text-[#64748B] flex items-center gap-1.5">
                      <Mail className="w-3.5 h-3.5 text-[#94A3B8]" />
                      Email:
                    </span>
                    <span className="font-mono font-medium text-xs text-[#071A4D]">
                      {viewingStudent.user?.email || "—"}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-[11px] text-[#64748B] flex items-center gap-1.5">
                      <Phone className="w-3.5 h-3.5 text-[#94A3B8]" />
                      Mobile Phone:
                    </span>
                    <span className="font-mono font-medium text-xs text-[#071A4D]">
                      {viewingStudent.user?.phone || "—"}
                    </span>
                  </div>
                </div>
              </div>

              {/* Attendance & Biometric Status */}
              <div className="bg-[#F1F6FC] border border-[#D0E2FF] rounded-xl p-3.5 flex items-center justify-between">
                <div>
                  <div className="font-bold text-xs text-[#071A4D]">
                    Attendance Records in DB
                  </div>
                  <div className="text-[11px] text-[#64748B]">
                    Enrolled records logged in database
                  </div>
                </div>
                <div className="text-right">
                  <span className="text-base font-bold text-[#1769E8] font-mono">
                    {viewingStudent._count?.attendanceRecords ?? 0} Sessions
                  </span>
                  <span className="block text-[10px] font-semibold text-emerald-700">
                    Active Registry
                  </span>
                </div>
              </div>
            </div>

            {/* Footer Actions */}
            <div className="px-6 py-4 bg-[#F8FAFC] border-t border-[#E5EAF0] flex items-center justify-between gap-3">
              <Link
                href={`/admin/people/students/edit?id=${viewingStudent.id}`}
                className="px-4 py-2 bg-white border border-[#CBD5E1] text-[#334155] hover:bg-slate-50 rounded-lg text-xs font-semibold transition-colors flex items-center gap-1.5 cursor-pointer"
              >
                <Edit2 className="w-3.5 h-3.5 text-[#1769E8]" />
                <span>Edit Record</span>
              </Link>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setViewingStudent(null)}
                  className="px-4 py-2 border border-[#E2E8F0] text-[#64748B] hover:bg-slate-100 rounded-lg text-xs font-semibold transition-colors cursor-pointer"
                >
                  Close
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
