"use client";

import React, { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import {
  Users,
  Search,
  ChevronRight,
  Eye,
  Mail,
  Phone,
  RotateCcw,
  FileSpreadsheet,
  Plus,
  X,
  UserCheck,
  Building,
  Calendar,
  AlertTriangle,
  GraduationCap,
  ShieldCheck,
  CheckCircle2,
  Camera,
  User,
  Hash,
  CalendarCheck,
  RefreshCw,
  Loader2,
} from "lucide-react";
import { toast } from "sonner";
import { apiClient } from "@/lib/api-client";
import { StudentDetailsView } from "@/components/students/student-details-view";

// 16 Client-Mandated Fields from PRD §5
interface StudentProfile {
  id: string;
  name: string; // 1. Student Name
  gender: string; // 2. Gender
  email: string; // 3. Email Address
  phone: string; // 4. Mobile Number
  guardianName: string; // 5. Guardian Name
  guardianEmail: string; // 6. Guardian Email
  guardianPhone: string; // 7. Guardian Mobile Number
  program: string; // 8. Course
  semester: string; // 9. Semester
  section: string; // 10. Group
  joiningYear: string; // 11. Joining Year
  passingYear: string; // 12. Passing Year
  roll: string; // 13. NCHM Roll Number
  username: string; // 14. Username
  status: "Active Enrolled" | "Medical Leave" | "Detained" | "Graduated"; // 15. Student Status
  photoUrl?: string; // 16. Student Photograph
  bloodGroup: string;
  category: string;
  attendance: number;
}

const initialProfiles: StudentProfile[] = [
  {
    id: "sp-1",
    name: "Aaron Smith",
    roll: "2441112001",
    username: "aaron.smith24",
    program: "B.Sc. in Hospitality",
    semester: "Semester III",
    section: "Batch B1",
    joiningYear: "2024",
    passingYear: "2027",
    email: "aaron.smith@ihmkolkata.edu.in",
    phone: "+91 98301 23456",
    attendance: 88,
    gender: "Male",
    bloodGroup: "O+",
    guardianName: "David Smith",
    guardianEmail: "david.smith@gmail.com",
    guardianPhone: "+91 98301 99001",
    status: "Active Enrolled",
    category: "General",
  },
  {
    id: "sp-2",
    name: "Bethany Roy",
    roll: "2441112002",
    username: "bethany.roy24",
    program: "B.Sc. in Hospitality",
    semester: "Semester III",
    section: "Batch B1",
    joiningYear: "2024",
    passingYear: "2027",
    email: "bethany.roy@ihmkolkata.edu.in",
    phone: "+91 98301 23457",
    attendance: 92,
    gender: "Female",
    bloodGroup: "A+",
    guardianName: "Subrata Roy",
    guardianEmail: "subrata.roy@gmail.com",
    guardianPhone: "+91 98301 99002",
    status: "Active Enrolled",
    category: "General",
  },
  {
    id: "sp-3",
    name: "Chirag Banerjee",
    roll: "2441112003",
    username: "chirag.b24",
    program: "B.Sc. in Hospitality",
    semester: "Semester III",
    section: "Batch B2",
    joiningYear: "2024",
    passingYear: "2027",
    email: "chirag.b@ihmkolkata.edu.in",
    phone: "+91 98301 23458",
    attendance: 78,
    gender: "Male",
    bloodGroup: "B+",
    guardianName: "Alok Banerjee",
    guardianEmail: "alok.banerjee@gmail.com",
    guardianPhone: "+91 98301 99003",
    status: "Active Enrolled",
    category: "General",
  },
  {
    id: "sp-4",
    name: "Debolina Mukherjee",
    roll: "2441112004",
    username: "debolina.m24",
    program: "B.Sc. in Hospitality",
    semester: "Semester III",
    section: "Batch B2",
    joiningYear: "2024",
    passingYear: "2027",
    email: "debolina.m@ihmkolkata.edu.in",
    phone: "+91 98301 23459",
    attendance: 84,
    gender: "Female",
    bloodGroup: "AB+",
    guardianName: "Pranab Mukherjee",
    guardianEmail: "pranab.m@gmail.com",
    guardianPhone: "+91 98301 99004",
    status: "Active Enrolled",
    category: "General",
  },
  {
    id: "sp-5",
    name: "Farhan Akhtar",
    roll: "2441112005",
    username: "farhan.a25",
    program: "B.Sc. in Hospitality",
    semester: "Semester I",
    section: "Batch A1",
    joiningYear: "2025",
    passingYear: "2028",
    email: "farhan.a@ihmkolkata.edu.in",
    phone: "+91 98301 23460",
    attendance: 71,
    gender: "Male",
    bloodGroup: "O-",
    guardianName: "Zaved Akhtar",
    guardianEmail: "zaved.akhtar@gmail.com",
    guardianPhone: "+91 98301 99005",
    status: "Medical Leave",
    category: "OBC",
  },
  {
    id: "sp-6",
    name: "Gargi Sengupta",
    roll: "2441112006",
    username: "gargi.s25",
    program: "M.Sc. in Hospitality",
    semester: "Semester I",
    section: "PG Batch 1",
    joiningYear: "2025",
    passingYear: "2027",
    email: "gargi.s@ihmkolkata.edu.in",
    phone: "+91 98301 23461",
    attendance: 95,
    gender: "Female",
    bloodGroup: "B+",
    guardianName: "Tapan Sengupta",
    guardianEmail: "tapan.sengupta@gmail.com",
    guardianPhone: "+91 98301 99006",
    status: "Active Enrolled",
    category: "General",
  },
  {
    id: "sp-7",
    name: "Harish Nair",
    roll: "2441112007",
    username: "harish.n25",
    program: "Diploma in Food Production",
    semester: "Semester I",
    section: "Diploma D1",
    joiningYear: "2025",
    passingYear: "2026",
    email: "harish.n@ihmkolkata.edu.in",
    phone: "+91 98301 23462",
    attendance: 81,
    gender: "Male",
    bloodGroup: "A-",
    guardianName: "Raman Nair",
    guardianEmail: "raman.nair@gmail.com",
    guardianPhone: "+91 98301 99007",
    status: "Active Enrolled",
    category: "General",
  },
  {
    id: "sp-8",
    name: "Ishita Chatterjee",
    roll: "2441112008",
    username: "ishita.c25",
    program: "Diploma in F&B Service",
    semester: "Semester I",
    section: "Diploma D2",
    joiningYear: "2025",
    passingYear: "2026",
    email: "ishita.c@ihmkolkata.edu.in",
    phone: "+91 98301 23463",
    attendance: 69,
    gender: "Female",
    bloodGroup: "O+",
    guardianName: "Somnath Chatterjee",
    guardianEmail: "somnath.c@gmail.com",
    guardianPhone: "+91 98301 99008",
    status: "Detained",
    category: "SC",
  },
];

export default function StudentProfilesPage() {
  const [profilesList, setProfilesList] = useState<StudentProfile[]>(initialProfiles);
  const [isLoading, setIsLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [search, setSearch] = useState("");
  const [programFilter, setProgramFilter] = useState("All Programs");
  const [semesterFilter, setSemesterFilter] = useState("All Semesters");
  const [attendanceFilter, setAttendanceFilter] = useState("All Standing");
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [pageSize, setPageSize] = useState("10 per page");

  // Profile Details View State
  const [viewingStudentId, setViewingStudentId] = useState<string | null>(null);

  // Fetch Live Students from DB
  const fetchProfiles = useCallback(async (isManualRefresh = false) => {
    try {
      if (isManualRefresh) setIsRefreshing(true);
      else setIsLoading(true);

      const [stuRes, recRes] = await Promise.allSettled([
        apiClient.get<{ success: boolean; data: any[] }>("/students?limit=100"),
        apiClient.get<{ success: boolean; data: any[] }>("/students/academic-records"),
      ]);

      const attendanceMap = new Map<string, number>();
      if (recRes.status === "fulfilled" && recRes.value.data?.success && Array.isArray(recRes.value.data.data)) {
        recRes.value.data.data.forEach((r: any) => {
          if (r.roll) attendanceMap.set(r.roll, r.attendancePercent);
          if (r.id) attendanceMap.set(r.id, r.attendancePercent);
        });
      }

      if (stuRes.status === "fulfilled" && stuRes.value.data?.success && Array.isArray(stuRes.value.data.data)) {
        const mapped: StudentProfile[] = stuRes.value.data.data.map((s: any, idx: number) => {
          const roll = s.nchmctRollNo || `244111${2000 + idx}`;
          const fullName = s.user?.fullName || "Student";
          const email = s.user?.email || `${roll.toLowerCase()}@ihmkolkata.edu.in`;
          const att = attendanceMap.get(s.id) ?? attendanceMap.get(roll) ?? (s.status === "ACTIVE" ? 86 : 64);

          return {
            id: s.id,
            name: fullName,
            gender: s.gender || (idx % 2 === 0 ? "Male" : "Female"),
            email: email,
            phone: s.user?.phone || `+91 98301 ${String(23450 + idx).slice(-5)}`,
            guardianName: `Guardian of ${fullName}`,
            guardianEmail: `guardian.${email.split("@")[0]}@gmail.com`,
            guardianPhone: `+91 98301 ${String(99000 + idx).slice(-5)}`,
            program: s.course?.name || s.course?.code || "B.Sc. in Hospitality",
            semester: s.semester?.name || "Semester V",
            section: s.studentGroup?.name || "Batch A",
            joiningYear: String(s.admissionYear || 2024),
            passingYear: String((s.admissionYear || 2024) + 3),
            roll: roll,
            username: email.split("@")[0],
            status: s.status === "ACTIVE" ? "Active Enrolled" : s.status === "DETAINED" ? "Detained" : "Medical Leave",
            photoUrl: s.photoUrl || s.user?.avatarUrl || null,
            bloodGroup: ["O+", "A+", "B+", "AB+", "O-"][idx % 5],
            category: "General",
            attendance: att,
          };
        });

        if (mapped.length > 0) {
          setProfilesList(mapped);
          if (isManualRefresh) toast.success("Student profiles refreshed!");
          return;
        }
      }
    } catch (err) {
      console.error("Failed to fetch student profiles:", err);
    } finally {
      setIsLoading(false);
      setIsRefreshing(false);
    }
  }, []);

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

  const filtered = profilesList.filter((p) => {
    const matchesSearch =
      search === "" ||
      p.name.toLowerCase().includes(search.toLowerCase()) ||
      p.roll.toLowerCase().includes(search.toLowerCase()) ||
      p.email.toLowerCase().includes(search.toLowerCase()) ||
      p.phone.includes(search);

    const matchesProgram =
      programFilter === "All Programs" || p.program === programFilter;

    const matchesSemester =
      semesterFilter === "All Semesters" || p.semester === semesterFilter;

    let matchesAttendance = true;
    if (attendanceFilter === "85%+ Exemplary") matchesAttendance = p.attendance >= 85;
    else if (attendanceFilter === "75% - 84% Regular") matchesAttendance = p.attendance >= 75 && p.attendance < 85;
    else if (attendanceFilter === "< 75% Critical Shortage") matchesAttendance = p.attendance < 75;

    return matchesSearch && matchesProgram && matchesSemester && matchesAttendance;
  });

  const handleResetFilters = () => {
    setSearch("");
    setProgramFilter("All Programs");
    setSemesterFilter("All Semesters");
    setAttendanceFilter("All Standing");
  };

  const handleToggleSelectAll = () => {
    if (selectedIds.length === filtered.length && filtered.length > 0) {
      setSelectedIds([]);
    } else {
      setSelectedIds(filtered.map((p) => p.id));
    }
  };

  const handleToggleSelectRow = (id: string) => {
    setSelectedIds((prev) =>
      prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id]
    );
  };

  const handleExportCSV = () => {
    if (filtered.length === 0) {
      toast.error("No student profiles available to export.");
      return;
    }
    const headers = [
      "NCHM Roll No",
      "Full Name",
      "Username",
      "Program",
      "Semester",
      "Section Group",
      "Joining Year",
      "Passing Year",
      "Email",
      "Mobile",
      "Gender",
      "Blood Group",
      "Category",
      "Status",
      "Attendance %",
      "Guardian Name",
      "Guardian Mobile",
    ];
    const rows = filtered.map((p) => [
      `"${p.roll}"`,
      `"${p.name}"`,
      `"${p.username}"`,
      `"${p.program}"`,
      `"${p.semester}"`,
      `"${p.section}"`,
      `"${p.joiningYear}"`,
      `"${p.passingYear}"`,
      `"${p.email}"`,
      `"${p.phone}"`,
      `"${p.gender}"`,
      `"${p.bloodGroup}"`,
      `"${p.category}"`,
      `"${p.status}"`,
      `"${p.attendance}%"`,
      `"${p.guardianName}"`,
      `"${p.guardianPhone}"`,
    ]);
    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_student_profiles_${new Date().toISOString().slice(0, 10)}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    toast.success("Student profiles exported to CSV!");
  };

  if (viewingStudentId) {
    const selectedProfile = profilesList.find((p) => p.id === viewingStudentId);
    return (
      <StudentDetailsView
        studentId={viewingStudentId}
        initialData={selectedProfile}
        onBack={() => setViewingStudentId(null)}
      />
    );
  }

  return (
    <div className="space-y-6 font-sans pb-12 bg-[#F8FAFC] min-h-screen">
      {/* ============================================================ */}
      {/* 1. TOP HEADER & BREADCRUMB                                   */}
      {/* ============================================================ */}
      <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">
            Students
          </Link>
          <ChevronRight className="w-3.5 h-3.5 text-[#94A3B8]" />
          <span className="text-[#071A4D] font-semibold">Student Profiles</span>
        </nav>

        <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
          <div>
            <h1 className="text-3xl font-bold font-heading text-[#071A4D] tracking-tight">
              Student Profiles Directory
            </h1>
            <p className="text-[15px] text-[#64748B] mt-1 font-normal">
              Serial roster view of student academic records, contact info, and attendance standing.
            </p>
          </div>

          <div className="flex items-center gap-2.5 shrink-0 flex-wrap">
            <button
              onClick={() => fetchProfiles(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 profiles"
            >
              <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 text-sm font-semibold text-[#071A4D] bg-white border border-[#E5EAF0] rounded-lg 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 Roster</span>
            </button>

            <Link
              href="/admin/people/students/register"
              className="h-10 px-4 inline-flex items-center justify-center gap-2 text-sm font-semibold text-white bg-[#1769E8] hover:bg-[#1257C7] rounded-lg shadow-sm transition-colors cursor-pointer shrink-0 whitespace-nowrap"
            >
              <Plus className="w-4 h-4" />
              <span>New Student Registration</span>
            </Link>
          </div>
        </div>
      </div>

      {/* ============================================================ */}
      {/* 2. FILTER AND SEARCH BAR                                     */}
      {/* ============================================================ */}
      <div className="p-4 rounded-xl bg-white border border-[#E5EAF0] shadow-xs">
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-12 gap-3.5 items-end">
          {/* Program Filter */}
          <div className="lg:col-span-3">
            <label className="block text-[11px] font-semibold text-[#64748B] uppercase tracking-wider mb-1.5">
              Program
            </label>
            <select
              value={programFilter}
              onChange={(e) => setProgramFilter(e.target.value)}
              className="w-full h-10 px-3 rounded-lg border border-[#E2E8F0] bg-white text-sm font-medium text-[#0F172A] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all cursor-pointer"
            >
              <option>All Programs</option>
              <option>B.Sc. in Hospitality</option>
              <option>M.Sc. in Hospitality</option>
              <option>Diploma in Food Production</option>
              <option>Diploma in F&B Service</option>
            </select>
          </div>

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

          {/* Attendance Standing */}
          <div className="lg:col-span-2">
            <label className="block text-[11px] font-semibold text-[#64748B] uppercase tracking-wider mb-1.5">
              Attendance Standing
            </label>
            <select
              value={attendanceFilter}
              onChange={(e) => setAttendanceFilter(e.target.value)}
              className="w-full h-10 px-3 rounded-lg border border-[#E2E8F0] bg-white text-sm font-medium text-[#0F172A] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all cursor-pointer"
            >
              <option>All Standing</option>
              <option>85%+ Exemplary</option>
              <option>75% - 84% Regular</option>
              <option>&lt; 75% Critical Shortage</option>
            </select>
          </div>

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

          {/* Action Buttons */}
          <div className="lg:col-span-2 flex items-center gap-2">
            <button
              onClick={() => { }}
              className="flex-1 h-10 px-4 rounded-lg bg-[#1769E8] hover:bg-[#1257C7] text-white text-sm font-semibold flex items-center justify-center gap-1.5 shadow-xs transition-colors cursor-pointer whitespace-nowrap"
            >
              <Search className="w-4 h-4" />
              <span>Search</span>
            </button>

            <button
              onClick={handleResetFilters}
              className="h-10 w-10 rounded-lg border border-[#E2E8F0] hover:bg-slate-50 text-[#64748B] flex items-center justify-center transition-colors shadow-2xs cursor-pointer shrink-0"
              title="Reset Filters"
            >
              <RotateCcw className="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>

      {/* ============================================================ */}
      {/* 3. FULL WIDTH SERIAL TABLE - SERIAL-WISE (NO SEPARATE CARDS) */}
      {/* ============================================================ */}
      <div className="rounded-xl bg-white border border-[#E5EAF0] shadow-xs overflow-hidden">
        {/* Table Header Controls */}
        <div className="p-4 border-b border-[#E5EAF0] flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Users className="w-4 h-4 text-[#1769E8]" />
            <h2 className="text-sm font-bold font-heading text-[#071A4D]">
              Enrolled Students Serial Roster ({filtered.length})
            </h2>
          </div>

          <select
            value={pageSize}
            onChange={(e) => setPageSize(e.target.value)}
            className="h-8 px-2.5 rounded-lg border border-[#D8E0EA] bg-white text-xs text-[#64748B] focus:outline-none focus:border-[#1769E8] cursor-pointer"
          >
            <option>10 per page</option>
            <option>25 per page</option>
            <option>50 per page</option>
          </select>
        </div>

        {/* Table Data */}
        <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] whitespace-nowrap">
                <th className="py-3 px-3.5 text-center w-10">
                  <input
                    type="checkbox"
                    checked={selectedIds.length === filtered.length && filtered.length > 0}
                    onChange={handleToggleSelectAll}
                    className="rounded border-[#D8E0EA] text-[#1769E8] focus:ring-[#1769E8] cursor-pointer"
                  />
                </th>
                <th className="py-3 px-2 text-center w-10">#</th>
                <th className="py-3 px-4">NCHM Roll No</th>
                <th className="py-3 px-4">Student & Username</th>
                <th className="py-3 px-4">Program</th>
                <th className="py-3 px-4">Semester & Group</th>
                <th className="py-3 px-4">Session Years</th>
                <th className="py-3 px-4">Status</th>
                <th className="py-3 px-4 text-center">Attendance %</th>
                <th className="py-3 px-4 text-center">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#E5EAF0] text-[#334155]">
              {isLoading && profilesList.length === 0 ? (
                <tr>
                  <td colSpan={10} 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 profiles...</span>
                    </div>
                  </td>
                </tr>
              ) : filtered.length === 0 ? (
                <tr>
                  <td colSpan={10} className="py-12 text-center text-slate-400">
                    No student profiles match the filter criteria.
                  </td>
                </tr>
              ) : (
                filtered.map((p, idx) => {
                  const isSelected = selectedIds.includes(p.id);
                  return (
                    <tr
                      key={p.id}
                      className={`hover:bg-[#F8FAFC] transition-colors whitespace-nowrap ${isSelected ? "bg-blue-50/40" : ""
                        }`}
                    >
                      <td className="py-3.5 px-3.5 text-center">
                        <input
                          type="checkbox"
                          checked={isSelected}
                          onChange={() => handleToggleSelectRow(p.id)}
                          className="rounded border-[#D8E0EA] text-[#1769E8] focus:ring-[#1769E8] cursor-pointer"
                        />
                      </td>
                      <td className="py-3.5 px-2 text-center text-slate-400 font-medium">
                        {idx + 1}
                      </td>
                      <td className="py-3.5 px-4 font-mono font-bold text-[#1769E8]">
                        <span className="bg-blue-50 border border-blue-100 px-2 py-0.5 rounded text-[11px]">
                          {p.roll}
                        </span>
                      </td>
                      <td className="py-3.5 px-4">
                        <div className="flex items-center gap-2.5">
                          {p.photoUrl ? (
                            <img
                              src={p.photoUrl}
                              alt={p.name}
                              className="w-8 h-8 rounded-lg object-cover border border-slate-200 shadow-2xs shrink-0"
                            />
                          ) : (
                            <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-[#1769E8] to-[#071A4D] text-white font-bold flex items-center justify-center text-xs shadow-2xs shrink-0 font-heading">
                              {p.name.slice(0, 2).toUpperCase()}
                            </div>
                          )}
                          <div>
                            <button
                              type="button"
                              onClick={() => setViewingStudentId(p.id)}
                              className="font-semibold text-[#071A4D] hover:text-[#1769E8] transition-colors text-left cursor-pointer block"
                              title="View complete student details"
                            >
                              {p.name}
                            </button>
                            <div className="text-[11px] font-mono text-slate-400">@{p.username}</div>
                          </div>
                        </div>
                      </td>
                      <td className="py-3.5 px-4 text-[#334155]">
                        {p.program}
                      </td>
                      <td className="py-3.5 px-4">
                        <span className="text-[#475569] block font-medium">{p.semester}</span>
                        <span className="inline-flex items-center px-1.5 py-0.2 rounded text-[10px] font-semibold bg-slate-100 text-slate-600">
                          {p.section}
                        </span>
                      </td>
                      <td className="py-3.5 px-4 font-mono text-[11px] text-[#64748B]">
                        {p.joiningYear} – {p.passingYear}
                      </td>
                      <td className="py-3.5 px-4">
                        <span
                          className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold border ${p.status === "Active Enrolled"
                            ? "bg-emerald-50 text-emerald-700 border-emerald-200"
                            : p.status === "Medical Leave"
                              ? "bg-amber-50 text-amber-700 border-amber-200"
                              : "bg-red-50 text-red-700 border-red-200"
                            }`}
                        >
                          {p.status}
                        </span>
                      </td>
                      <td className="py-3.5 px-4 text-center">
                        <span
                          className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-[11px] font-bold ${p.attendance >= 85
                            ? "bg-[#DCFCE7] text-[#15803D]"
                            : p.attendance >= 75
                              ? "bg-[#FEF3C7] text-[#D97706]"
                              : "bg-[#FEE2E2] text-[#DC2626]"
                            }`}
                        >
                          {p.attendance}%
                        </span>
                      </td>
                      <td className="py-3.5 px-4 text-center">
                        <button
                          onClick={() => setViewingStudentId(p.id)}
                          className="inline-flex items-center gap-1 px-2.5 py-1 text-xs font-semibold text-[#1769E8] hover:bg-blue-50 border border-blue-200 rounded-lg transition-colors cursor-pointer"
                          title="View complete student details"
                        >
                          <Eye className="w-3.5 h-3.5" />
                          <span>View Profile</span>
                        </button>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination Footer */}
        <div className="p-3.5 px-4 border-t border-[#E5EAF0] flex items-center justify-between text-xs text-[#64748B]">
          <div>
            Showing 1 to {filtered.length} of {profilesList.length} student profiles
          </div>
          <div className="flex items-center gap-1">
            <button
              disabled
              className="px-2.5 py-1 rounded border border-[#E5EAF0] text-slate-300 cursor-not-allowed"
            >
              &lt;
            </button>
            <button className="px-3 py-1 rounded bg-[#1769E8] text-white font-bold">
              1
            </button>
            <button
              disabled
              className="px-2.5 py-1 rounded border border-[#E5EAF0] text-slate-300 cursor-not-allowed"
            >
              &gt;
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
