"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  Search,
  RotateCcw,
  Eye,
  FileSpreadsheet,
  FileText,
  Shield,
  Sparkles,
  ArrowRight,
  ShieldAlert,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";
import { toast } from "sonner";

interface AuditLogEntry {
  id: string;
  action: "SESSION_LOCK" | "SESSION_UNLOCK" | "MARK_UPDATE" | "MEDICAL_APPROVE" | "CONDONATION_GRANT" | "POLICY_CHANGE";
  entityName: string;
  entityId: string;
  actorName: string;
  actorRole: string;
  ipAddress: string;
  timestamp: string;
  previousState: Record<string, any>;
  newState: Record<string, any>;
}

const mockAuditLogs: AuditLogEntry[] = [
  {
    id: "log-101",
    action: "SESSION_LOCK",
    entityName: "AttendanceSession",
    entityId: "session_1038",
    actorName: "Chef Rajesh Sharma",
    actorRole: "FACULTY",
    ipAddress: "192.168.1.45",
    timestamp: "2026-10-06 13:05:22",
    previousState: {
      status: "DRAFT",
      version: 1,
      totalUnits: 4.0,
      presentStudents: 29,
    },
    newState: {
      status: "LOCKED",
      version: 2,
      totalUnits: 4.0,
      presentStudents: 29,
      lockedAt: "2026-10-06T13:05:22Z",
    },
  },
  {
    id: "log-102",
    action: "MEDICAL_APPROVE",
    entityName: "MedicalRequest",
    entityId: "med-102",
    actorName: "Dr. K. S. Verma",
    actorRole: "MEDICAL_OFFICER",
    ipAddress: "192.168.1.12",
    timestamp: "2026-09-23 15:00:10",
    previousState: {
      status: "PENDING",
      approvedHours: 0,
    },
    newState: {
      status: "APPROVED",
      approvedHours: 8.0,
      reviewedBy: "Dr. K. S. Verma",
    },
  },
  {
    id: "log-103",
    action: "CONDONATION_GRANT",
    entityName: "CondonationRequest",
    entityId: "cond-101",
    actorName: "Dr. V. Swaminathan",
    actorRole: "PRINCIPAL",
    ipAddress: "192.168.1.2",
    timestamp: "2026-10-02 11:30:45",
    previousState: {
      status: "PENDING",
      grantedHours: 0,
    },
    newState: {
      status: "APPROVED",
      grantedHours: 8.0,
      event: "National Culinary Challenge 2026",
    },
  },
  {
    id: "log-104",
    action: "MARK_UPDATE",
    entityName: "AttendanceRecord",
    entityId: "rec_9824",
    actorName: "Super Admin",
    actorRole: "SUPER_ADMIN",
    ipAddress: "192.168.1.1",
    timestamp: "2026-09-18 16:42:01",
    previousState: {
      status: "ABSENT",
      unitsGranted: 0,
    },
    newState: {
      status: "PRESENT",
      unitsGranted: 4.0,
      overrideReason: "Biometric station offline sync reconciliation",
    },
  },
];

