"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  ShieldCheck,
  Search,
  RotateCcw,
  Download,
  Filter,
  CheckCircle2,
  XCircle,
  FileCheck2,
  HeartPulse,
  Sliders,
  FileText,
  Award,
  RefreshCw,
  History,
  Clock,
  UserCheck,
  Lock,
  ArrowRight,
  ChevronLeft,
  ChevronRight,
  ExternalLink,
} from "lucide-react";
import { toast } from "sonner";

interface AuditEntry {
  id: string;
  timestamp: string;
  actionType: "Claim Submitted" | "CMO Endorsement" | "Admin Approval" | "Claim Rejected" | "Recalculation Triggered" | "Condonation Signed";
  rollNumber: string;
  studentName: string;
  actorName: string;
  actorRole: string;
  ipAddress: string;
  changeSummary: string;
  justification: string;
  securityHash: string;
}

const initialAuditLogs: AuditEntry[] = [
  {
    id: "AUD-MED-9014",
    timestamp: "2026-10-15 11:42:18",
    actionType: "Recalculation Triggered",
    rollNumber: "2441112003",
    studentName: "Chirag Banerjee",
    actorName: "Super Admin",
    actorRole: "System Administrator",
    ipAddress: "192.168.1.12",
    changeSummary: "Standing updated: 73.15% ➔ 75.37% (Debarred ➔ Eligible)",
    justification: "Batch recalculation executed after +12.0h medical credit",
    securityHash: "SHA256: 4f8a...c91d",
  },
  {
    id: "AUD-MED-9012",
    timestamp: "2026-10-14 16:20:05",
    actionType: "Admin Approval",
    rollNumber: "2441112003",
    studentName: "Chirag Banerjee",
    actorName: "Dr. A. K. Roy",
    actorRole: "Dean of Academics",
    ipAddress: "192.168.1.45",
    changeSummary: "Approved: +12.0 Attendance Hours Credited",
    justification: "Valid hospital inpatient records verified. Approved under 10% statutory ceiling.",
    securityHash: "SHA256: 8e3c...77a1",
  },
  {
    id: "AUD-MED-9008",
    timestamp: "2026-10-14 14:15:32",
    actionType: "CMO Endorsement",
    rollNumber: "2441112003",
    studentName: "Chirag Banerjee",
    actorName: "Dr. Sandip Sengupta (CMO)",
    actorRole: "Chief Medical Officer",
    ipAddress: "192.168.2.18",
    changeSummary: "Certificate CERT-2026-103-HOSPITAL.pdf verified and signed",
    justification: "Confirmed WBMC doctor registration & outpatient dehydration prescription.",
    securityHash: "SHA256: 9b2a...e405",
  },
  {
    id: "AUD-MED-8994",
    timestamp: "2026-10-12 10:05:44",
    actionType: "Condonation Signed",
    rollNumber: "2441112030",
    studentName: "Priyanka Bose",
    actorName: "Prof. S. Mukherjee",
    actorRole: "Principal / Director",
    ipAddress: "192.168.1.10",
    changeSummary: "Condonation Granted: +18.0 Hours for National Hospitality Olympiad",
    justification: "Official institutional representation approved by Council Directorate.",
    securityHash: "SHA256: 3c11...ff90",
  },
  {
    id: "AUD-MED-8980",
    timestamp: "2026-10-08 17:30:19",
    actionType: "Claim Rejected",
    rollNumber: "2441112015",
    studentName: "Rohan Mukherjee",
    actorName: "Dr. A. K. Roy",
    actorRole: "Dean of Academics",
    ipAddress: "192.168.1.45",
    changeSummary: "Claim Rejected (0.0 Hours Credited)",
    justification: "Certificate submitted 21 days late after statutory 7-day window. Unverified dispensary.",
    securityHash: "SHA256: 1d44...88e2",
  },
  {
    id: "AUD-MED-8975",
    timestamp: "2026-10-04 09:12:00",
    actionType: "Claim Submitted",
    rollNumber: "2441112003",
    studentName: "Chirag Banerjee",
    actorName: "Chirag Banerjee",
    actorRole: "Student Portal User",
    ipAddress: "103.21.144.60",
    changeSummary: "Medical claim submitted for 3 days (12.0 hours)",
    justification: "Acute viral gastroenteritis rest certificate attached.",
    securityHash: "SHA256: 7a88...0012",
  },
];

