"use client";

import React, { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import {
  ChevronRight,
  FileSpreadsheet,
  Search,
  RotateCcw,
  RefreshCw,
  Loader2,
  CheckCircle2,
  AlertTriangle,
  UserX,
  GraduationCap,
  Award,
  Eye,
  X,
  Sparkles,
  BookOpen,
  Calendar,
} from "lucide-react";
import { toast } from "sonner";
import { apiClient } from "@/lib/api-client";

interface AcademicRecordItem {
  id: string;
  roll: string;
  name: string;
  email: string;
  phone?: string | null;
  course: string;
  courseName: string;
  semester: string;
  batch: string;
  conductedHours: number;
  attendedHours: number;
  creditsEarned: number;
  attendancePercent: number;
  standing: string;
  standingColor: string;
  isEligible: boolean;
  subjectCount: number;
}

interface SummaryStats {
  totalEvaluated: number;
  goodStandingCount: number;
  warningCount: number;
  criticalCount: number;
}

export default function AcademicRecordsPage() {
  const [records, setRecords] = useState<AcademicRecordItem[]>([]);
  const [summaryStats, setSummaryStats] = useState<SummaryStats | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isError, setIsError] = useState(false);

  // Filters
  const [search, setSearch] = useState("");
  const [selectedStanding, setSelectedStanding] = useState("All Standings");
  const [selectedBatch, setSelectedBatch] = useState("All Batches");
  const [viewingRecord, setViewingRecord] = useState<AcademicRecordItem | null>(null);

  // Fetch live academic performance records from database
  const fetchAcademicRecords = useCallback(async (isManualRefresh = false) => {
    try {
      if (isManualRefresh) setIsRefreshing(true);
      else setIsLoading(true);
      setIsError(false);

      const params: Record<string, string> = {};
      if (search.trim()) params.search = search.trim();

      const res = await apiClient.get<{
        success: boolean;
        data: AcademicRecordItem[];
        meta?: { total: number };
        summaryStats?: SummaryStats;
      }>("/students/academic-records", { params });

      if (res.data?.success && Array.isArray(res.data.data)) {
        setRecords(res.data.data);
        if (res.data.summaryStats) {
          setSummaryStats(res.data.summaryStats);
        } else {
          // Compute summary stats directly from real records
          const data = res.data.data;
          setSummaryStats({
            totalEvaluated: data.length,
            goodStandingCount: data.filter((r) => r.attendancePercent >= 75).length,
            warningCount: data.filter((r) => r.attendancePercent < 75 && r.attendancePercent >= 70).length,
            criticalCount: data.filter((r) => r.attendancePercent < 70).length,
          });
        }

        if (isManualRefresh) {
          toast.success("Academic records updated live from MySQL database!");
        }
      }
    } catch (err: unknown) {
      console.error("Failed to load academic records:", err);
      setIsError(true);
      toast.error("Failed to fetch academic records from database.");
    } finally {
      setIsLoading(false);
      setIsRefreshing(false);
    }
  }, [search]);

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

  // Unique batches extracted dynamically from real records
  const availableBatches = Array.from(new Set(records.map((r) => r.batch).filter(Boolean)));

  // Client filtering
  const filtered = records.filter((r) => {
    const matchesSearch =
      search === "" ||
      r.name.toLowerCase().includes(search.toLowerCase()) ||
      r.roll.toLowerCase().includes(search.toLowerCase()) ||
      r.email.toLowerCase().includes(search.toLowerCase());

    const matchesStanding =
      selectedStanding === "All Standings" ||
      r.standing.toLowerCase().includes(selectedStanding.toLowerCase());

    const matchesBatch =
      selectedBatch === "All Batches" || r.batch === selectedBatch;

    return matchesSearch && matchesStanding && matchesBatch;
  });

  const handleResetFilters = () => {
    setSearch("");
    setSelectedStanding("All Standings");
    setSelectedBatch("All Batches");
    toast.info("Filters reset to default");
  };

  // Export records to CSV
  const handleExportCSV = () => {
    if (filtered.length === 0) {
      toast.error("No records available to export.");
      return;
    }

    const headers = [
      "Roll No",
      "Student Name",
      "Program",
      "Semester",
      "Batch Group",
      "Conducted Hours",
      "Attended Hours",
      "Attendance %",
      "Credits Earned",
      "Standing Status",
      "Hall Ticket Eligibility",
    ];

    const rows = filtered.map((r) => [
      `"${r.roll}"`,
      `"${r.name}"`,
      `"${r.courseName}"`,
      `"${r.semester}"`,
      `"${r.batch}"`,
      `"${r.conductedHours}h"`,
      `"${r.attendedHours}h"`,
      `"${r.attendancePercent}%"`,
      `"${r.creditsEarned}"`,
      `"${r.standing}"`,
      `"${r.isEligible ? "Eligible" : "Detained / Debarred"}"`,
    ]);

    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_academic_records_${new Date().toISOString().slice(0, 10)}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    toast.success("Academic performance records exported to CSV!");
  };

  return (
    <div className="space-y-6 font-sans pb-12 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">
            Students
          </Link>
          <ChevronRight className="w-3.5 h-3.5 text-[#94A3B8]" />
          <span className="text-[#071A4D] font-semibold">Academic Records</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">
              Academic Performance Records
            </h1>
            <p className="text-[15px] text-[#64748B] mt-1 font-normal">
              Consolidated contact hours fulfillment, credits earned, and statutory NCHMCT compliance standings.
            </p>
          </div>

          <div className="flex items-center gap-2.5 shrink-0 flex-wrap">
            <button
              onClick={() => fetchAcademicRecords(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 academic records"
            >
              <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 CSV</span>
            </button>
          </div>
        </div>
      </div>

      {/* 2. Statutory KPI Cards (Dashboard Style) */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
        {/* Metric 1: Total Evaluated */}
        <div className="p-4 rounded-xl bg-white border border-slate-200 shadow-2xs flex flex-col justify-between">
          <div className="flex items-center justify-between mb-2">
            <div className="w-8 h-8 rounded-lg bg-blue-50 border border-blue-100 text-blue-600 flex items-center justify-center">
              <GraduationCap className="w-4 h-4" />
            </div>
            <span className="text-[10px] font-bold text-blue-600 bg-blue-50 px-2 py-0.5 rounded-full border border-blue-200">
              Evaluated
            </span>
          </div>
          <div>
            <div className="text-2xl font-black text-[#0B1F33] font-mono">
              {summaryStats?.totalEvaluated ?? records.length}
            </div>
            <div className="text-xs font-bold text-slate-700 mt-0.5">Enrolled Students</div>
            <div className="text-[10px] text-slate-400 font-medium truncate mt-0.5">
              Active in Semester V
            </div>
          </div>
        </div>

        {/* Metric 2: Good Standing (>= 75%) */}
        <div className="p-4 rounded-xl bg-white border border-slate-200 shadow-2xs flex flex-col justify-between">
          <div className="flex items-center justify-between mb-2">
            <div className="w-8 h-8 rounded-lg bg-emerald-50 border border-emerald-100 text-emerald-600 flex items-center justify-center">
              <CheckCircle2 className="w-4 h-4" />
            </div>
            <span className="text-[10px] font-bold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-full border border-emerald-200">
              &ge; 75%
            </span>
          </div>
          <div>
            <div className="text-2xl font-black text-emerald-700 font-mono">
              {summaryStats?.goodStandingCount ?? 0}
            </div>
            <div className="text-xs font-bold text-slate-700 mt-0.5">Compliant / Eligible</div>
            <div className="text-[10px] text-emerald-600 font-medium truncate mt-0.5">
              Approved for Hall Ticket
            </div>
          </div>
        </div>

        {/* Metric 3: Warning Tier (70-74%) */}
        <div className="p-4 rounded-xl bg-white border border-slate-200 shadow-2xs flex flex-col justify-between">
          <div className="flex items-center justify-between mb-2">
            <div className="w-8 h-8 rounded-lg bg-amber-50 border border-amber-100 text-amber-600 flex items-center justify-center">
              <AlertTriangle className="w-4 h-4" />
            </div>
            <span className="text-[10px] font-bold text-amber-700 bg-amber-50 px-2 py-0.5 rounded-full border border-amber-200">
              70–74%
            </span>
          </div>
          <div>
            <div className="text-2xl font-black text-amber-600 font-mono">
              {summaryStats?.warningCount ?? 0}
            </div>
            <div className="text-xs font-bold text-slate-700 mt-0.5">Warning Tier</div>
            <div className="text-[10px] text-amber-600 font-medium truncate mt-0.5">
              Notice Dispatched
            </div>
          </div>
        </div>

        {/* Metric 4: Severe Shortage (< 65%) */}
        <div className="p-4 rounded-xl bg-white border border-slate-200 shadow-2xs flex flex-col justify-between">
          <div className="flex items-center justify-between mb-2">
            <div className="w-8 h-8 rounded-lg bg-rose-50 border border-rose-100 text-rose-600 flex items-center justify-center">
              <UserX className="w-4 h-4" />
            </div>
            <span className="text-[10px] font-bold text-rose-700 bg-rose-50 px-2 py-0.5 rounded-full border border-rose-200">
              &lt; 65%
            </span>
          </div>
          <div>
            <div className="text-2xl font-black text-rose-600 font-mono">
              {summaryStats?.criticalCount ?? 0}
            </div>
            <div className="text-xs font-bold text-slate-700 mt-0.5">Severe Shortage</div>
            <div className="text-[10px] text-rose-500 font-medium truncate mt-0.5">
              Debarment Candidate
            </div>
          </div>
        </div>
      </div>

      {/* 3. Filter 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">
          {/* Search Input */}
          <div className="lg:col-span-5">
            <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 by student name or roll number..."
                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>

          {/* Standing Filter */}
          <div className="lg:col-span-3">
            <label className="block text-[11px] font-semibold text-[#64748B] uppercase tracking-wider mb-1.5">
              Standing / Compliance
            </label>
            <select
              value={selectedStanding}
              onChange={(e) => setSelectedStanding(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 Standings</option>
              <option value="Dean">Dean&apos;s List (&ge; 90%)</option>
              <option value="Good">Good Standing (&ge; 75%)</option>
              <option value="Warning">Attendance Warning (70-74%)</option>
              <option value="Shortage">Severe Shortage (&lt; 65%)</option>
            </select>
          </div>

          {/* Batch Group */}
          <div className="lg:col-span-2">
            <label className="block text-[11px] font-semibold text-[#64748B] uppercase tracking-wider mb-1.5">
              Batch Group
            </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.map((b) => (
                <option key={b} value={b}>
                  {b}
                </option>
              ))}
            </select>
          </div>

          {/* Filter Action Buttons */}
          <div className="lg:col-span-2 flex items-center gap-2">
            <button
              onClick={() => fetchAcademicRecords()}
              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>

      {/* 4. 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">
          <span>Failed to connect to database for academic performance records. Ensure backend is running.</span>
          <button
            onClick={() => fetchAcademicRecords(true)}
            className="px-3 py-1 bg-rose-600 text-white rounded-md font-semibold hover:bg-rose-700 cursor-pointer"
          >
            Retry
          </button>
        </div>
      )}

      {/* 5. Academic Performance Records Table */}
      <div className="rounded-xl bg-white border border-[#E5EAF0] shadow-2xs overflow-hidden">
        <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">Roll No</th>
                <th className="py-3 px-3">Student Name</th>
                <th className="py-3 px-3">Program &amp; Semester</th>
                <th className="py-3 px-3">Batch Group</th>
                <th className="py-3 px-3 text-center">Contact Hours</th>
                <th className="py-3 px-3 text-center">Attendance %</th>
                <th className="py-3 px-3 text-center">Standing</th>
                <th className="py-3 px-3 text-center">Hall Ticket</th>
                <th className="py-3 px-3 text-right">Action</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#E5EAF0] text-[#334155]">
              {isLoading && records.length === 0 ? (
                <tr>
                  <td colSpan={9} 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 academic performance records from database...
                      </span>
                    </div>
                  </td>
                </tr>
              ) : filtered.length === 0 ? (
                <tr>
                  <td colSpan={9} className="py-12 text-center text-slate-400">
                    No student academic records found in active database.
                  </td>
                </tr>
              ) : (
                filtered.map((r) => (
                  <tr key={r.id} className="hover:bg-[#F8FAFC] transition-colors">
                    {/* Roll No */}
                    <td className="py-3.5 px-3 font-mono font-bold text-[#1769E8]">
                      {r.roll}
                    </td>

                    {/* Student Name */}
                    <td className="py-3.5 px-3 whitespace-nowrap">
                      <button
                        onClick={() => setViewingRecord(r)}
                        className="font-bold text-[#071A4D] hover:text-[#1769E8] transition-colors text-left cursor-pointer"
                      >
                        {r.name}
                      </button>
                    </td>

                    {/* Program & Semester */}
                    <td className="py-3.5 px-3 text-[#64748B]">
                      <span className="font-semibold text-slate-800">{r.course}</span> •{" "}
                      <span>{r.semester}</span>
                    </td>

                    {/* Batch */}
                    <td className="py-3.5 px-3">
                      <span className="inline-flex px-2 py-0.5 rounded font-bold text-[11px] bg-slate-100 text-slate-700 border border-slate-200">
                        {r.batch}
                      </span>
                    </td>

                    {/* Contact Hours (Attended / Conducted) */}
                    <td className="py-3.5 px-3 text-center font-mono">
                      <span className="font-bold text-slate-800">{r.attendedHours}h</span>{" "}
                      <span className="text-slate-400">/ {r.conductedHours}h</span>
                    </td>

                    {/* Attendance % */}
                    <td className="py-3.5 px-3 text-center">
                      <span
                        className={`font-mono font-bold text-xs ${r.attendancePercent >= 75
                          ? "text-emerald-700"
                          : r.attendancePercent >= 70
                            ? "text-amber-600"
                            : "text-rose-600"
                          }`}
                      >
                        {r.attendancePercent}%
                      </span>
                    </td>

                    {/* Standing Pill */}
                    <td className="py-3.5 px-3 text-center">
                      <span
                        className={`inline-block px-2.5 py-0.5 rounded-full text-[11px] font-semibold border ${r.standingColor}`}
                      >
                        {r.standing}
                      </span>
                    </td>

                    {/* Hall Ticket Eligibility */}
                    <td className="py-3.5 px-3 text-center">
                      <span
                        className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-bold ${r.isEligible
                          ? "bg-emerald-50 text-emerald-700 border border-emerald-200"
                          : "bg-rose-50 text-rose-700 border border-rose-200"
                          }`}
                      >
                        {r.isEligible ? (
                          <>
                            <CheckCircle2 className="w-3 h-3 text-emerald-600" />
                            <span>Eligible</span>
                          </>
                        ) : (
                          <>
                            <UserX className="w-3 h-3 text-rose-600" />
                            <span>Debarred</span>
                          </>
                        )}
                      </span>
                    </td>

                    {/* Action */}
                    <td className="py-3.5 px-3 text-right whitespace-nowrap">
                      <button
                        onClick={() => setViewingRecord(r)}
                        className="p-1.5 text-[#64748B] hover:text-[#1769E8] hover:bg-[#EFF6FF] rounded-md transition-colors cursor-pointer"
                        title="View Full Academic Card"
                      >
                        <Eye className="w-4 h-4" />
                      </button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* Table Footer */}
        <div className="p-4 border-t border-[#E5EAF0] flex items-center justify-between text-xs text-[#64748B]">
          <div>
            Showing {filtered.length} of {records.length} evaluated student records
          </div>
          <div className="font-mono text-[11px]">
            NCHMCT Statutory Bench: <span className="font-bold text-slate-800">75.0% Mandatory</span>
          </div>
        </div>
      </div>

      {/* 6. Complete Student Academic Dossier Modal */}
      {viewingRecord && (
        <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">
            {/* Modal Header */}
            <div className="bg-[#071A4D] px-6 py-5 text-white">
              <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">
                    <Award className="w-6 h-6 text-[#C8A45D]" />
                  </div>
                  <div>
                    <h3 className="font-heading font-bold text-lg text-white">
                      {viewingRecord.name}
                    </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: {viewingRecord.roll}
                      </span>
                      <span className={`text-[10px] font-bold px-2 py-0.5 rounded-full border ${viewingRecord.standingColor}`}>
                        {viewingRecord.standing}
                      </span>
                    </div>
                  </div>
                </div>

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

            {/* Modal Body */}
            <div className="p-6 space-y-4 text-xs">
              {/* Enrollment Info */}
              <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 Registration
                  </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]">
                      {viewingRecord.courseName} ({viewingRecord.course})
                    </span>
                  </div>
                  <div>
                    <span className="text-[11px] text-[#64748B] block">Semester:</span>
                    <span className="font-semibold text-xs text-[#071A4D]">
                      {viewingRecord.semester}
                    </span>
                  </div>
                  <div>
                    <span className="text-[11px] text-[#64748B] block">Kitchen/Lab Batch:</span>
                    <span className="font-semibold text-xs text-[#071A4D]">
                      {viewingRecord.batch}
                    </span>
                  </div>
                  <div>
                    <span className="text-[11px] text-[#64748B] block">Registered Subjects:</span>
                    <span className="font-semibold text-xs text-[#071A4D]">
                      {viewingRecord.subjectCount} Course Modules
                    </span>
                  </div>
                </div>
              </div>

              {/* Contact Hours Performance */}
              <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]">
                  <BookOpen className="w-4 h-4 text-[#1769E8]" />
                  <span className="font-heading text-xs uppercase tracking-wider">
                    Contact Hours &amp; Compliance
                  </span>
                </div>
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-slate-600">Total Curriculum Hours Delivered:</span>
                    <span className="font-mono font-bold text-slate-900">{viewingRecord.conductedHours} hrs</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-slate-600">Total Hours Attended / Condoned:</span>
                    <span className="font-mono font-bold text-emerald-700">{viewingRecord.attendedHours} hrs</span>
                  </div>
                  <div className="flex items-center justify-between pt-2 border-t border-slate-200">
                    <span className="text-slate-800 font-bold">Statutory Attendance Percentage:</span>
                    <span className={`font-mono font-black text-sm ${viewingRecord.attendancePercent >= 75 ? "text-emerald-700" : "text-rose-600"}`}>
                      {viewingRecord.attendancePercent}%
                    </span>
                  </div>
                </div>
              </div>

              {/* Examination Hall Ticket Decision */}
              <div className={`p-4 rounded-xl border flex items-center justify-between ${viewingRecord.isEligible ? "bg-emerald-50/50 border-emerald-200" : "bg-rose-50/50 border-rose-200"}`}>
                <div>
                  <div className="font-bold text-xs text-[#071A4D]">
                    NCHMCT End-Term Hall Ticket Status
                  </div>
                  <div className="text-[11px] text-[#64748B] mt-0.5">
                    {viewingRecord.isEligible
                      ? "Attendance fulfills statutory regulation. Hall ticket issued."
                      : "Attendance below 75% threshold. Debarred pending condonation review."}
                  </div>
                </div>
                <span className={`px-3 py-1 rounded-full text-xs font-bold ${viewingRecord.isEligible ? "bg-emerald-600 text-white" : "bg-rose-600 text-white"}`}>
                  {viewingRecord.isEligible ? "Approved" : "Debarred"}
                </span>
              </div>
            </div>

            {/* Modal Footer */}
            <div className="px-6 py-4 bg-[#F8FAFC] border-t border-[#E5EAF0] flex items-center justify-between">
              <div className="flex items-center gap-3">
                <Link
                  href={`/admin/people/students/details?id=${viewingRecord.id}`}
                  className="text-xs font-semibold text-[#1769E8] hover:underline flex items-center gap-1"
                >
                  <span>View Complete Details</span>
                  <span>→</span>
                </Link>
                <span className="text-slate-300">|</span>
                <Link
                  href={`/admin/people/students/edit?id=${viewingRecord.id}`}
                  className="text-xs font-semibold text-[#64748B] hover:text-[#071A4D]"
                >
                  Edit
                </Link>
              </div>
              <button
                onClick={() => setViewingRecord(null)}
                className="px-4 py-2 bg-slate-800 text-white hover:bg-slate-900 rounded-lg text-xs font-semibold transition-colors cursor-pointer"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
