"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  Search,
  RotateCcw,
  Plus,
  Eye,
  Trash2,
  ChevronLeft,
  ChevronRight,
  FileSpreadsheet,
  FileText,
  FileCheck2,
  Lock,
  Printer,
  Sparkles,
  ShieldCheck,
  CheckCircle2,
  AlertTriangle,
} from "lucide-react";
import { toast } from "sonner";

interface APRStudentSnapshotItem {
  studentId: string;
  nchmRollNumber: string;
  studentName: string;
  theoryHoursConducted: number;
  theoryHoursAttended: number;
  practicalHoursConducted: number;
  practicalHoursAttended: number;
  totalConducted: number;
  totalAttended: number;
  condonationHours: number;
  approvedMedicalHours: number;
  aggregatePercentage: number;
  isExcluded: boolean;
}

const mockAPRStudents: APRStudentSnapshotItem[] = [
  {
    studentId: "s-101",
    nchmRollNumber: "2441112001",
    studentName: "Aaron Smith",
    theoryHoursConducted: 20.0,
    theoryHoursAttended: 18.0,
    practicalHoursConducted: 40.0,
    practicalHoursAttended: 36.0,
    totalConducted: 60.0,
    totalAttended: 54.0,
    condonationHours: 0,
    approvedMedicalHours: 0,
    aggregatePercentage: 90.0,
    isExcluded: false,
  },
  {
    studentId: "s-102",
    nchmRollNumber: "2441112002",
    studentName: "Bethany Roy",
    theoryHoursConducted: 20.0,
    theoryHoursAttended: 16.0,
    practicalHoursConducted: 40.0,
    practicalHoursAttended: 32.0,
    totalConducted: 60.0,
    totalAttended: 48.0,
    condonationHours: 0,
    approvedMedicalHours: 0,
    aggregatePercentage: 80.0,
    isExcluded: false,
  },
  {
    studentId: "s-103",
    nchmRollNumber: "2441112003",
    studentName: "Chirag Banerjee",
    theoryHoursConducted: 20.0,
    theoryHoursAttended: 15.0,
    practicalHoursConducted: 40.0,
    practicalHoursAttended: 32.0,
    totalConducted: 60.0,
    totalAttended: 47.0,
    condonationHours: 2.0,
    approvedMedicalHours: 0,
    aggregatePercentage: 81.7,
    isExcluded: false,
  },
  {
    studentId: "s-104",
    nchmRollNumber: "2441112004",
    studentName: "Devika Sharma",
    theoryHoursConducted: 20.0,
    theoryHoursAttended: 12.0,
    practicalHoursConducted: 40.0,
    practicalHoursAttended: 24.0,
    totalConducted: 60.0,
    totalAttended: 36.0,
    condonationHours: 0,
    approvedMedicalHours: 0,
    aggregatePercentage: 60.0,
    isExcluded: false,
  },
  {
    studentId: "s-199",
    nchmRollNumber: "2441112099",
    studentName: "Rohan Varma",
    theoryHoursConducted: 20.0,
    theoryHoursAttended: 2.0,
    practicalHoursConducted: 40.0,
    practicalHoursAttended: 4.0,
    totalConducted: 60.0,
    totalAttended: 6.0,
    condonationHours: 0,
    approvedMedicalHours: 0,
    aggregatePercentage: 10.0,
    isExcluded: true,
  },
];

