"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  FileSpreadsheet,
  Download,
  Lock,
  RefreshCw,
  CheckCircle2,
  AlertTriangle,
  ChevronRight,
  ShieldCheck,
  Calendar,
  Sparkles,
  Award,
} from "lucide-react";
import { toast } from "sonner";

interface APRStudentEntry {
  rollNo: string;
  name: string;
  semester: number;
  batch: string;
  totalHeld: number;
  attendedRaw: number;
  medicalCredits: number;
  finalAttended: number;
  finalPct: number;
  boardStatus: "ELIGIBLE" | "CONDONATION_REQ" | "DETAINED";
}

export default function DeptAdminAPRPage() {
  const [selectedSem, setSelectedSem] = useState<number>(1);
  const [isLocked, setIsLocked] = useState(false);
  const [isCalculating, setIsCalculating] = useState(false);

  const [aprData, setAprData] = useState<APRStudentEntry[]>([
    {
      rollNo: "2441112001",
      name: "Aarav Sharma",
      semester: 1,
      batch: "Kitchen Batch K1",
      totalHeld: 130,
      attendedRaw: 115,
      medicalCredits: 0,
      finalAttended: 115,
      finalPct: 88.5,
      boardStatus: "ELIGIBLE",
    },
    {
      rollNo: "2441112002",
      name: "Ananya Mukherjee",
      semester: 1,
      batch: "Kitchen Batch K1",
      totalHeld: 130,
      attendedRaw: 111,
      medicalCredits: 9,
      finalAttended: 120,
      finalPct: 92.3,
      boardStatus: "ELIGIBLE",
    },
    {
      rollNo: "2441112015",
      name: "Debashis Sen",
      semester: 3,
      batch: "Kitchen Batch Q1",
      totalHeld: 148,
      attendedRaw: 105,
      medicalCredits: 14,
      finalAttended: 119,
      finalPct: 80.4,
      boardStatus: "ELIGIBLE",
    },
    {
      rollNo: "2441112061",
      name: "Roshni Paul",
      semester: 1,
      batch: "Kitchen Batch K1",
      totalHeld: 130,
      attendedRaw: 94,
      medicalCredits: 0,
      finalAttended: 94,
      finalPct: 72.3,
      boardStatus: "CONDONATION_REQ",
    },
    {
      rollNo: "2441112078",
      name: "Tanmay Ghosh",
      semester: 1,
      batch: "Kitchen Batch K2",
      totalHeld: 130,
      attendedRaw: 81,
      medicalCredits: 0,
      finalAttended: 81,
      finalPct: 62.3,
      boardStatus: "DETAINED",
    },
  ]);

  const filtered = aprData.filter((d) => d.semester === selectedSem);

  const handleRunCalculation = () => {
    setIsCalculating(true);
    setTimeout(() => {
      setIsCalculating(false);
      toast.success(`Batch APR calculation complete for Semester ${selectedSem}. Medical adjustments incorporated.`);
    }, 800);
  };

  const handleLockAPR = () => {
    setIsLocked(!isLocked);
    toast.success(
      isLocked
        ? "APR unlocked for departmental modifications"
        : "APR frozen and verified for NCHMCT Examination Board submission"
    );
  };

  const handleDownload = () => {
    toast.success("Downloading official NCHMCT APR Excel register");
  };

  return (
    <div className="p-4 sm:p-6 lg:p-8 space-y-6 max-w-7xl mx-auto">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <div className="flex items-center gap-2 text-xs font-semibold text-slate-500 mb-1">
            <Link href="/dept-admin/dashboard" className="hover:text-[#1769E8]">
              Dashboard
            </Link>
            <ChevronRight className="w-3.5 h-3.5" />
            <span className="text-[#071A4D] font-bold">APR Generation</span>
          </div>
          <h1 className="text-xl sm:text-2xl font-black text-[#071A4D] tracking-tight">
            Academic Performance & Attendance Progress Report (APR)
          </h1>
          <p className="text-xs text-slate-500 mt-0.5">
            Official NCHMCT examination eligibility register incorporating certified medical concessions
          </p>
        </div>

        <div className="flex items-center gap-2">
          <button
            onClick={handleDownload}
            className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg border border-slate-200 bg-white hover:bg-slate-50 text-slate-700 text-xs font-bold transition-all"
          >
            <Download className="w-3.5 h-3.5" />
            <span>Export Official Format</span>
          </button>
          <button
            onClick={handleRunCalculation}
            disabled={isCalculating}
            className="inline-flex items-center gap-2 px-4 py-2.5 rounded-lg bg-[#C8A45D] hover:bg-[#B38F48] text-slate-950 font-bold text-xs shadow-sm transition-all"
          >
            <RefreshCw className={`w-4 h-4 ${isCalculating ? "animate-spin" : ""}`} />
            <span>Recalculate APR</span>
          </button>
        </div>
      </div>

      {/* Compliance Status Banner */}
      <div className="p-5 rounded-xl bg-gradient-to-r from-[#081A2E] to-[#123154] text-white shadow-md border border-[#1E3A5F] flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div className="space-y-1">
          <div className="inline-flex items-center gap-2 px-2.5 py-0.5 rounded-full bg-[#C8A45D]/20 border border-[#C8A45D]/40 text-amber-200 text-[10px] font-bold uppercase">
            <Award className="w-3 h-3 text-[#C8A45D]" />
            NCHMCT Examination Protocol
          </div>
          <h2 className="text-lg font-bold text-white">
            Semester {selectedSem} — Academic Session AY-2024-25-ODD
          </h2>
          <p className="text-xs text-slate-300">
            Admit cards are auto-cleared for students with &gt;= 75% attendance after approved medical credits.
          </p>
        </div>

        <div className="flex items-center gap-3 shrink-0">
          <button
            onClick={handleLockAPR}
            className={`px-4 py-2.5 rounded-lg text-xs font-bold transition-all flex items-center gap-2 ${
              isLocked
                ? "bg-rose-500 hover:bg-rose-600 text-white"
                : "bg-emerald-600 hover:bg-emerald-700 text-white"
            }`}
          >
            <Lock className="w-4 h-4" />
            <span>{isLocked ? "Unlock Register" : "Freeze & Lock APR"}</span>
          </button>
        </div>
      </div>

      {/* Semester Selector */}
      <div className="flex items-center gap-3 bg-white p-3 rounded-xl border border-slate-200 shadow-xs">
        <span className="text-xs font-bold text-slate-700">Select APR Cohort:</span>
        {[1, 3, 5].map((sem) => (
          <button
            key={sem}
            onClick={() => setSelectedSem(sem)}
            className={`px-3 py-1.5 rounded-lg text-xs font-bold transition-all ${
              selectedSem === sem
                ? "bg-[#081A2E] text-[#C8A45D]"
                : "bg-slate-100 text-slate-600 hover:bg-slate-200"
            }`}
          >
            Semester {sem} (Odd Term)
          </button>
        ))}
      </div>

      {/* APR Table */}
      <div className="bg-white rounded-xl border border-slate-200 shadow-xs overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs">
            <thead className="bg-[#081A2E] text-slate-200 uppercase tracking-wider text-[10px]">
              <tr>
                <th className="p-3.5">Roll Number</th>
                <th className="p-3.5">Candidate Name</th>
                <th className="p-3.5">Total Held</th>
                <th className="p-3.5">Raw Attended</th>
                <th className="p-3.5">Medical Adjustments</th>
                <th className="p-3.5">Final Attended</th>
                <th className="p-3.5">Final APR %</th>
                <th className="p-3.5">NCHMCT Board Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {filtered.map((item) => (
                <tr key={item.rollNo} className="hover:bg-slate-50/80 transition-colors">
                  <td className="p-3.5 font-mono font-bold text-[#071A4D]">
                    {item.rollNo}
                  </td>
                  <td className="p-3.5 font-bold text-slate-900">
                    {item.name}
                  </td>
                  <td className="p-3.5 font-mono text-slate-600">
                    {item.totalHeld}
                  </td>
                  <td className="p-3.5 font-mono text-slate-600">
                    {item.attendedRaw}
                  </td>
                  <td className="p-3.5 font-mono text-slate-700">
                    {item.medicalCredits > 0 ? (
                      <span className="text-emerald-700 font-bold bg-emerald-50 px-2 py-0.5 rounded-md">
                        +{item.medicalCredits} Sessions
                      </span>
                    ) : (
                      <span className="text-slate-400">—</span>
                    )}
                  </td>
                  <td className="p-3.5 font-mono font-bold text-slate-900">
                    {item.finalAttended}
                  </td>
                  <td className="p-3.5 font-mono font-black text-sm">
                    <span
                      className={
                        item.finalPct >= 75
                          ? "text-emerald-700"
                          : item.finalPct >= 65
                          ? "text-amber-700"
                          : "text-rose-600"
                      }
                    >
                      {item.finalPct}%
                    </span>
                  </td>
                  <td className="p-3.5">
                    <span
                      className={`px-2.5 py-0.5 rounded-full font-bold text-[10px] uppercase ${
                        item.boardStatus === "ELIGIBLE"
                          ? "bg-emerald-100 text-emerald-800 border border-emerald-300"
                          : item.boardStatus === "CONDONATION_REQ"
                          ? "bg-amber-100 text-amber-900 border border-amber-300"
                          : "bg-rose-100 text-rose-900 border border-rose-300"
                      }`}
                    >
                      {item.boardStatus === "ELIGIBLE"
                        ? "Admit Card Eligible (>=75%)"
                        : item.boardStatus === "CONDONATION_REQ"
                        ? "Condonation Required (65-74%)"
                        : "Detained / Debarred (<65%)"}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
