import React, { useState, useEffect } from "react";
import { 
  Database, 
  Zap, 
  Activity, 
  CheckCircle2, 
  RefreshCw, 
  Layers, 
  ShieldCheck, 
  Clock, 
  ArrowRight, 
  Server, 
  FileText, 
  Download, 
  Radio, 
  Cpu, 
  CloudCheck,
  TrendingUp,
  AlertTriangle,
  Users,
  CalendarCheck,
  CreditCard,
  Play,
  Pause,
  RotateCcw,
  Search,
  Filter,
  XCircle,
  FileSpreadsheet,
  AlertCircle
} from "lucide-react";
import { Employee } from "../types";

interface DataReplicationDashboardProps {
  currentUser?: Employee;
  employees?: Employee[];
}

interface ReplicationModuleHealth {
  id: string;
  name: string;
  sourceTable: string;
  targetCollection: string;
  totalSynced: number;
  status: "SYNCHRONIZED" | "SYNCHRONIZING" | "PAUSED" | "ERROR";
  latencyMs: number;
  lastSync: string;
  conflictPolicy: string;
  syncMode: string;
  icon: any;
}

interface CDCEventLog {
  id: string;
  timestamp: string;
  module: string;
  action: "INSERT" | "UPDATE" | "DELETE";
  recordId: string;
  payloadDiff: string;
  latencyMs: number;
  status: "SUCCESS" | "DLQ_RETRY" | "FAILED";
  errorMessage?: string;
  operator?: string;
}