export default function ApprovalAuditTrailPage() {
  const [auditLogs, setAuditLogs] = useState<AuditEntry[]>(initialAuditLogs);
  const [selectedAction, setSelectedAction] = useState("All Events");
  const [searchQuery, setSearchQuery] = useState("");

  const filteredLogs = auditLogs.filter((log) => {
    const matchesAction =
      selectedAction === "All Events" || log.actionType === selectedAction;
    const matchesSearch =
      searchQuery === "" ||
      log.studentName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      log.rollNumber.includes(searchQuery) ||
      log.actorName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      log.id.toLowerCase().includes(searchQuery.toLowerCase()) ||
      log.changeSummary.toLowerCase().includes(searchQuery.toLowerCase());
    return matchesAction && matchesSearch;
  });

  const getActionBadge = (action: string) => {
    switch (action) {
      case "Admin Approval":
        return "bg-emerald-50 text-emerald-700 border-emerald-200";
      case "CMO Endorsement":
        return "bg-blue-50 text-[#1769E8] border-blue-200";
      case "Condonation Signed":
        return "bg-purple-50 text-purple-700 border-purple-200";
      case "Recalculation Triggered":
        return "bg-amber-50 text-amber-700 border-amber-200";
      case "Claim Rejected":
        return "bg-rose-50 text-rose-700 border-rose-200";
      default:
        return "bg-slate-100 text-slate-700 border-slate-200";
    }
  };

  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: false },
    { label: "History", href: "/admin/adjustments/history", icon: History, active: false },
    { label: "Audit Trail", href: "/admin/adjustments/audit-trail", icon: ShieldCheck, active: true },
  ];

  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">Approval Audit Trail</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">
              Approval Audit Trail & Compliance Log
            </h1>
            <p className="text-[15px] text-[#64748B] mt-1 font-normal">
              Immutable forensic log tracking all medical submissions, CMO endorsements, condonation sanctions, and attendance adjustments.
            </p>
          </div>

          <div className="flex items-center gap-2">
            <button
              onClick={() => toast.success("Exporting cryptographically signed audit log to CSV...")}
              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"
            >
              <Download className="w-4 h-4 text-[#1769E8]" />
              <span>Export Audit Trail</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. Security Highlights Card */}
      <div className="bg-[#081A2E] text-white p-5 rounded-xl border border-slate-700 shadow-sm flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div className="flex items-center gap-3.5">
          <div className="w-10 h-10 rounded-lg bg-emerald-500/20 border border-emerald-400/30 flex items-center justify-center text-emerald-400">
            <Lock className="w-5 h-5" />
          </div>
          <div>
            <div className="font-heading font-bold text-sm text-white">
              Tamper-Proof Audit Security Active
            </div>
            <div className="text-xs text-slate-300">
              Every endorsement and attendance revision is stamped with SHA-256 hash, actor role, IP address, and server clock timestamp.
            </div>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <span className="font-mono text-xs px-2.5 py-1 bg-white/10 rounded border border-white/20 text-[#F4B400] font-bold">
            Compliance: ISO 27001 / NCHMCT
          </span>
        </div>
      </div>

      {/* 4. 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">
              Action Category
            </label>
            <select
              value={selectedAction}
              onChange={(e) => setSelectedAction(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 Events</option>
              <option>Admin Approval</option>
              <option>CMO Endorsement</option>
              <option>Condonation Signed</option>
              <option>Recalculation Triggered</option>
              <option>Claim Rejected</option>
              <option>Claim Submitted</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 Logs
            </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 audit ID, student name, roll number, or approver..."
                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 ${filteredLogs.length} audit logs`)}
              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={() => {
                setSelectedAction("All Events");
                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>

      {/* 5. Audit Log 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">
            <ShieldCheck className="w-5 h-5 text-[#1769E8]" />
            <h2 className="font-heading font-bold text-lg text-[#071A4D]">
              Approval Audit Trail Records ({filteredLogs.length})
            </h2>
          </div>
          <span className="text-xs text-[#64748B]">Chronological Event Timeline</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]">Audit Ref & Time</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D]">Event Action</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D]">Target Student</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D]">Change Summary</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D]">Authorized By</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D]">Clinical / Academic Justification</th>
                <th className="py-3 px-4 font-bold text-[#071A4D] text-right">Digital Seal</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#E5EAF0]">
              {filteredLogs.length === 0 ? (
                <tr>
                  <td colSpan={8} className="py-12 text-center text-slate-400">
                    No audit records match your filters.
                  </td>
                </tr>
              ) : (
                filteredLogs.map((log, idx) => (
                  <tr key={log.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 whitespace-nowrap">
                      <div className="font-mono font-bold text-xs text-[#071A4D]">
                        {log.id}
                      </div>
                      <div className="text-[11px] text-[#64748B] flex items-center gap-1">
                        <Clock className="w-3 h-3 text-[#94A3B8]" />
                        <span>{log.timestamp}</span>
                      </div>
                    </td>
                    <td className="py-3.5 px-3.5">
                      <span
                        className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-[11px] font-bold border whitespace-nowrap ${getActionBadge(
                          log.actionType
                        )}`}
                      >
                        {log.actionType}
                      </span>
                    </td>
                    <td className="py-3.5 px-3.5">
                      <div className="font-bold text-[#071A4D] text-sm">
                        {log.studentName}
                      </div>
                      <div className="font-mono text-[11px] text-[#1769E8]">
                        {log.rollNumber}
                      </div>
                    </td>
                    <td className="py-3.5 px-3.5 max-w-[240px]">
                      <div className="font-medium text-[#071A4D] text-xs">
                        {log.changeSummary}
                      </div>
                    </td>
                    <td className="py-3.5 px-3.5 whitespace-nowrap">
                      <div className="font-semibold text-[#071A4D] flex items-center gap-1">
                        <UserCheck className="w-3.5 h-3.5 text-[#1769E8]" />
                        <span>{log.actorName}</span>
                      </div>
                      <div className="text-[11px] text-[#64748B]">
                        {log.actorRole} • <span className="font-mono">{log.ipAddress}</span>
                      </div>
                    </td>
                    <td className="py-3.5 px-3.5 max-w-[260px]">
                      <div className="text-[11px] text-[#475569] italic bg-slate-50 p-1.5 rounded border border-slate-200">
                        "{log.justification}"
                      </div>
                    </td>
                    <td className="py-3.5 px-4 text-right whitespace-nowrap">
                      <span
                        className="font-mono text-[10px] bg-slate-100 text-slate-700 px-2 py-1 rounded border border-slate-300 inline-flex items-center gap-1"
                        title="Cryptographic verification fingerprint"
                      >
                        <ShieldCheck className="w-3 h-3 text-emerald-600" />
                        <span>{log.securityHash}</span>
                      </span>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
