"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  RefreshCw,
  Play,
  RotateCcw,
  CheckCircle2,
  AlertTriangle,
  ArrowRight,
  Database,
  FileSpreadsheet,
  Download,
  Search,
  Filter,
  Sparkles,
  ShieldCheck,
  Award,
  History,
  HeartPulse,
  FileCheck2,
  Sliders,
  FileText,
  Clock,
} from "lucide-react";
import { toast } from "sonner";

interface RecalcRecord {
  id: string;
  rollNumber: string;
  studentName: string;
  semester: string;
  totalHours: number;
  rawAttendedHours: number;
  rawPercentage: number;
  approvedMedicalHours: number;
  approvedCondonationHours: number;
  revisedPercentage: number;
  statusShift: "Eligible" | "Debarred";
  prevStatusShift: "Eligible" | "Debarred";
  syncedToAPR: boolean;
}

const initialRecalcData: RecalcRecord[] = [
  {
    id: "rec-01",
    rollNumber: "2441112003",
    studentName: "Chirag Banerjee",
    semester: "B.Sc H&HA Sem-IV",
    totalHours: 540,
    rawAttendedHours: 395,
    rawPercentage: 73.15,
    approvedMedicalHours: 12.0,
    approvedCondonationHours: 0.0,
    revisedPercentage: 75.37,
    statusShift: "Eligible",
    prevStatusShift: "Debarred",
    syncedToAPR: true,
  },
  {
    id: "rec-02",
    rollNumber: "2441112005",
    studentName: "Farhan Ahmed",
    semester: "B.Sc H&HA Sem-IV",
    totalHours: 540,
    rawAttendedHours: 398,
    rawPercentage: 73.7,
    approvedMedicalHours: 8.0,
    approvedCondonationHours: 0.0,
    revisedPercentage: 75.18,
    statusShift: "Eligible",
    prevStatusShift: "Debarred",
    syncedToAPR: true,
  },
  {
    id: "rec-03",
    rollNumber: "2441112009",
    studentName: "Jayant Verma",
    semester: "B.Sc H&HA Sem-VI",
    totalHours: 600,
    rawAttendedHours: 420,
    rawPercentage: 70.0,
    approvedMedicalHours: 32.0,
    approvedCondonationHours: 0.0,
    revisedPercentage: 75.33,
    statusShift: "Eligible",
    prevStatusShift: "Debarred",
    syncedToAPR: false,
  },
  {
    id: "rec-04",
    rollNumber: "2441112015",
    studentName: "Rohan Mukherjee",
    semester: "B.Sc H&HA Sem-II",
    totalHours: 520,
    rawAttendedHours: 330,
    rawPercentage: 63.46,
    approvedMedicalHours: 0.0,
    approvedCondonationHours: 0.0,
    revisedPercentage: 63.46,
    statusShift: "Debarred",
    prevStatusShift: "Debarred",
    syncedToAPR: true,
  },
  {
    id: "rec-05",
    rollNumber: "2441112022",
    studentName: "Ananya Iyer",
    semester: "B.Sc H&HA Sem-II",
    totalHours: 520,
    rawAttendedHours: 382,
    rawPercentage: 73.46,
    approvedMedicalHours: 10.0,
    approvedCondonationHours: 0.0,
    revisedPercentage: 75.38,
    statusShift: "Eligible",
    prevStatusShift: "Debarred",
    syncedToAPR: false,
  },
  {
    id: "rec-06",
    rollNumber: "2441112030",
    studentName: "Priyanka Bose",
    semester: "B.Sc H&HA Sem-VI",
    totalHours: 600,
    rawAttendedHours: 435,
    rawPercentage: 72.5,
    approvedMedicalHours: 0.0,
    approvedCondonationHours: 18.0,
    revisedPercentage: 75.5,
    statusShift: "Eligible",
    prevStatusShift: "Debarred",
    syncedToAPR: true,
  },
];