export const DataReplicationDashboard: React.FC<DataReplicationDashboardProps> = ({
  currentUser,
  employees = []
}) => {
  const [isLiveStreaming, setIsLiveStreaming] = useState<boolean>(true);
  const [activeTab, setActiveTab] = useState<"overview" | "modules" | "topology" | "logs">("overview");
  
  // Real-time simulated statistics
  const [throughputRps, setThroughputRps] = useState<number>(520);
  const [avgLatency, setAvgLatency] = useState<number>(11.8);
  const [totalSyncedRecords, setTotalSyncedRecords] = useState<number>(342150);

  // Filter & Search states for Audit Log
  const [logStatusFilter, setLogStatusFilter] = useState<string>("ALL");
  const [logModuleFilter, setLogModuleFilter] = useState<string>("ALL");
  const [logSearchQuery, setLogSearchQuery] = useState<string>("");
  const [isResyncing, setIsResyncing] = useState<string | null>(null);
  
  // Modules state
  const [modules, setModules] = useState<ReplicationModuleHealth[]>([
    {
      id: "mod-01",
      name: "Profil Pegawai & Biodata Master",
      sourceTable: "public.employees",
      targetCollection: "firestore/employees",
      totalSynced: employees.length || 1248,
      status: "SYNCHRONIZED",
      latencyMs: 8,
      lastSync: "Baru saja",
      conflictPolicy: "Source Wins (Supabase)",
      syncMode: "PostgreSQL WAL Listener",
      icon: Users
    },
    {
      id: "mod-02",
      name: "Absensi & Log Presensi Pegawai",
      sourceTable: "public.attendance_logs",
      targetCollection: "firestore/attendance_logs",
      totalSynced: 18920,
      status: "SYNCHRONIZED",
      latencyMs: 14,
      lastSync: "Baru saja",
      conflictPolicy: "Source Wins (Supabase)",
      syncMode: "Supabase Webhook Trigger",
      icon: CalendarCheck
    },
    {
      id: "mod-03",
      name: "Payroll & Rekap Slip Gaji",
      sourceTable: "public.salary_records",
      targetCollection: "firestore/salary_records",
      totalSynced: 3420,
      status: "SYNCHRONIZED",
      latencyMs: 18,
      lastSync: "1 mnt lalu",
      conflictPolicy: "Source Wins (Supabase)",
      syncMode: "Encrypted Dual-Write Worker",
      icon: CreditCard
    },
    {
      id: "mod-04",
      name: "Struktur Organisasi & Divisi",
      sourceTable: "public.divisions",
      targetCollection: "firestore/divisions",
      totalSynced: 48,
      status: "SYNCHRONIZED",
      latencyMs: 6,
      lastSync: "5 mnt lalu",
      conflictPolicy: "Source Wins (Supabase)",
      syncMode: "Direct Write Sync",
      icon: Layers
    }
  ]);

  // Live CDC Logs state containing success and failure entries for IT audit
  const [cdcLogs, setCdcLogs] = useState<CDCEventLog[]>([
    {
      id: "cdc-105",
      timestamp: new Date().toLocaleTimeString(),
      module: "Absensi Pegawai",
      action: "INSERT",
      recordId: "LOG-ABS-20260805-0892",
      payloadDiff: "{ nip: '19920104', check_in: '07:58:12', status: 'Hadir Tepat Waktu' }",
      latencyMs: 11,
      status: "SUCCESS",
      operator: "Supabase-Webhook-Worker-01"
    },
    {
      id: "cdc-104",
      timestamp: new Date(Date.now() - 1000 * 12).toLocaleTimeString(),
      module: "Profil Pegawai",
      action: "UPDATE",
      recordId: "EMP-CEO-01 (Bambang Hartono)",
      payloadDiff: "{ status: 'Aktif', division: 'Direksi Utama', salary: 85000000 }",
      latencyMs: 9,
      status: "SUCCESS",
      operator: "PostgreSQL-WAL-Listener"
    },
    {
      id: "cdc-103",
      timestamp: new Date(Date.now() - 1000 * 28).toLocaleTimeString(),
      module: "Payroll & Slip Gaji",
      action: "UPDATE",
      recordId: "SLIP-202608-0088",
      payloadDiff: "{ net_salary: 18500000, tax_deduction: 1850000 }",
      latencyMs: 420,
      status: "DLQ_RETRY",
      errorMessage: "HTTP 503: Firestore Write Rate Limit - Retrying in DLQ Queue (Attempt 2/5)",
      operator: "Encrypted-DualWrite-Worker"
    },
    {
      id: "cdc-102",
      timestamp: new Date(Date.now() - 1000 * 45).toLocaleTimeString(),
      module: "Absensi Pegawai",
      action: "INSERT",
      recordId: "LOG-ABS-20260805-0890",
      payloadDiff: "{ nip: '19950811', check_in: '08:12:05', status: 'Terlambat (+12m)' }",
      latencyMs: 14,
      status: "SUCCESS",
      operator: "Supabase-Webhook-Worker-02"
    },
    {
      id: "cdc-101",
      timestamp: new Date(Date.now() - 1000 * 75).toLocaleTimeString(),
      module: "Struktur Organisasi",
      action: "UPDATE",
      recordId: "DIV-IT-001 (Teknologi Informasi)",
      payloadDiff: "{ head_of_division: 'Dian Ermawan', budget: 1500000000 }",
      latencyMs: 820,
      status: "FAILED",
      errorMessage: "Schema Mismatch: Column 'budget' expecting Int64, received String in payload mapping",
      operator: "DirectWriteSync-Process"
    },
    {
      id: "cdc-100",
      timestamp: new Date(Date.now() - 1000 * 110).toLocaleTimeString(),
      module: "Profil Pegawai",
      action: "INSERT",
      recordId: "EMP-NEW-99 (Siti Rahmawati)",
      payloadDiff: "{ nip: '19981201', position: 'Backend Engineer', status: 'Aktif' }",
      latencyMs: 12,
      status: "SUCCESS",
      operator: "PostgreSQL-WAL-Listener"
    }
  ]);

  // Simulate periodic incoming CDC events
  useEffect(() => {
    if (!isLiveStreaming) return;

    const interval = setInterval(() => {
      const actions: ("INSERT" | "UPDATE")[] = ["INSERT", "UPDATE"];
      const randAction = actions[Math.floor(Math.random() * actions.length)];
      const randModule = Math.random() > 0.5 ? "Absensi Pegawai" : "Profil Pegawai";
      const randomLatency = Math.floor(Math.random() * 8) + 8; // 8ms to 15ms
      const newLogId = `cdc-${Date.now().toString().slice(-4)}`;

      const newLog: CDCEventLog = {
        id: newLogId,
        timestamp: new Date().toLocaleTimeString(),
        module: randModule,
        action: randAction,
        recordId: randModule === "Absensi Pegawai" 
          ? `LOG-ABS-${Math.floor(1000 + Math.random() * 9000)}` 
          : `EMP-${Math.floor(100 + Math.random() * 900)}`,
        payloadDiff: randModule === "Absensi Pegawai"
          ? `{ check_in: '${new Date().toLocaleTimeString()}', location: 'HQ Gedung A', verified: true }`
          : `{ updated_at: '${new Date().toISOString()}', _sync_status: 'replicated' }`,
        latencyMs: randomLatency,
        status: "SUCCESS",
        operator: "Supabase-CDC-Worker"
      };

      setCdcLogs(prev => [newLog, ...prev.slice(0, 24)]);
      setTotalSyncedRecords(prev => prev + 1);
      setThroughputRps(Math.floor(490 + Math.random() * 60));
      setAvgLatency(parseFloat((10 + Math.random() * 3).toFixed(1)));
    }, 4000);

    return () => clearInterval(interval);
  }, [isLiveStreaming]);

  // Retry/Re-sync failed log entry
  const handleRetryLog = (logId: string) => {
    setIsResyncing(logId);
    setTimeout(() => {
      setCdcLogs(prev => prev.map(item => {
        if (item.id === logId) {
          return {
            ...item,
            status: "SUCCESS",
            timestamp: new Date().toLocaleTimeString(),
            latencyMs: Math.floor(Math.random() * 10) + 10,
            errorMessage: undefined
          };
        }
        return item;
      }));
      setIsResyncing(null);
    }, 800);
  };

  // Handle Manual Trigger Test
  const handleTriggerManualSync = () => {
    const testLog: CDCEventLog = {
      id: `manual-${Date.now().toString().slice(-4)}`,
      timestamp: new Date().toLocaleTimeString(),
      module: "Profil Pegawai",
      action: "UPDATE",
      recordId: "EMP-SUPABASE-TEST-SYNC",
      payloadDiff: "{ source: 'Manual Trigger UI Test', supabase_wal: true, firestore_synced: true }",
      latencyMs: 7,
      status: "SUCCESS",
      operator: currentUser?.name || "Admin-CTO-User"
    };

    setCdcLogs(prev => [testLog, ...prev]);
    setTotalSyncedRecords(prev => prev + 1);

    // Flash module status
    setModules(prev => prev.map(m => m.id === "mod-01" ? { ...m, lastSync: "Baru saja (Manual Trigger)" } : m));
  };

  // Export Audit Log CSV
  const handleExportAuditCSV = () => {
    const headers = ["ID Event", "Waktu", "Modul Aplikasi", "Aksi CDC", "Record ID", "Status", "Latensi (ms)", "Error Message / Detail", "Worker Process"];
    const rows = filteredLogs.map(l => [
      l.id,
      l.timestamp,
      `"${l.module}"`,
      l.action,
      `"${l.recordId}"`,
      l.status,
      l.latencyMs,
      `"${l.errorMessage || l.payloadDiff.replace(/"/g, '""')}"`,
      `"${l.operator || 'System'}"`
    ]);

    const csvContent = "\uFEFF" + [headers.join(","), ...rows.map(e => e.join(","))].join("\n");
    const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", `AUDIT_LOG_REPLIKASI_SUPABASE_FIREBASE_${new Date().toISOString().slice(0, 10)}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // Filtered Logs
  const filteredLogs = cdcLogs.filter(log => {
    const matchesStatus = logStatusFilter === "ALL" || log.status === logStatusFilter;
    const matchesModule = logModuleFilter === "ALL" || log.module === logModuleFilter;
    const matchesSearch = logSearchQuery === "" || 
      log.recordId.toLowerCase().includes(logSearchQuery.toLowerCase()) ||
      log.module.toLowerCase().includes(logSearchQuery.toLowerCase()) ||
      (log.errorMessage && log.errorMessage.toLowerCase().includes(logSearchQuery.toLowerCase()));
    
    return matchesStatus && matchesModule && matchesSearch;
  });

  const failedCount = cdcLogs.filter(l => l.status === "FAILED" || l.status === "DLQ_RETRY").length;
  const successCount = cdcLogs.filter(l => l.status === "SUCCESS").length;

  return (
    <div className="space-y-6 font-sans text-slate-100 pb-10">
      
      {/* HEADER BANNER */}
      <div className="bg-[#0d1117] border border-[#21262d] p-5 sm:p-6 shadow-2xl relative overflow-hidden rounded-none">
        <div className="absolute top-0 right-0 w-96 h-96 bg-gradient-to-bl from-emerald-500/10 via-cyan-500/5 to-transparent pointer-events-none" />
        
        <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4 relative z-10">
          <div className="space-y-1.5">
            <div className="flex items-center gap-2.5">
              <span className="px-2.5 py-0.5 bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 font-mono text-[11px] font-bold tracking-wider uppercase flex items-center gap-1.5">
                <span className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse" />
                Live CDC Engine Active
              </span>
              <span className="px-2.5 py-0.5 bg-[#facc15]/10 border border-[#facc15]/30 text-[#facc15] font-mono text-[11px] font-bold tracking-wider uppercase">
                Supabase ➔ Firebase
              </span>
            </div>
            <h1 className="text-xl sm:text-2xl font-black text-white uppercase tracking-tight flex items-center gap-2.5">
              <Database className="w-6 h-6 text-emerald-400" />
              DASHBOARD REPLIKASI DATA REAL-TIME & AUDIT LOG IT
            </h1>
            <p className="text-xs text-slate-400 font-mono max-w-2xl">
              Monitoring Change Data Capture (CDC) & Dual-Write Pipeline antara Supabase PostgreSQL Cloud (Primary OLTP) dan Firebase Firestore (Read-Replica Realtime) dengan Log Histori Audit IT.
            </p>
          </div>

          <div className="flex flex-wrap items-center gap-2.5">
            <button
              type="button"
              onClick={() => setIsLiveStreaming(!isLiveStreaming)}
              className={`px-3.5 py-2 border text-xs font-mono font-bold uppercase transition-all flex items-center gap-2 cursor-pointer ${
                isLiveStreaming 
                  ? "bg-emerald-500/10 border-emerald-500/40 text-emerald-400 hover:bg-emerald-500/20" 
                  : "bg-amber-500/10 border-amber-500/40 text-amber-400 hover:bg-amber-500/20"
              }`}
            >
              {isLiveStreaming ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}
              {isLiveStreaming ? "Pause Live Sync" : "Resume Live Sync"}
            </button>

            <button
              type="button"
              onClick={handleTriggerManualSync}
              className="px-4 py-2 bg-[#facc15] hover:bg-yellow-400 text-black font-black uppercase text-xs font-mono transition-all flex items-center gap-2 shadow-lg cursor-pointer"
            >
              <Zap className="w-4 h-4 text-black fill-black" />
              Uji Coba Sync Real-Time
            </button>
          </div>
        </div>
      </div>

      {/* KPI METRICS OVERVIEW */}
      <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-3">
        
        <div className="bg-[#0a0a0a] border border-[#222] p-4 space-y-1 relative overflow-hidden">
          <div className="flex items-center justify-between text-slate-400">
            <span className="text-[10px] font-mono uppercase font-bold tracking-wider">Status Replikasi</span>
            <Activity className="w-4 h-4 text-emerald-400" />
          </div>
          <div className="text-lg font-black text-emerald-400 font-mono tracking-tight flex items-center gap-2">
            <span className="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-ping" />
            100% HEALTHY
          </div>
          <p className="text-[10px] text-slate-500 font-mono">WAL CDC Stream OK</p>
        </div>

        <div className="bg-[#0a0a0a] border border-[#222] p-4 space-y-1">
          <div className="flex items-center justify-between text-slate-400">
            <span className="text-[10px] font-mono uppercase font-bold tracking-wider">Avg Sync Latency</span>
            <Zap className="w-4 h-4 text-[#facc15]" />
          </div>
          <div className="text-lg font-black text-[#facc15] font-mono tracking-tight">
            {avgLatency} ms
          </div>
          <p className="text-[10px] text-slate-500 font-mono">Sangat Cepat (&lt; 20ms)</p>
        </div>

        <div className="bg-[#0a0a0a] border border-[#222] p-4 space-y-1">
          <div className="flex items-center justify-between text-slate-400">
            <span className="text-[10px] font-mono uppercase font-bold tracking-wider">Kecepatan Sync</span>
            <TrendingUp className="w-4 h-4 text-cyan-400" />
          </div>
          <div className="text-lg font-black text-cyan-400 font-mono tracking-tight">
            {throughputRps} RPS
          </div>
          <p className="text-[10px] text-slate-500 font-mono">Records per Detik</p>
        </div>

        <div className="bg-[#0a0a0a] border border-[#222] p-4 space-y-1">
          <div className="flex items-center justify-between text-slate-400">
            <span className="text-[10px] font-mono uppercase font-bold tracking-wider">Total Ter-sinkron</span>
            <Database className="w-4 h-4 text-indigo-400" />
          </div>
          <div className="text-lg font-black text-indigo-300 font-mono tracking-tight">
            {totalSyncedRecords.toLocaleString("id-ID")}
          </div>
          <p className="text-[10px] text-slate-500 font-mono">Entri Supabase ➔ Firebase</p>
        </div>

        <div className="bg-[#0a0a0a] border border-[#222] p-4 space-y-1 col-span-2 md:col-span-1">
          <div className="flex items-center justify-between text-slate-400">
            <span className="text-[10px] font-mono uppercase font-bold tracking-wider">Audit Alert / DLQ</span>
            <AlertTriangle className="w-4 h-4 text-amber-400" />
          </div>
          <div className="text-lg font-black text-amber-400 font-mono tracking-tight">
            {failedCount} Peristiwa
          </div>
          <p className="text-[10px] text-slate-400 font-mono">Perlu Audit / Re-sync</p>
        </div>

      </div>

      {/* NAVIGATION TABS */}
      <div className="border-b border-[#222] flex items-center gap-1 overflow-x-auto">
        <button
          type="button"
          onClick={() => setActiveTab("overview")}
          className={`px-4 py-2.5 text-xs font-mono font-bold uppercase transition-all border-b-2 cursor-pointer flex items-center gap-2 ${
            activeTab === "overview"
              ? "border-[#facc15] text-[#facc15] bg-[#facc15]/5"
              : "border-transparent text-slate-400 hover:text-white hover:bg-[#111]"
          }`}
        >
          <Layers className="w-4 h-4" />
          Modul Utama Replikasi ({modules.length})
        </button>

        <button
          type="button"
          onClick={() => setActiveTab("topology")}
          className={`px-4 py-2.5 text-xs font-mono font-bold uppercase transition-all border-b-2 cursor-pointer flex items-center gap-2 ${
            activeTab === "topology"
              ? "border-[#facc15] text-[#facc15] bg-[#facc15]/5"
              : "border-transparent text-slate-400 hover:text-white hover:bg-[#111]"
          }`}
        >
          <Server className="w-4 h-4" />
          Topologi Arsitektur CDC
        </button>

        <button
          type="button"
          onClick={() => setActiveTab("logs")}
          className={`px-4 py-2.5 text-xs font-mono font-bold uppercase transition-all border-b-2 cursor-pointer flex items-center gap-2 ${
            activeTab === "logs"
              ? "border-[#facc15] text-[#facc15] bg-[#facc15]/5"
              : "border-transparent text-slate-400 hover:text-white hover:bg-[#111]"
          }`}
        >
          <Activity className="w-4 h-4" />
          Audit Log Histori Sinkronisasi ({cdcLogs.length})
        </button>
      </div>

      {/* TAB 1: OVERVIEW MODUL REPLIKASI & AUDIT TABLE */}
      {activeTab === "overview" && (
        <div className="space-y-6">
          <div className="flex items-center justify-between">
            <h2 className="text-sm font-black text-white uppercase font-mono tracking-wider flex items-center gap-2">
              <CheckCircle2 className="w-4 h-4 text-emerald-400" />
              STATUS REPLIKASI PER MODUL APLIKASI
            </h2>
            <span className="text-xs text-slate-400 font-mono">
              Database Master: <span className="text-cyan-400 font-bold">Supabase PostgreSQL</span> | Read-Replica: <span className="text-amber-400 font-bold">Firebase Firestore</span>
            </span>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {modules.map(mod => {
              const IconComp = mod.icon;
              return (
                <div key={mod.id} className="bg-[#0a0a0a] border border-[#222] p-5 space-y-4 relative hover:border-[#333] transition-all">
                  
                  <div className="flex items-start justify-between border-b border-[#222] pb-3">
                    <div className="flex items-center gap-3">
                      <div className="p-2 bg-[#111] border border-[#333] text-[#facc15]">
                        <IconComp className="w-5 h-5 text-[#facc15]" />
                      </div>
                      <div>
                        <h3 className="text-sm font-bold text-white uppercase tracking-tight font-mono">
                          {mod.name}
                        </h3>
                        <p className="text-[11px] text-slate-400 font-mono">
                          Mode: {mod.syncMode}
                        </p>
                      </div>
                    </div>

                    <span className="px-2.5 py-0.5 bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 text-[10px] font-mono font-bold uppercase tracking-wider flex items-center gap-1.5">
                      <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />
                      {mod.status}
                    </span>
                  </div>

                  {/* Mapping Source to Target */}
                  <div className="bg-[#050505] border border-[#1a1a1a] p-3 text-xs font-mono space-y-2">
                    <div className="flex items-center justify-between text-slate-400 text-[11px]">
                      <span>Supabase (Source)</span>
                      <ArrowRight className="w-3.5 h-3.5 text-slate-600" />
                      <span>Firebase Firestore (Target)</span>
                    </div>

                    <div className="flex items-center justify-between font-bold text-white">
                      <span className="text-cyan-400">{mod.sourceTable}</span>
                      <span className="text-amber-400">{mod.targetCollection}</span>
                    </div>
                  </div>

                  {/* Operational Metrics */}
                  <div className="grid grid-cols-3 gap-2 text-center font-mono text-xs">
                    <div className="bg-[#111] p-2 border border-[#222]">
                      <span className="text-[10px] text-slate-500 block uppercase">Total Synced</span>
                      <span className="font-bold text-white text-sm">{mod.totalSynced.toLocaleString("id-ID")}</span>
                    </div>

                    <div className="bg-[#111] p-2 border border-[#222]">
                      <span className="text-[10px] text-slate-500 block uppercase">Latensi</span>
                      <span className="font-bold text-[#facc15] text-sm">{mod.latencyMs} ms</span>
                    </div>

                    <div className="bg-[#111] p-2 border border-[#222]">
                      <span className="text-[10px] text-slate-500 block uppercase">Terakhir Sync</span>
                      <span className="font-bold text-emerald-400 text-xs">{mod.lastSync}</span>
                    </div>
                  </div>

                  <div className="flex items-center justify-between text-[11px] font-mono text-slate-400 pt-1 border-t border-[#1a1a1a]">
                    <span>Aturan Konflik: <strong className="text-slate-200">{mod.conflictPolicy}</strong></span>
                    <span className="text-emerald-400 flex items-center gap-1">
                      <ShieldCheck className="w-3.5 h-3.5" /> Direct WAL Sync OK
                    </span>
                  </div>

                </div>
              );
            })}
          </div>

          {/* AUDIT LOG HISTORI REPLIKASI SINKRONISASI UNTUK TIM IT */}
          <div className="bg-[#0a0a0a] border-2 border-[#222] overflow-hidden space-y-0 mt-8">
            <div className="p-4 bg-[#050505] border-b border-[#222] flex flex-wrap items-center justify-between gap-3">
              <div>
                <h3 className="text-xs font-black text-white uppercase font-mono tracking-wider flex items-center gap-2">
                  <Activity className="w-4 h-4 text-[#facc15]" />
                  TABEL LOG HISTORI SINKRONISASI & AUDIT TIM IT
                </h3>
                <p className="text-[11px] text-slate-400 font-mono mt-0.5">
                  Rekapitulasi peristiwa sukses/gagal tiap modul untuk diagnosa & re-sinkronisasi data
                </p>
              </div>

              <div className="flex items-center gap-2">
                <button
                  type="button"
                  onClick={handleExportAuditCSV}
                  className="bg-[#111] hover:bg-[#222] text-[#facc15] border border-[#333] hover:border-[#facc15] px-3 py-1.5 text-xs font-mono font-bold uppercase transition-all cursor-pointer flex items-center gap-1.5"
                >
                  <FileSpreadsheet className="w-3.5 h-3.5 text-[#facc15]" />
                  Unduh Audit Log (CSV)
                </button>
              </div>
            </div>

            {/* FILTER BAR FOR AUDIT LOG */}
            <div className="p-3 bg-[#0d1117] border-b border-[#222] flex flex-wrap items-center justify-between gap-3 font-mono text-xs">
              <div className="flex flex-wrap items-center gap-2">
                
                {/* Search */}
                <div className="relative">
                  <Search className="w-3.5 h-3.5 text-slate-500 absolute left-2.5 top-2.5" />
                  <input
                    type="text"
                    placeholder="Cari ID Record / Error..."
                    value={logSearchQuery}
                    onChange={(e) => setLogSearchQuery(e.target.value)}
                    className="bg-[#050505] border border-[#333] focus:border-[#facc15] text-slate-200 pl-8 pr-3 py-1.5 text-xs font-mono outline-none w-48 sm:w-64"
                  />
                </div>

                {/* Status Filter */}
                <div className="flex items-center gap-1 bg-[#050505] border border-[#333] p-1">
                  <Filter className="w-3 h-3 text-slate-500 ml-1" />
                  <span className="text-[10px] text-slate-400 uppercase font-bold mr-1">Status:</span>
                  {["ALL", "SUCCESS", "DLQ_RETRY", "FAILED"].map(statusKey => (
                    <button
                      key={statusKey}
                      type="button"
                      onClick={() => setLogStatusFilter(statusKey)}
                      className={`px-2 py-0.5 text-[10px] font-bold uppercase cursor-pointer ${
                        logStatusFilter === statusKey
                          ? "bg-[#facc15] text-black font-black"
                          : "text-slate-400 hover:text-white"
                      }`}
                    >
                      {statusKey === "ALL" ? "Semua" : statusKey === "SUCCESS" ? "Sukses" : statusKey === "DLQ_RETRY" ? "DLQ Retry" : "Gagal"}
                    </button>
                  ))}
                </div>

                {/* Module Filter */}
                <select
                  value={logModuleFilter}
                  onChange={(e) => setLogModuleFilter(e.target.value)}
                  className="bg-[#050505] border border-[#333] text-slate-200 px-2.5 py-1.5 text-xs font-mono outline-none cursor-pointer"
                >
                  <option value="ALL">Semua Modul</option>
                  <option value="Profil Pegawai">Profil Pegawai</option>
                  <option value="Absensi Pegawai">Absensi Pegawai</option>
                  <option value="Payroll & Slip Gaji">Payroll & Slip Gaji</option>
                  <option value="Struktur Organisasi">Struktur Organisasi</option>
                </select>

              </div>

              <div className="text-[11px] text-slate-400">
                Total Entri Audit: <strong className="text-white">{filteredLogs.length}</strong> | <span className="text-emerald-400 font-bold">{successCount} Sukses</span> | <span className="text-rose-400 font-bold">{failedCount} Gagal/DLQ</span>
              </div>
            </div>

            {/* AUDIT LOG TABLE */}
            <div className="overflow-x-auto">
              <table className="w-full text-left font-mono text-xs">
                <thead>
                  <tr className="border-b border-[#222] bg-[#050505] text-slate-400 uppercase text-[10px]">
                    <th className="p-3">Waktu Sync</th>
                    <th className="p-3">Modul Aplikasi</th>
                    <th className="p-3">Aksi CDC</th>
                    <th className="p-3">Target Record ID</th>
                    <th className="p-3">Latensi</th>
                    <th className="p-3">Status Replikasi</th>
                    <th className="p-3">Detail Diagnosa / Error Log</th>
                    <th className="p-3 text-right">Aksi IT</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-[#1a1a1a]">
                  {filteredLogs.length === 0 ? (
                    <tr>
                      <td colSpan={8} className="p-6 text-center text-slate-500 italic">
                        Tidak ada histori log sinkronisasi yang memenuhi filter.
                      </td>
                    </tr>
                  ) : (
                    filteredLogs.map((log) => (
                      <tr 
                        key={log.id} 
                        className={`hover:bg-[#111] transition-colors ${
                          log.status === "FAILED" ? "bg-rose-500/5" :
                          log.status === "DLQ_RETRY" ? "bg-amber-500/5" : ""
                        }`}
                      >
                        <td className="p-3 text-slate-400 whitespace-nowrap text-[11px]">
                          <span className="flex items-center gap-1">
                            <Clock className="w-3 h-3 text-slate-500" />
                            {log.timestamp}
                          </span>
                        </td>
                        <td className="p-3 text-white font-bold">{log.module}</td>
                        <td className="p-3">
                          <span className={`px-2 py-0.5 text-[10px] font-bold uppercase ${
                            log.action === "INSERT" ? "bg-emerald-500/10 border border-emerald-500/30 text-emerald-400" :
                            log.action === "UPDATE" ? "bg-cyan-500/10 border border-cyan-500/30 text-cyan-400" :
                            "bg-rose-500/10 border border-rose-500/30 text-rose-400"
                          }`}>
                            {log.action}
                          </span>
                        </td>
                        <td className="p-3 text-slate-200 font-mono text-[11px] font-bold">{log.recordId}</td>
                        <td className="p-3 text-[#facc15] font-bold">{log.latencyMs} ms</td>
                        <td className="p-3">
                          {log.status === "SUCCESS" && (
                            <span className="px-2 py-0.5 bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 text-[10px] font-bold flex items-center gap-1 w-max">
                              <CheckCircle2 className="w-3 h-3" /> SUKSES
                            </span>
                          )}
                          {log.status === "DLQ_RETRY" && (
                            <span className="px-2 py-0.5 bg-amber-500/10 border border-amber-500/30 text-amber-400 text-[10px] font-bold flex items-center gap-1 w-max">
                              <AlertCircle className="w-3 h-3" /> DLQ RETRY
                            </span>
                          )}
                          {log.status === "FAILED" && (
                            <span className="px-2 py-0.5 bg-rose-500/10 border border-rose-500/30 text-rose-400 text-[10px] font-bold flex items-center gap-1 w-max">
                              <XCircle className="w-3 h-3" /> GAGAL
                            </span>
                          )}
                        </td>
                        <td className="p-3 text-slate-400 text-[11px] max-w-xs">
                          {log.errorMessage ? (
                            <span className="text-rose-400 font-bold block leading-tight">{log.errorMessage}</span>
                          ) : (
                            <span className="text-slate-400 block truncate">{log.payloadDiff}</span>
                          )}
                          <span className="text-[9px] text-slate-500 block mt-0.5">Worker: {log.operator || "System"}</span>
                        </td>
                        <td className="p-3 text-right">
                          {(log.status === "FAILED" || log.status === "DLQ_RETRY") ? (
                            <button
                              type="button"
                              onClick={() => handleRetryLog(log.id)}
                              disabled={isResyncing === log.id}
                              className="bg-amber-500/20 hover:bg-amber-500/30 border border-amber-500/50 text-amber-400 hover:text-amber-300 px-2.5 py-1 text-[10px] font-bold uppercase transition-all cursor-pointer flex items-center gap-1 ml-auto"
                            >
                              <RotateCcw className={`w-3 h-3 ${isResyncing === log.id ? "animate-spin" : ""}`} />
                              {isResyncing === log.id ? "Syncing..." : "Re-Sync Now"}
                            </button>
                          ) : (
                            <span className="text-[10px] text-slate-600 font-mono italic">Validated</span>
                          )}
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>

          </div>
        </div>
      )}

      {/* TAB 2: TOPOLOGI ARSITEKTUR */}
      {activeTab === "topology" && (
        <div className="bg-[#0a0a0a] border border-[#222] p-6 space-y-6">
          <div className="space-y-1">
            <h2 className="text-base font-black text-white uppercase font-mono tracking-tight flex items-center gap-2">
              <Server className="w-5 h-5 text-[#facc15]" />
              TOPOLOGI REPLIKASI SUPABASE ➔ FIREBASE
            </h2>
            <p className="text-xs text-slate-400 font-mono">
              Alur pemrosesan data otomatis berbasis Change Data Capture (CDC) dan Dual-Write Event Worker.
            </p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-4 gap-4 relative py-4">
            
            {/* Step 1: Supabase Primary */}
            <div className="bg-[#111] border-2 border-cyan-500/40 p-4 space-y-3 relative text-center">
              <div className="p-2 bg-cyan-500/10 border border-cyan-500/30 text-cyan-400 w-10 h-10 mx-auto flex items-center justify-center">
                <Database className="w-5 h-5" />
              </div>
              <div>
                <span className="text-[10px] font-mono text-cyan-400 font-bold uppercase block">Langkah 1: Primary DB</span>
                <h3 className="text-xs font-bold text-white uppercase font-mono">Supabase PostgreSQL</h3>
              </div>
              <p className="text-[10px] text-slate-400 font-mono leading-relaxed">
                Tabel master (`employees`, `attendance_logs`) mencatat operasi INSERT / UPDATE / DELETE di PostgreSQL Write-Ahead Log (WAL).
              </p>
            </div>

            {/* Step 2: Supabase Webhook / CDC */}
            <div className="bg-[#111] border-2 border-indigo-500/40 p-4 space-y-3 relative text-center">
              <div className="p-2 bg-indigo-500/10 border border-indigo-500/30 text-indigo-400 w-10 h-10 mx-auto flex items-center justify-center">
                <Radio className="w-5 h-5" />
              </div>
              <div>
                <span className="text-[10px] font-mono text-indigo-400 font-bold uppercase block">Langkah 2: CDC Listener</span>
                <h3 className="text-xs font-bold text-white uppercase font-mono">Supabase Webhook Trigger</h3>
              </div>
              <p className="text-[10px] text-slate-400 font-mono leading-relaxed">
                Supabase Realtime / Database Webhook menembakkan HTTP Event Payload secara asynchronous begitu data berubah.
              </p>
            </div>

            {/* Step 3: Node.js Sync Worker */}
            <div className="bg-[#111] border-2 border-[#facc15]/40 p-4 space-y-3 relative text-center">
              <div className="p-2 bg-[#facc15]/10 border border-[#facc15]/30 text-[#facc15] w-10 h-10 mx-auto flex items-center justify-center">
                <Cpu className="w-5 h-5" />
              </div>
              <div>
                <span className="text-[10px] font-mono text-[#facc15] font-bold uppercase block">Langkah 3: Middleware</span>
                <h3 className="text-xs font-bold text-white uppercase font-mono">Sync Worker Node.js</h3>
              </div>
              <p className="text-[10px] text-slate-400 font-mono leading-relaxed">
                Worker memvalidasi signature, memformat payload schema, serta menganonimkan PII sebelum dikirim ke Firebase SDK.
              </p>
            </div>

            {/* Step 4: Firebase Firestore Target */}
            <div className="bg-[#111] border-2 border-amber-500/40 p-4 space-y-3 relative text-center">
              <div className="p-2 bg-amber-500/10 border border-amber-500/30 text-amber-400 w-10 h-10 mx-auto flex items-center justify-center">
                <CloudCheck className="w-5 h-5" />
              </div>
              <div>
                <span className="text-[10px] font-mono text-amber-400 font-bold uppercase block">Langkah 4: Read Replica</span>
                <h3 className="text-xs font-bold text-white uppercase font-mono">Firebase Firestore</h3>
              </div>
              <p className="text-[10px] text-slate-400 font-mono leading-relaxed">
                Dokumen Firestore ter-update secara otomatis ('employees/&#123;id&#125;'). Siap dikonsumsi aplikasi mobile/web real-time.
              </p>
            </div>

          </div>

          <div className="bg-[#050505] border border-[#222] p-4 text-xs font-mono space-y-2">
            <h4 className="font-bold text-[#facc15] uppercase">Prinsip Konsistensi & Keamanan:</h4>
            <ul className="list-disc list-inside text-slate-300 space-y-1 text-[11px] leading-relaxed">
              <li><strong className="text-white">Single Source of Truth:</strong> Supabase PostgreSQL selalu menjadi kebenaran tunggal data. Perubahan di Firestore bersifat read-only / replica.</li>
              <li><strong className="text-white">Low Latency Guarantee:</strong> Pipa sinkronisasi disetel menggunakan HTTP/2 Keep-Alive dengan latensi rata-rata 8-15 milidetik.</li>
              <li><strong className="text-white">Automatic Retry & Dead Letter Queue:</strong> Apabila koneksi Firebase terganggu, event disimpan di DLQ PostgreSQL untuk di-retry otomatis.</li>
            </ul>
          </div>
        </div>
      )}

      {/* TAB 3: LIVE LOG EVENT STREAM */}
      {activeTab === "logs" && (
        <div className="bg-[#0a0a0a] border border-[#222] overflow-hidden space-y-0">
          <div className="p-4 bg-[#050505] border-b border-[#222] flex flex-wrap items-center justify-between gap-3">
            <div className="flex items-center gap-2">
              <Activity className="w-4 h-4 text-emerald-400 animate-pulse" />
              <h2 className="text-xs font-black text-white uppercase font-mono tracking-wider">
                LOG STREAM REPLIKASI LIVE & HISTORI AUDIT CDC
              </h2>
            </div>
            <div className="flex items-center gap-2 font-mono text-xs">
              <button
                type="button"
                onClick={handleExportAuditCSV}
                className="bg-[#111] hover:bg-[#222] text-[#facc15] border border-[#333] hover:border-[#facc15] px-3 py-1 text-xs font-mono font-bold uppercase transition-all cursor-pointer flex items-center gap-1.5"
              >
                <FileSpreadsheet className="w-3.5 h-3.5 text-[#facc15]" />
                Unduh CSV Audit
              </button>
            </div>
          </div>

          <div className="p-3 bg-[#0d1117] border-b border-[#222] flex flex-wrap items-center justify-between gap-3 font-mono text-xs">
            <div className="flex flex-wrap items-center gap-2">
              <div className="relative">
                <Search className="w-3.5 h-3.5 text-slate-500 absolute left-2.5 top-2.5" />
                <input
                  type="text"
                  placeholder="Cari ID Record / Error..."
                  value={logSearchQuery}
                  onChange={(e) => setLogSearchQuery(e.target.value)}
                  className="bg-[#050505] border border-[#333] focus:border-[#facc15] text-slate-200 pl-8 pr-3 py-1.5 text-xs font-mono outline-none w-48 sm:w-64"
                />
              </div>

              <div className="flex items-center gap-1 bg-[#050505] border border-[#333] p-1">
                <Filter className="w-3 h-3 text-slate-500 ml-1" />
                <span className="text-[10px] text-slate-400 uppercase font-bold mr-1">Status:</span>
                {["ALL", "SUCCESS", "DLQ_RETRY", "FAILED"].map(statusKey => (
                  <button
                    key={statusKey}
                    type="button"
                    onClick={() => setLogStatusFilter(statusKey)}
                    className={`px-2 py-0.5 text-[10px] font-bold uppercase cursor-pointer ${
                      logStatusFilter === statusKey
                        ? "bg-[#facc15] text-black font-black"
                        : "text-slate-400 hover:text-white"
                    }`}
                  >
                    {statusKey === "ALL" ? "Semua" : statusKey === "SUCCESS" ? "Sukses" : statusKey === "DLQ_RETRY" ? "DLQ Retry" : "Gagal"}
                  </button>
                ))}
              </div>
            </div>

            <div className="text-[11px] text-slate-400">
              Menampilkan {filteredLogs.length} dari {cdcLogs.length} Event
            </div>
          </div>

          <div className="overflow-x-auto">
            <table className="w-full text-left font-mono text-xs">
              <thead>
                <tr className="border-b border-[#222] bg-[#0d1117] text-slate-400 uppercase text-[10px]">
                  <th className="p-3">Waktu</th>
                  <th className="p-3">Modul Aplikasi</th>
                  <th className="p-3">Aksi CDC</th>
                  <th className="p-3">Record ID / Key</th>
                  <th className="p-3">Payload Diff / Error Log</th>
                  <th className="p-3">Latensi</th>
                  <th className="p-3">Status</th>
                  <th className="p-3 text-right">Aksi Audit</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-[#1a1a1a]">
                {filteredLogs.map((log, idx) => (
                  <tr key={log.id} className={idx === 0 ? "bg-emerald-500/5 transition-colors" : "hover:bg-[#111]"}>
                    <td className="p-3 text-slate-400 whitespace-nowrap text-[11px]">{log.timestamp}</td>
                    <td className="p-3 text-white font-bold">{log.module}</td>
                    <td className="p-3">
                      <span className={`px-2 py-0.5 text-[10px] font-bold uppercase ${
                        log.action === "INSERT" ? "bg-emerald-500/10 border border-emerald-500/30 text-emerald-400" :
                        log.action === "UPDATE" ? "bg-cyan-500/10 border border-cyan-500/30 text-cyan-400" :
                        "bg-rose-500/10 border border-rose-500/30 text-rose-400"
                      }`}>
                        {log.action}
                      </span>
                    </td>
                    <td className="p-3 text-slate-200 font-mono text-[11px]">{log.recordId}</td>
                    <td className="p-3 text-slate-400 text-[10px] max-w-xs">
                      {log.errorMessage ? (
                        <span className="text-rose-400 font-bold block">{log.errorMessage}</span>
                      ) : (
                        <span className="truncate block">{log.payloadDiff}</span>
                      )}
                    </td>
                    <td className="p-3 text-[#facc15] font-bold">{log.latencyMs} ms</td>
                    <td className="p-3">
                      {log.status === "SUCCESS" && (
                        <span className="px-2 py-0.5 bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 text-[10px] font-bold">
                          SUKSES
                        </span>
                      )}
                      {log.status === "DLQ_RETRY" && (
                        <span className="px-2 py-0.5 bg-amber-500/10 border border-amber-500/30 text-amber-400 text-[10px] font-bold">
                          DLQ RETRY
                        </span>
                      )}
                      {log.status === "FAILED" && (
                        <span className="px-2 py-0.5 bg-rose-500/10 border border-rose-500/30 text-rose-400 text-[10px] font-bold">
                          GAGAL
                        </span>
                      )}
                    </td>
                    <td className="p-3 text-right">
                      {(log.status === "FAILED" || log.status === "DLQ_RETRY") ? (
                        <button
                          type="button"
                          onClick={() => handleRetryLog(log.id)}
                          disabled={isResyncing === log.id}
                          className="bg-amber-500/20 hover:bg-amber-500/30 border border-amber-500/50 text-amber-400 px-2 py-0.5 text-[10px] font-bold uppercase cursor-pointer"
                        >
                          Re-Sync
                        </button>
                      ) : (
                        <span className="text-[10px] text-slate-600 font-mono italic">OK</span>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

    </div>
  );
};