export default function APRManagementPage() {
  const [students, setStudents] = useState<APRStudentSnapshotItem[]>(mockAPRStudents);
  const [selectedTerm, setSelectedTerm] = useState("OCT-2026");
  const [selectedSemester, setSelectedSemester] = useState("Semester III");
  const [selectedStatus, setSelectedStatus] = useState("All Cohort");
  const [searchQuery, setSearchQuery] = useState("");
  const [isLocked, setIsLocked] = useState(false);
  const [sha256Hash, setSha256Hash] = useState<string | null>(null);
  const [selectedRows, setSelectedRows] = useState<string[]>([]);
  const [pageSize, setPageSize] = useState("10");

  const filteredStudents = students.filter((s) => {
    const isEligible = s.aggregatePercentage >= 75.0 && !s.isExcluded;
    const matchesStatus =
      selectedStatus === "All Cohort" ||
      (selectedStatus === "Eligible (>= 75%)" && isEligible) ||
      (selectedStatus === "Debarred (< 75%)" && !isEligible);
    const matchesSearch =
      searchQuery === "" ||
      s.studentName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      s.nchmRollNumber.includes(searchQuery);
    return matchesStatus && matchesSearch;
  });

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

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

  const handleResetFilters = () => {
    setSelectedTerm("OCT-2026");
    setSelectedSemester("Semester III");
    setSelectedStatus("All Cohort");
    setSearchQuery("");
    toast.info("Filters reset to default");
  };

  const handleFreezeSnapshot = () => {
    const hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
    setSha256Hash(hash);
    setIsLocked(true);
    toast.success("APR Snapshot frozen and cryptographically sealed with SHA-256 hash.");
  };

  return (
    <div className="space-y-6 pb-12 font-sans bg-[#F8FAFC] min-h-screen">
      {/* 1. Header Bar */}
      <div>
        <div className="flex items-center gap-2 text-xs text-[#64748B] mb-2 font-medium">
          <Link href="/admin/dashboard" className="hover:text-[#1769E8] transition-colors">
            Home
          </Link>
          <span>&gt;</span>
          <Link href="/admin/reports/monthly-matrix" className="hover:text-[#1769E8] transition-colors">
            Reports &amp; Analytics
          </Link>
          <span>&gt;</span>
          <span className="text-[#071A4D] font-semibold">Attendance Performance Report (APR)</span>
        </div>

        <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">
              Attendance Performance Report (APR)
            </h1>
            <p className="text-[15px] text-[#64748B] mt-1 font-normal">
              Official statutory attendance snapshots, theory vs. practical contact hour splits, and tamper-evident cryptographic freeze.
            </p>
          </div>

          <div className="flex items-center gap-3">
            <button
              onClick={() => toast.success("Exporting APR statutory report to Excel...")}
              className="px-4 py-2 bg-white border border-[#E2E8F0] rounded-lg text-sm font-medium text-[#334155] hover:bg-slate-50 transition-colors flex items-center gap-2 shadow-xs cursor-pointer"
            >
              <FileSpreadsheet className="w-4 h-4 text-emerald-600" />
              <span>Export</span>
            </button>
            <button
              onClick={() => toast.info("Generating printable NCHMCT PDF Document...")}
              className="px-4 py-2 bg-white border border-[#E2E8F0] rounded-lg text-sm font-medium text-[#334155] hover:bg-slate-50 transition-colors flex items-center gap-2 shadow-xs cursor-pointer"
            >
              <Printer className="w-4 h-4 text-purple-600" />
              <span>Preview PDF</span>
            </button>
            <button
              onClick={handleFreezeSnapshot}
              disabled={isLocked}
              className={`px-5 py-2.5 text-white rounded-lg text-sm font-semibold transition-colors flex items-center gap-2 shadow-sm cursor-pointer ${
                isLocked ? "bg-emerald-600" : "bg-[#1769E8] hover:bg-[#1255be]"
              }`}
            >
              <Lock className="w-4 h-4" />
              <span>{isLocked ? "Snapshot Frozen" : "Freeze & Lock APR"}</span>
            </button>
          </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">
          <div className="lg:col-span-3">
            <label className="block text-[11px] font-semibold text-[#64748B] uppercase tracking-wider mb-1.5">
              Snapshot Term
            </label>
            <select
              value={selectedTerm}
              onChange={(e) => setSelectedTerm(e.target.value)}
              className="w-full bg-white border border-[#E2E8F0] text-sm text-[#0F172A] rounded-lg px-3 py-2 font-medium focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all cursor-pointer font-mono"
            >
              <option>OCT-2026</option>
              <option>SEP-2026</option>
              <option>AUG-2026</option>
            </select>
          </div>

          <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 bg-white border border-[#E2E8F0] text-sm text-[#0F172A] rounded-lg px-3 py-2 font-medium focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all cursor-pointer"
            >
              <option>Semester I</option>
              <option>Semester III</option>
              <option>Semester V</option>
            </select>
          </div>

          <div className="lg:col-span-4">
            <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)}
                placeholder="Search by student name or NCHM roll..."
                className="w-full pl-9 pr-3 py-2 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>

          <div className="lg:col-span-2 flex items-center gap-2">
            <button
              onClick={() => toast.success(`Found ${filteredStudents.length} snapshot records`)}
              className="flex-1 bg-[#1769E8] hover:bg-[#1255be] text-white py-2 rounded-lg text-sm font-semibold transition-colors flex items-center justify-center gap-1.5 shadow-xs cursor-pointer"
            >
              <Search className="w-4 h-4" />
              <span>Search</span>
            </button>
            <button
              onClick={handleResetFilters}
              className="border border-[#E2E8F0] hover:bg-slate-50 text-[#64748B] p-2 rounded-lg text-sm font-medium transition-colors flex items-center justify-center cursor-pointer"
              title="Reset Filters"
            >
              <RotateCcw className="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>

      {/* 3. Main Split Layout */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
        {/* Left (8 cols): Table */}
        <div className="lg:col-span-8 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">
              <FileCheck2 className="w-5 h-5 text-[#1769E8]" />
              <h2 className="font-heading font-bold text-lg text-[#071A4D]">
                Statutory APR Snapshot ({filteredStudents.length})
              </h2>
            </div>
            <div className="flex items-center gap-2">
              <select
                value={pageSize}
                onChange={(e) => setPageSize(e.target.value)}
                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>
              </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] font-semibold">
                  <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.5 font-bold text-[#071A4D]">Roll No</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D]">Student Name</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Theory Hours</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Practical Hours</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Adjustments</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Aggregate %</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Status</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-[#E5EAF0]">
                {filteredStudents.length === 0 ? (
                  <tr>
                    <td colSpan={9} className="py-12 text-center text-slate-400">
                      No student records found in this snapshot.
                    </td>
                  </tr>
                ) : (
                  filteredStudents.map((s, idx) => {
                    const isEligible = s.aggregatePercentage >= 75.0 && !s.isExcluded;
                    return (
                      <tr
                        key={s.studentId}
                        className={`hover:bg-[#F8FAFC] transition-colors ${
                          selectedRows.includes(s.studentId) ? "bg-[#EFF6FF]/40" : ""
                        }`}
                      >
                        <td className="py-3.5 px-3.5 text-center">
                          <input
                            type="checkbox"
                            checked={selectedRows.includes(s.studentId)}
                            onChange={() => handleRowSelect(s.studentId)}
                            className="rounded border-[#CBD5E1] text-[#1769E8] focus:ring-0 cursor-pointer"
                          />
                        </td>
                        <td className="py-3.5 px-2 text-center text-[#94A3B8] font-medium">
                          {idx + 1}
                        </td>
                        <td className="py-3.5 px-3.5 font-mono font-bold text-xs">
                          <span className="bg-[#F1F6FC] text-[#1769E8] px-2 py-0.5 rounded border border-[#D0E2FF]">
                            {s.nchmRollNumber}
                          </span>
                        </td>
                        <td className="py-3.5 px-3.5">
                          <div className="font-bold text-[#071A4D] text-sm">
                            {s.studentName}
                          </div>
                          {s.isExcluded && (
                            <div className="text-[10px] text-rose-600 font-semibold">
                              Exclusion Policy Disqualified
                            </div>
                          )}
                        </td>
                        <td className="py-3.5 px-3.5 text-center font-mono">
                          <div className="font-bold text-[#071A4D]">
                            {s.theoryHoursAttended}h / {s.theoryHoursConducted}h
                          </div>
                          <div className="text-[10px] text-[#64748B]">
                            {((s.theoryHoursAttended / s.theoryHoursConducted) * 100).toFixed(0)}%
                          </div>
                        </td>
                        <td className="py-3.5 px-3.5 text-center font-mono">
                          <div className="font-bold text-[#071A4D]">
                            {s.practicalHoursAttended}h / {s.practicalHoursConducted}h
                          </div>
                          <div className="text-[10px] text-[#64748B]">
                            {((s.practicalHoursAttended / s.practicalHoursConducted) * 100).toFixed(0)}%
                          </div>
                        </td>
                        <td className="py-3.5 px-3.5 text-center font-mono text-emerald-600 font-bold">
                          +{s.condonationHours + s.approvedMedicalHours}h
                        </td>
                        <td className="py-3.5 px-3.5 text-center font-mono font-bold text-sm text-[#071A4D]">
                          {s.aggregatePercentage.toFixed(1)}%
                        </td>
                        <td className="py-3.5 px-3.5 text-center">
                          <span
                            className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-[10px] font-bold border ${
                              isEligible
                                ? "bg-[#DCFCE7] text-[#15803D] border-[#BBF7D0]"
                                : "bg-[#FEE2E2] text-[#DC2626] border-[#FECACA]"
                            }`}
                          >
                            {isEligible ? "Eligible (Admit Card)" : "Debarred"}
                          </span>
                        </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 1 to {filteredStudents.length} of {students.length} students
            </div>
            <div className="flex items-center gap-1">
              <button className="p-1.5 border border-[#E2E8F0] rounded-md hover:bg-slate-50 transition-colors cursor-pointer">
                <ChevronLeft className="w-3.5 h-3.5" />
              </button>
              <button className="px-3 py-1 bg-[#1769E8] text-white font-bold rounded-md text-xs">
                1
              </button>
              <button className="p-1.5 border border-[#E2E8F0] rounded-md hover:bg-slate-50 transition-colors cursor-pointer">
                <ChevronRight className="w-3.5 h-3.5" />
              </button>
            </div>
          </div>
        </div>

        {/* Right (4 cols): Snapshot Freeze & Guidelines */}
        <div className="lg:col-span-4 space-y-5">
          <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs p-5">
            <div className="flex items-center justify-between pb-3 mb-4 border-b border-[#E5EAF0]">
              <div className="flex items-center gap-2">
                <ShieldCheck className="w-4 h-4 text-[#1769E8]" />
                <h3 className="font-heading font-bold text-base text-[#071A4D]">
                  Snapshot Cryptographic Seal
                </h3>
              </div>
              <span
                className={`text-[10px] font-bold px-2 py-0.5 rounded-full border ${
                  isLocked
                    ? "bg-emerald-50 text-emerald-700 border-emerald-200"
                    : "bg-amber-50 text-amber-700 border-amber-200"
                }`}
              >
                {isLocked ? "SEALED" : "DRAFT"}
              </span>
            </div>

            <div className="space-y-3.5 text-xs">
              <div className="p-3 bg-[#F8FAFC] rounded-lg border border-[#E2E8F0] space-y-1.5">
                <div className="text-[#64748B] font-medium">Selected Term</div>
                <div className="font-bold text-[#071A4D] font-mono text-sm">
                  {selectedTerm} • {selectedSemester}
                </div>
              </div>

              <div>
                <span className="block font-semibold text-[#334155] mb-1">
                  SHA-256 Tamper-Evident Hash
                </span>
                <div className="p-2.5 bg-slate-50 border border-[#E2E8F0] rounded-lg font-mono text-[11px] text-[#475569] break-all leading-tight">
                  {sha256Hash || "Snapshot not yet frozen. Click lock to seal records."}
                </div>
              </div>

              <div className="pt-2">
                <button
                  type="button"
                  onClick={handleFreezeSnapshot}
                  disabled={isLocked}
                  className={`w-full py-2.5 px-3 text-white rounded-lg text-xs font-semibold transition-colors flex items-center justify-center gap-1.5 shadow-xs cursor-pointer ${
                    isLocked ? "bg-emerald-600 opacity-90 cursor-not-allowed" : "bg-[#1769E8] hover:bg-[#1255be]"
                  }`}
                >
                  <Lock className="w-3.5 h-3.5" />
                  <span>{isLocked ? "Cryptographically Locked" : "Freeze & Generate SHA-256"}</span>
                </button>
              </div>
            </div>
          </div>

          {/* Guidelines Card */}
          <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs p-4 text-xs">
            <div className="flex items-center gap-2 font-bold text-[#071A4D] mb-2.5 pb-2 border-b border-[#E5EAF0]">
              <Sparkles className="w-4 h-4 text-amber-500" />
              <span>NCHMCT APR Regulatory Formula</span>
            </div>
            <div className="space-y-2 text-[#475569]">
              <div className="flex items-center justify-between">
                <span className="font-medium">Regulatory Attendance Formula</span>
                <span className="font-mono font-bold text-[#071A4D]">(P+C+M)/C &times; 100</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="font-medium">Exam Admit Card Threshold</span>
                <span className="font-mono font-bold text-[#1769E8]">&ge; 75.0%</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="font-medium">Direct Exclusion Floor</span>
                <span className="font-mono font-bold text-rose-600">&lt; 20.0%</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="font-medium">Council Data Submission</span>
                <span className="font-mono font-bold text-emerald-600">Electronic XML</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