export default function AttendanceRecalculationPage() {
  const [records, setRecords] = useState<RecalcRecord[]>(initialRecalcData);
  const [selectedSemester, setSelectedSemester] = useState("All Semesters");
  const [searchQuery, setSearchQuery] = useState("");
  const [isRunning, setIsRunning] = useState(false);
  const [progress, setProgress] = useState(0);
  const [lastRunTime, setLastRunTime] = useState("Today, 12:30 PM");

  const filteredRecords = records.filter((r) => {
    const matchesSem =
      selectedSemester === "All Semesters" || r.semester.includes(selectedSemester);
    const matchesSearch =
      searchQuery === "" ||
      r.studentName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      r.rollNumber.includes(searchQuery);
    return matchesSem && matchesSearch;
  });

  const handleRunRecalculation = () => {
    setIsRunning(true);
    setProgress(15);
    toast.info("Initiating batch attendance recalculation engine...");

    const interval = setInterval(() => {
      setProgress((prev) => {
        if (prev >= 90) {
          clearInterval(interval);
          setTimeout(() => {
            setIsRunning(false);
            setProgress(100);
            setLastRunTime("Just now");
            toast.success("Recalculation complete! 5 student standings updated.");
          }, 400);
          return 95;
        }
        return prev + 25;
      });
    }, 250);
  };

  const handleSyncToAPR = () => {
    setRecords((prev) => prev.map((r) => ({ ...r, syncedToAPR: true })));
    toast.success("All revised percentages synchronized to APR & Monthly Matrix registers!");
  };

  const navTabs = [
    { label: "Requests", href: "/admin/adjustments/medical", icon: HeartPulse, active: false },
    { label: "Certificate Reference", href: "/admin/adjustments/medical/certificates", icon: FileCheck2, active: false },
    { label: "Approvals", href: "/admin/adjustments/medical/approvals", icon: CheckCircle2, active: false },
    { label: "Configurable %", href: "/admin/adjustments/medical/policy", icon: Sliders, active: false },
    { label: "Condonations", href: "/admin/adjustments/condonation", icon: FileText, active: false },
    { label: "Approved Hours", href: "/admin/adjustments/approved", icon: Award, active: false },
    { label: "Recalculation", href: "/admin/adjustments/recalculation", icon: RefreshCw, active: true },
    { label: "History", href: "/admin/adjustments/history", icon: History, active: false },
    { label: "Audit Trail", href: "/admin/adjustments/audit-trail", icon: ShieldCheck, active: false },
  ];

  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/adjustments/medical" className="hover:text-[#1769E8] transition-colors">
            Medical & Condonation
          </Link>
          <span>&gt;</span>
          <span className="text-[#071A4D] font-semibold">Automatic Attendance Recalculation</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">
              Automatic Attendance Recalculation Engine
            </h1>
            <p className="text-[15px] text-[#64748B] mt-1 font-normal">
              Execute real-time algorithmic attendance recalibration incorporating approved medical and condonation hours into academic standings.
            </p>
          </div>

          <div className="flex items-center gap-3">
            <button
              onClick={handleSyncToAPR}
              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"
            >
              <Database className="w-4 h-4 text-emerald-600" />
              <span>Sync to APR Register</span>
            </button>
            <button
              onClick={handleRunRecalculation}
              disabled={isRunning}
              className="px-5 py-2.5 bg-[#1769E8] hover:bg-[#1255be] text-white rounded-lg text-sm font-semibold transition-colors flex items-center gap-2 shadow-sm cursor-pointer disabled:opacity-50"
            >
              <Play className={`w-4 h-4 ${isRunning ? "animate-spin" : ""}`} />
              <span>{isRunning ? "Recalculating..." : "Run Batch Recalculation"}</span>
            </button>
          </div>
        </div>
      </div>

      {/* 2. Subcategory Navigation Tabs */}
      <div className="flex items-center gap-1.5 overflow-x-auto pb-1 border-b border-[#E2E8F0]">
        {navTabs.map((tab) => {
          const Icon = tab.icon;
          return (
            <Link
              key={tab.href}
              href={tab.href}
              className={`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-semibold whitespace-nowrap transition-all ${
                tab.active
                  ? "bg-[#081A2E] text-white shadow-xs"
                  : "bg-white text-[#64748B] hover:text-[#071A4D] hover:bg-slate-100 border border-[#E2E8F0]"
              }`}
            >
              <Icon className="w-3.5 h-3.5" />
              <span>{tab.label}</span>
            </Link>
          );
        })}
      </div>

      {/* 3. Progress Card if running */}
      {isRunning && (
        <div className="bg-white rounded-xl border border-[#1769E8]/30 shadow-md p-5 animate-in fade-in">
          <div className="flex items-center justify-between mb-2">
            <div className="flex items-center gap-2 font-bold text-sm text-[#071A4D]">
              <RefreshCw className="w-4 h-4 text-[#1769E8] animate-spin" />
              <span>Recalculating term attendance percentages...</span>
            </div>
            <span className="font-mono font-bold text-xs text-[#1769E8]">{progress}%</span>
          </div>
          <div className="w-full bg-slate-100 rounded-full h-2.5 overflow-hidden">
            <div
              className="bg-[#1769E8] h-2.5 rounded-full transition-all duration-300 ease-out"
              style={{ width: `${progress}%` }}
            />
          </div>
        </div>
      )}

      {/* 4. KPI Summary Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="bg-white p-4 rounded-xl border border-[#E5EAF0] shadow-xs flex items-center gap-3.5">
          <div className="w-10 h-10 rounded-lg bg-blue-50 border border-blue-200 flex items-center justify-center text-[#1769E8]">
            <RefreshCw className="w-5 h-5" />
          </div>
          <div>
            <div className="text-[11px] font-semibold text-[#64748B] uppercase tracking-wider">
              Last Recalculation
            </div>
            <div className="text-sm font-bold font-heading text-[#071A4D]">
              {lastRunTime}
            </div>
          </div>
        </div>

        <div className="bg-white p-4 rounded-xl border border-[#E5EAF0] shadow-xs flex items-center gap-3.5">
          <div className="w-10 h-10 rounded-lg bg-emerald-50 border border-emerald-200 flex items-center justify-center text-emerald-600">
            <CheckCircle2 className="w-5 h-5" />
          </div>
          <div>
            <div className="text-[11px] font-semibold text-[#64748B] uppercase tracking-wider">
              Converted to Eligible
            </div>
            <div className="text-xl font-bold font-heading text-emerald-700">
              5 Students
            </div>
          </div>
        </div>

        <div className="bg-white p-4 rounded-xl border border-[#E5EAF0] shadow-xs flex items-center gap-3.5">
          <div className="w-10 h-10 rounded-lg bg-purple-50 border border-purple-200 flex items-center justify-center text-purple-600">
            <Database className="w-5 h-5" />
          </div>
          <div>
            <div className="text-[11px] font-semibold text-[#64748B] uppercase tracking-wider">
              Total Adjusted Hours
            </div>
            <div className="text-xl font-bold font-heading text-purple-700">
              +70.0 Hours
            </div>
          </div>
        </div>

        <div className="bg-white p-4 rounded-xl border border-[#E5EAF0] shadow-xs flex items-center gap-3.5">
          <div className="w-10 h-10 rounded-lg bg-amber-50 border border-amber-200 flex items-center justify-center text-amber-600">
            <Clock className="w-5 h-5" />
          </div>
          <div>
            <div className="text-[11px] font-semibold text-[#64748B] uppercase tracking-wider">
              Pending APR Sync
            </div>
            <div className="text-xl font-bold font-heading text-amber-700">
              {records.filter((r) => !r.syncedToAPR).length} Records
            </div>
          </div>
        </div>
      </div>

      {/* 5. 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">
              Filter by 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>All Semesters</option>
              <option>Sem-II</option>
              <option>Sem-IV</option>
              <option>Sem-VI</option>
            </select>
          </div>

          <div className="lg:col-span-7">
            <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 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 student name or roll number..."
                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(`Showing ${filteredRecords.length} 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>Filter</span>
            </button>
            <button
              onClick={() => {
                setSelectedSemester("All Semesters");
                setSearchQuery("");
                toast.info("Reset filters");
              }}
              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"
            >
              <RotateCcw className="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>

      {/* 6. Differential Recalculation Table */}
      <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs overflow-hidden">
        <div className="p-4 border-b border-[#E5EAF0] flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Sparkles className="w-5 h-5 text-amber-500" />
            <h2 className="font-heading font-bold text-lg text-[#071A4D]">
              Attendance Recalculation Ledger ({filteredRecords.length})
            </h2>
          </div>
          <span className="text-xs text-[#64748B]">
            Formula: [(Attended Hours + Credited Hours) ÷ Term Hours] × 100
          </span>
        </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-8 text-center">#</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D]">Roll Number</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D]">Student Name & Batch</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Term Total</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Raw Attendance</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Approved Credit</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Recalculated %</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Standing Shift</th>
                <th className="py-3 px-4 font-bold text-[#071A4D] text-right">APR Sync</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#E5EAF0]">
              {filteredRecords.length === 0 ? (
                <tr>
                  <td colSpan={9} className="py-12 text-center text-slate-400">
                    No recalculation records match criteria.
                  </td>
                </tr>
              ) : (
                filteredRecords.map((r, idx) => {
                  const gained = (r.revisedPercentage - r.rawPercentage).toFixed(2);
                  return (
                    <tr key={r.id} className="hover:bg-[#F8FAFC] transition-colors">
                      <td className="py-3.5 px-3.5 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]">
                          {r.rollNumber}
                        </span>
                      </td>
                      <td className="py-3.5 px-3.5">
                        <div className="font-bold text-[#071A4D] text-sm">{r.studentName}</div>
                        <div className="text-[11px] text-[#64748B]">{r.semester}</div>
                      </td>
                      <td className="py-3.5 px-3.5 text-center font-mono font-bold text-[#475569]">
                        {r.totalHours}h
                      </td>
                      <td className="py-3.5 px-3.5 text-center">
                        <div className="font-mono font-bold text-[#071A4D]">
                          {r.rawPercentage.toFixed(2)}%
                        </div>
                        <div className="text-[10px] text-[#64748B]">
                          ({r.rawAttendedHours}h attended)
                        </div>
                      </td>
                      <td className="py-3.5 px-3.5 text-center font-mono">
                        <div className="font-bold text-emerald-600">
                          +{r.approvedMedicalHours + r.approvedCondonationHours}h
                        </div>
                        <div className="text-[10px] text-[#64748B]">
                          {r.approvedMedicalHours > 0 ? `Med: ${r.approvedMedicalHours}h` : ""}
                          {r.approvedCondonationHours > 0 ? `Cond: ${r.approvedCondonationHours}h` : ""}
                        </div>
                      </td>
                      <td className="py-3.5 px-3.5 text-center">
                        <div className="font-mono font-bold text-sm text-[#071A4D]">
                          {r.revisedPercentage.toFixed(2)}%
                        </div>
                        <div className="text-[10px] font-bold text-emerald-600">
                          +{gained}% Boost
                        </div>
                      </td>
                      <td className="py-3.5 px-3.5 text-center">
                        {r.prevStatusShift === "Debarred" && r.statusShift === "Eligible" ? (
                          <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">
                            <span className="line-through text-rose-500 font-normal">Debarred</span>
                            <ArrowRight className="w-3 h-3 text-emerald-600" />
                            <span>Eligible</span>
                          </span>
                        ) : (
                          <span
                            className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-[11px] font-bold border ${
                              r.statusShift === "Eligible"
                                ? "bg-emerald-50 text-emerald-700 border-emerald-200"
                                : "bg-rose-50 text-rose-700 border-rose-200"
                            }`}
                          >
                            {r.statusShift}
                          </span>
                        )}
                      </td>
                      <td className="py-3.5 px-4 text-right">
                        {r.syncedToAPR ? (
                          <span className="inline-flex items-center gap-1 text-[11px] font-bold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200">
                            <CheckCircle2 className="w-3 h-3" />
                            Synced
                          </span>
                        ) : (
                          <button
                            onClick={() => {
                              setRecords((prev) =>
                                prev.map((item) =>
                                  item.id === r.id ? { ...item, syncedToAPR: true } : item
                                )
                              );
                              toast.success(`Synced ${r.rollNumber} to APR register`);
                            }}
                            className="px-2.5 py-1 bg-amber-500 hover:bg-amber-600 text-white rounded text-[10px] font-bold cursor-pointer"
                          >
                            Push to APR
                          </button>
                        )}
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