export default function AuditLogsPage() {
  const [logs] = useState<AuditLogEntry[]>(mockAuditLogs);
  const [selectedAction, setSelectedAction] = useState("All Actions");
  const [searchQuery, setSearchQuery] = useState("");
  const [activeLog, setActiveLog] = useState<AuditLogEntry>(mockAuditLogs[0]);
  const [selectedRows, setSelectedRows] = useState<string[]>([]);
  const [pageSize, setPageSize] = useState("10");

  const filteredLogs = logs.filter((l) => {
    const matchesAction =
      selectedAction === "All Actions" || l.action === selectedAction;
    const matchesSearch =
      searchQuery === "" ||
      l.actorName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      l.entityName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      l.entityId.toLowerCase().includes(searchQuery.toLowerCase()) ||
      l.ipAddress.includes(searchQuery);
    return matchesAction && matchesSearch;
  });

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

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

  const getActionBadge = (action: string) => {
    switch (action) {
      case "SESSION_LOCK":
        return "bg-[#F3E8FF] text-[#7E22CE] border-[#E9D5FF]";
      case "MEDICAL_APPROVE":
        return "bg-[#DCFCE7] text-[#15803D] border-[#BBF7D0]";
      case "CONDONATION_GRANT":
        return "bg-[#FEF3C7] text-[#B45309] border-[#FDE68A]";
      case "MARK_UPDATE":
        return "bg-[#E0F2FE] text-[#0369A1] border-[#BAE6FD]";
      default:
        return "bg-slate-100 text-slate-700 border-slate-200";
    }
  };

  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/settings/global" className="hover:text-[#1769E8] transition-colors">
            System Settings
          </Link>
          <span>&gt;</span>
          <span className="text-[#071A4D] font-semibold">Audit Logs</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">
              Security Audit Logs
            </h1>
            <p className="text-[15px] text-[#64748B] mt-1 font-normal">
              Immutable electronic ledger of all attendance modifications, session lock actions, and regulatory adjustments.
            </p>
          </div>

          <div className="flex items-center gap-3">
            <button
              onClick={() => toast.success("Exporting audit logs 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"
            >
              <FileSpreadsheet className="w-4 h-4 text-emerald-600" />
              <span>Export</span>
            </button>
            <button
              onClick={() => toast.info("Generating system governance report...")}
              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"
            >
              <FileText className="w-4 h-4 text-purple-600" />
              <span>Generate Report</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">
              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 Actions</option>
              <option value="SESSION_LOCK">SESSION_LOCK</option>
              <option value="MEDICAL_APPROVE">MEDICAL_APPROVE</option>
              <option value="CONDONATION_GRANT">CONDONATION_GRANT</option>
              <option value="MARK_UPDATE">MARK_UPDATE</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
            </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 actor name, entity ID, or IP address..."
                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 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={() => {
                setSelectedAction("All Actions");
                setSearchQuery("");
                toast.info("Filters reset");
              }}
              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">
              <Shield className="w-5 h-5 text-[#1769E8]" />
              <h2 className="font-heading font-bold text-lg text-[#071A4D]">
                Audit Trail ({filteredLogs.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 === filteredLogs.length &&
                        filteredLogs.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]">Timestamp</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D]">Action</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D]">Target Entity</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D]">Actor</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D]">IP Address</th>
                  <th className="py-3 px-4 font-bold text-[#071A4D] text-right">Inspect</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-[#E5EAF0]">
                {filteredLogs.map((l, idx) => (
                  <tr
                    key={l.id}
                    onClick={() => setActiveLog(l)}
                    className={`hover:bg-[#F8FAFC] transition-colors cursor-pointer ${
                      activeLog.id === l.id ? "bg-[#EFF6FF]/60" : ""
                    }`}
                  >
                    <td className="py-3.5 px-3.5 text-center">
                      <input
                        type="checkbox"
                        checked={selectedRows.includes(l.id)}
                        onChange={() => handleRowSelect(l.id)}
                        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 text-[11px] text-[#071A4D]">
                      {l.timestamp}
                    </td>
                    <td className="py-3.5 px-3.5">
                      <span
                        className={`inline-flex items-center px-2 py-0.5 rounded text-[10px] font-mono font-bold border ${getActionBadge(
                          l.action
                        )}`}
                      >
                        {l.action}
                      </span>
                    </td>
                    <td className="py-3.5 px-3.5 font-mono text-xs text-[#334155]">
                      {l.entityName} <span className="text-[#94A3B8]">({l.entityId})</span>
                    </td>
                    <td className="py-3.5 px-3.5">
                      <div className="font-bold text-[#071A4D] text-xs">
                        {l.actorName}
                      </div>
                      <div className="text-[10px] text-[#64748B] font-mono">
                        {l.actorRole}
                      </div>
                    </td>
                    <td className="py-3.5 px-3.5 font-mono text-xs text-[#64748B]">
                      {l.ipAddress}
                    </td>
                    <td className="py-3.5 px-4 text-right">
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          setActiveLog(l);
                          toast.info(`Inspecting state diff for ${l.entityId}`);
                        }}
                        className="p-1.5 text-[#1769E8] hover:bg-[#EFF6FF] rounded-md transition-colors cursor-pointer"
                        title="Inspect Diff"
                      >
                        <Eye className="w-3.5 h-3.5" />
                      </button>
                    </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 {filteredLogs.length} of {logs.length} entries
            </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): State Diff Inspector */}
        <div className="lg:col-span-4 space-y-5">
          <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs p-5 text-xs">
            <div className="flex items-center justify-between pb-3 mb-4 border-b border-[#E5EAF0]">
              <div className="flex items-center gap-2">
                <Shield className="w-4 h-4 text-[#1769E8]" />
                <h3 className="font-heading font-bold text-base text-[#071A4D]">
                  State Diff Inspector
                </h3>
              </div>
              <span className="font-mono text-[10px] text-[#64748B]">
                {activeLog.id}
              </span>
            </div>

            <div className="space-y-3.5">
              <div className="grid grid-cols-2 gap-2 p-2.5 bg-slate-50 rounded-lg border border-[#E2E8F0]">
                <div>
                  <span className="text-[#64748B] block text-[10px]">Actor</span>
                  <span className="font-bold text-[#071A4D]">{activeLog.actorName}</span>
                </div>
                <div>
                  <span className="text-[#64748B] block text-[10px]">IP Address</span>
                  <span className="font-mono font-bold text-[#071A4D]">{activeLog.ipAddress}</span>
                </div>
              </div>

              <div>
                <span className="block font-semibold text-[#64748B] mb-1">
                  Previous State (Before)
                </span>
                <pre className="p-2.5 bg-rose-50/50 border border-rose-200 text-rose-800 rounded-lg font-mono text-[10px] overflow-x-auto leading-relaxed">
                  {JSON.stringify(activeLog.previousState, null, 2)}
                </pre>
              </div>

              <div>
                <span className="block font-semibold text-[#64748B] mb-1">
                  New State (Committed)
                </span>
                <pre className="p-2.5 bg-emerald-50/50 border border-emerald-200 text-emerald-800 rounded-lg font-mono text-[10px] overflow-x-auto leading-relaxed">
                  {JSON.stringify(activeLog.newState, null, 2)}
                </pre>
              </div>
            </div>
          </div>

          {/* Compliance 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>Immutable Audit Standards</span>
            </div>
            <div className="space-y-2 text-[#475569]">
              <div className="flex items-center justify-between">
                <span className="font-medium">Write-Once Ledger</span>
                <span className="font-mono font-bold text-emerald-600">Active</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="font-medium">Session Unlock Audit</span>
                <span className="font-mono font-bold text-[#071A4D]">Mandatory Log</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="font-medium">Retention Period</span>
                <span className="font-mono font-bold text-[#1769E8]">5 Academic Years</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
