/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState, useEffect, useMemo } from "react";
import { 
  Database, 
  Server, 
  ArrowRight, 
  RefreshCw, 
  ShieldCheck, 
  Sliders, 
  Activity, 
  Play, 
  Pause, 
  CheckCircle2, 
  AlertTriangle, 
  XCircle, 
  Cpu, 
  HardDrive, 
  Zap, 
  Layers, 
  Search, 
  Filter, 
  Eye, 
  Plus, 
  Trash2, 
  Clock, 
  FileCode2, 
  ArrowLeftRight, 
  Terminal, 
  Check, 
  Settings, 
  Copy,
  Lock,
  Boxes,
  HelpCircle,
  Smartphone
} from "lucide-react";
import { Employee } from "../types";
import { DataReplicationDashboard } from "./DataReplicationDashboard";
import { BackendDatabaseManager } from "./BackendDatabaseManager";
import { CtoApkBuildManager } from "./CtoApkBuildManager";

interface CtoDataReplicationModuleProps {
  currentUser: Employee;
  employees: Employee[];
}

// Replication Pipeline Interface
interface ReplicationPipeline {
  id: string;
  name: string;
  sourceType: "PostgreSQL Primary" | "MySQL Legacy" | "Supabase Cloud" | "MongoDB Cluster" | "REST API Feed";
  sourceHost: string;
  sourceDb: string;
  sourceTable: string;
  
  targetType: "PostgreSQL Read-Replica" | "BigQuery Analytics" | "Redis Cache Cluster" | "Elasticsearch Sink" | "Disaster Recovery Node" | "Firebase Firestore";
  targetHost: string;
  targetDb: string;
  targetTable: string;

  syncMode: "CDC (Change Data Capture)" | "Scheduled Batch (Cron)" | "Real-time Event Stream" | "Manual Trigger";
  status: "ACTIVE" | "PAUSED" | "SYNCING" | "ERROR" | "IDLE";
  
  // Metrics
  lastSyncTime: string;
  totalRecordsSynced: number;
  syncSpeedRps: number; // Records Per Second
  latencyMs: number;
  dlqCount: number; // Dead Letter Queue count

  // Rules & Transformation
  anonymizePii: boolean;
  conflictStrategy: "Source Wins" | "Target Wins" | "Last Write Wins (LWW)";
  batchSize: number;
  retryAttempts: number;
}

// Log Event Interface
interface ReplicationLog {
  id: string;
  timestamp: string;
  pipelineId: string;
  pipelineName: string;
  action: "INSERT" | "UPDATE" | "DELETE" | "BATCH_SYNC" | "DLQ_RETRY";
  sourceRecordId: string;
  status: "SUCCESS" | "FAILED" | "PENDING";
  latencyMs: number;
  details: string;
}

const INITIAL_PIPELINES: ReplicationPipeline[] = [
  {
    id: "pipe-sb-fb-01",
    name: "Supabase Cloud ➔ Firebase Firestore CDC Dual-Write Sync Engine",
    sourceType: "Supabase Cloud",
    sourceHost: "https://ku5fhm3xfhqlogsf6ndd4t.supabase.co:5432",
    sourceDb: "public",
    sourceTable: "employees",
    targetType: "Firebase Firestore",
    targetHost: "firestore.googleapis.com/v1/projects/ems-firebase-sync",
    targetDb: "(default)",
    targetTable: "employees",
    syncMode: "CDC (Change Data Capture)",
    status: "ACTIVE",
    lastSyncTime: "Baru saja (0.1s lalu)",
    totalRecordsSynced: 342150,
    syncSpeedRps: 520,
    latencyMs: 12,
    dlqCount: 0,
    anonymizePii: false,
    conflictStrategy: "Source Wins",
    batchSize: 200,
    retryAttempts: 5
  },
  {
    id: "pipe-01",
    name: "Master Employee CDC Replication (Prod ➔ Read Replica)",
    sourceType: "PostgreSQL Primary",
    sourceHost: "pg-prod-primary.garda.internal:5432",
    sourceDb: "ems_prod_db",
    sourceTable: "employees_master",
    targetType: "PostgreSQL Read-Replica",
    targetHost: "pg-read-replica-01.garda.internal:5432",
    targetDb: "ems_read_db",
    targetTable: "employees_replica",
    syncMode: "CDC (Change Data Capture)",
    status: "ACTIVE",
    lastSyncTime: "Baru saja (0.2s lalu)",
    totalRecordsSynced: 128450,
    syncSpeedRps: 240,
    latencyMs: 8,
    dlqCount: 0,
    anonymizePii: false,
    conflictStrategy: "Source Wins",
    batchSize: 500,
    retryAttempts: 3
  },
  {
    id: "pipe-02",
    name: "HR Analytics Data Warehouse Sync (Prod ➔ BigQuery)",
    sourceType: "PostgreSQL Primary",
    sourceHost: "pg-prod-primary.garda.internal:5432",
    sourceDb: "ems_prod_db",
    sourceTable: "kpi_performance_logs",
    targetType: "BigQuery Analytics",
    targetHost: "bigquery.googleapis.com/projects/garda-dw",
    targetDb: "hr_analytics_dataset",
    targetTable: "fact_employee_kpi",
    syncMode: "Scheduled Batch (Cron)",
    status: "ACTIVE",
    lastSyncTime: "12 menit lalu",
    totalRecordsSynced: 420900,
    syncSpeedRps: 1800,
    latencyMs: 145,
    dlqCount: 2,
    anonymizePii: true,
    conflictStrategy: "Last Write Wins (LWW)",
    batchSize: 2000,
    retryAttempts: 5
  },
  {
    id: "pipe-03",
    name: "Employee Search Index Replicator (Prod ➔ Elasticsearch)",
    sourceType: "PostgreSQL Primary",
    sourceHost: "pg-prod-primary.garda.internal:5432",
    sourceDb: "ems_prod_db",
    sourceTable: "employees_master",
    targetType: "Elasticsearch Sink",
    targetHost: "es-cluster.garda.internal:9200",
    targetDb: "search_index",
    targetTable: "idx_employee_directory",
    syncMode: "Real-time Event Stream",
    status: "ACTIVE",
    lastSyncTime: "1 menit lalu",
    totalRecordsSynced: 95300,
    syncSpeedRps: 110,
    latencyMs: 18,
    dlqCount: 0,
    anonymizePii: true,
    conflictStrategy: "Source Wins",
    batchSize: 100,
    retryAttempts: 3
  },
  {
    id: "pipe-04",
    name: "Disaster Recovery Database Mirror (Jakarta ➔ Surabaya DR)",
    sourceType: "PostgreSQL Primary",
    sourceHost: "pg-prod-primary.garda.internal:5432",
    sourceDb: "ems_prod_db",
    sourceTable: "* (All Tables)",
    targetType: "Disaster Recovery Node",
    targetHost: "dr-surabaya.garda.internal:5432",
    targetDb: "ems_dr_db",
    targetTable: "* (All Tables)",
    syncMode: "CDC (Change Data Capture)",
    status: "ACTIVE",
    lastSyncTime: "3 detik lalu",
    totalRecordsSynced: 1840000,
    syncSpeedRps: 650,
    latencyMs: 28,
    dlqCount: 0,
    anonymizePii: false,
    conflictStrategy: "Source Wins",
    batchSize: 1000,
    retryAttempts: 10
  }
];

const INITIAL_LOGS: ReplicationLog[] = [
  {
    id: "log-sb-fb-100",
    timestamp: new Date(Date.now() - 1000 * 5).toLocaleTimeString(),
    pipelineId: "pipe-sb-fb-01",
    pipelineName: "Supabase Cloud ➔ Firebase Firestore CDC Dual-Write",
    action: "UPDATE",
    sourceRecordId: "EMP-CEO-01 (Bambang Hartono)",
    status: "SUCCESS",
    latencyMs: 11,
    details: "CDC Webhook fired. Updated Firestore doc 'employees/emp-ceo-01' with merged payload from Supabase WAL."
  },
  {
    id: "log-sb-fb-101",
    timestamp: new Date(Date.now() - 1000 * 25).toLocaleTimeString(),
    pipelineId: "pipe-sb-fb-01",
    pipelineName: "Supabase Cloud ➔ Firebase Firestore CDC Dual-Write",
    action: "INSERT",
    sourceRecordId: "EMP-NEW-99 (Siti Rahma)",
    status: "SUCCESS",
    latencyMs: 14,
    details: "Supabase insert trigger triggered Node.js worker. Firestore document created with _replicatedFrom='supabase'."
  },
  {
    id: "log-1001",
    timestamp: new Date(Date.now() - 1000 * 45).toLocaleTimeString(),
    pipelineId: "pipe-01",
    pipelineName: "Master Employee CDC Replication",
    action: "UPDATE",
    sourceRecordId: "EMP-001 (Dian Ermawan)",
    status: "SUCCESS",
    latencyMs: 6,
    details: "Replicated field 'position' and 'kpiScore' via WAL streaming. Source CRC matching."
  },
  {
    id: "log-1002",
    timestamp: new Date(Date.now() - 1000 * 90).toLocaleTimeString(),
    pipelineId: "pipe-02",
    pipelineName: "HR Analytics Data Warehouse Sync",
    action: "BATCH_SYNC",
    sourceRecordId: "Batch #4421 (2,000 items)",
    status: "SUCCESS",
    latencyMs: 142,
    details: "Bulk insert to BigQuery dataset succeeded. PII anonymization hash applied."
  }
];

export default function CtoDataReplicationModule({
  currentUser,
  employees
}: CtoDataReplicationModuleProps) {
  const [pipelines, setPipelines] = useState<ReplicationPipeline[]>(INITIAL_PIPELINES);
  const [logs, setLogs] = useState<ReplicationLog[]>(INITIAL_LOGS);
  const [selectedPipelineId, setSelectedPipelineId] = useState<string>("pipe-sb-fb-01");
  const [activeTab, setActiveTab] = useState<"dashboard_supabase_firebase" | "pipelines" | "topology" | "logs" | "dlq" | "config" | "backend_sql_triggers_passwords" | "apk_build_manager">("dashboard_supabase_firebase");

  const [isSimulatingSync, setIsSimulatingSync] = useState<boolean>(false);
  const [simulationProgress, setSimulationProgress] = useState<number>(0);

  // Modal / Form state for creating new Replication Pipeline
  const [isCreateModalOpen, setIsCreateModalOpen] = useState<boolean>(false);
  const [newPipeline, setNewPipeline] = useState<Partial<ReplicationPipeline>>({
    name: "New Data Replication Pipeline",
    sourceType: "PostgreSQL Primary",
    sourceHost: "127.0.0.1:5432",
    sourceDb: "source_db",
    sourceTable: "employees",
    targetType: "PostgreSQL Read-Replica",
    targetHost: "replica.internal:5432",
    targetDb: "target_replica_db",
    targetTable: "employees_replica",
    syncMode: "CDC (Change Data Capture)",
    anonymizePii: false,
    conflictStrategy: "Source Wins",
    batchSize: 500,
    retryAttempts: 3
  });

  const selectedPipeline = useMemo(() => {
    return pipelines.find(p => p.id === selectedPipelineId) || pipelines[0];
  }, [pipelines, selectedPipelineId]);

  // Aggregate stats
  const totalSyncedAll = useMemo(() => {
    return pipelines.reduce((acc, p) => acc + p.totalRecordsSynced, 0);
  }, [pipelines]);

  const totalDlq = useMemo(() => {
    return pipelines.reduce((acc, p) => acc + p.dlqCount, 0);
  }, [pipelines]);

  const avgLatency = useMemo(() => {
    if (pipelines.length === 0) return 0;
    const sum = pipelines.reduce((acc, p) => acc + p.latencyMs, 0);
    return Math.round(sum / pipelines.length);
  }, [pipelines]);

  // Toggle pipeline active status
  const togglePipelineStatus = (id: string) => {
    setPipelines(prev => prev.map(p => {
      if (p.id === id) {
        const nextStatus = p.status === "ACTIVE" ? "PAUSED" : "ACTIVE";
        return { ...p, status: nextStatus };
      }
      return p;
    }));
  };

  // Trigger manual simulation of data replication
  const handleTriggerReplication = (pipeline: ReplicationPipeline) => {
    setIsSimulatingSync(true);
    setSimulationProgress(10);

    const step1 = setTimeout(() => setSimulationProgress(35), 600);
    const step2 = setTimeout(() => setSimulationProgress(70), 1200);
    const step3 = setTimeout(() => {
      setSimulationProgress(100);

      // Randomly pick an employee from database to replicate
      const randomEmp = employees[Math.floor(Math.random() * employees.length)] || employees[0];
      const newSyncedRecordCount = Math.floor(Math.random() * 50) + 10;

      // Update Pipeline statistics
      setPipelines(prev => prev.map(p => {
        if (p.id === pipeline.id) {
          return {
            ...p,
            totalRecordsSynced: p.totalRecordsSynced + newSyncedRecordCount,
            lastSyncTime: "Baru saja",
            status: "ACTIVE"
          };
        }
        return p;
      }));

      // Append new log entry
      const newLog: ReplicationLog = {
        id: `log-${Date.now()}`,
        timestamp: new Date().toLocaleTimeString(),
        pipelineId: pipeline.id,
        pipelineName: pipeline.name,
        action: Math.random() > 0.3 ? "UPDATE" : "INSERT",
        sourceRecordId: `${randomEmp.nip} (${randomEmp.name})`,
        status: "SUCCESS",
        latencyMs: Math.floor(Math.random() * 15) + 5,
        details: `Replikasi ${newSyncedRecordCount} record via Middleware CDC Engine [Source: ${pipeline.sourceDb} ➔ Target: ${pipeline.targetDb}]`
      };

      setLogs(prev => [newLog, ...prev]);

      setTimeout(() => {
        setIsSimulatingSync(false);
        setSimulationProgress(0);
      }, 500);

    }, 1800);
  };

  // Process Dead Letter Queue (DLQ) Retry
  const handleReprocessDlq = (pipelineId: string) => {
    setPipelines(prev => prev.map(p => {
      if (p.id === pipelineId && p.dlqCount > 0) {
        return { ...p, dlqCount: 0 };
      }
      return p;
    }));

    const newLog: ReplicationLog = {
      id: `log-dlq-${Date.now()}`,
      timestamp: new Date().toLocaleTimeString(),
      pipelineId: pipelineId,
      pipelineName: selectedPipeline?.name || "Pipeline",
      action: "DLQ_RETRY",
      sourceRecordId: "Batch DLQ Re-drive",
      status: "SUCCESS",
      latencyMs: 24,
      details: "Seluruh antrean pesan gagal (Dead Letter Queue) berhasil diproses ulang dan direplikasikan ke target sink."
    };

    setLogs(prev => [newLog, ...prev]);
    alert("Berhasil memproses ulang pesan gagal pada Dead Letter Queue (DLQ)!");
  };

  // Create new pipeline handler
  const handleCreatePipeline = (e: React.FormEvent) => {
    e.preventDefault();
    const created: ReplicationPipeline = {
      id: `pipe-0${pipelines.length + 1}`,
      name: newPipeline.name || "Custom Data Replication Pipeline",
      sourceType: newPipeline.sourceType || "PostgreSQL Primary",
      sourceHost: newPipeline.sourceHost || "127.0.0.1:5432",
      sourceDb: newPipeline.sourceDb || "source_db",
      sourceTable: newPipeline.sourceTable || "employees",
      targetType: newPipeline.targetType || "PostgreSQL Read-Replica",
      targetHost: newPipeline.targetHost || "replica.internal:5432",
      targetDb: newPipeline.targetDb || "target_db",
      targetTable: newPipeline.targetTable || "employees_replica",
      syncMode: newPipeline.syncMode || "CDC (Change Data Capture)",
      status: "ACTIVE",
      lastSyncTime: "Baru saja dibuat",
      totalRecordsSynced: 0,
      syncSpeedRps: 150,
      latencyMs: 12,
      dlqCount: 0,
      anonymizePii: newPipeline.anonymizePii || false,
      conflictStrategy: newPipeline.conflictStrategy || "Source Wins",
      batchSize: newPipeline.batchSize || 500,
      retryAttempts: newPipeline.retryAttempts || 3
    };

    setPipelines(prev => [...prev, created]);
    setSelectedPipelineId(created.id);
    setIsCreateModalOpen(false);
  };

  return (
    <div className="space-y-6 font-sans">
      
      {/* Top Banner Header: Backend Division / CTO Scope */}
      <div className="bg-gradient-to-r from-slate-900 via-sky-950 to-blue-950 border border-sky-500/30 rounded-2xl p-6 text-white shadow-xl relative overflow-hidden">
        <div className="absolute top-0 right-0 w-96 h-96 bg-sky-500/10 rounded-full blur-3xl pointer-events-none"></div>

        <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4 relative z-10">
          <div>
            <div className="flex items-center gap-2 mb-2">
              <span className="bg-sky-500/20 text-sky-300 border border-sky-400/30 text-[10px] font-mono font-bold uppercase px-2.5 py-0.5 rounded-md flex items-center gap-1">
                <Cpu className="w-3 h-3 text-sky-400" />
                Direktorat CTO • Divisi Backend Engineering
              </span>
              <span className="bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 text-[10px] font-mono font-bold uppercase px-2.5 py-0.5 rounded-md flex items-center gap-1">
                <span className="w-2 h-2 bg-emerald-400 rounded-full animate-pulse"></span>
                Engine Middleware v3.4 Active
              </span>
            </div>

            <h2 className="text-xl sm:text-2xl font-black uppercase tracking-tight text-white flex items-center gap-2.5">
              <ArrowLeftRight className="w-6 h-6 text-sky-400" />
              Middleware Replikasi Data Source & Destination
            </h2>
            <p className="text-xs sm:text-sm text-slate-300 mt-1 max-w-3xl leading-relaxed">
              Arsitektur penanganan tugas Divisi Backend CTO untuk mengelola sinkronisasi data real-time CDC (Change Data Capture), transformasi filter, pencegahan konflik, dan replikasi antar basis data utama dan target sink.
            </p>
          </div>

          <div className="flex items-center gap-2 shrink-0">
            <button
              onClick={() => setIsCreateModalOpen(true)}
              className="px-4 py-2.5 bg-gradient-to-r from-sky-500 to-blue-600 hover:from-sky-400 hover:to-blue-500 text-slate-950 font-black text-xs uppercase tracking-wider rounded-xl transition-all shadow-lg shadow-sky-500/25 flex items-center gap-2 active:scale-95"
            >
              <Plus className="w-4 h-4 text-slate-950" />
              <span>Tambah Pipeline Replikasi</span>
            </button>
          </div>
        </div>

        {/* Real-time Performance Metrics Bar */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mt-6 pt-5 border-t border-sky-800/40 font-mono">
          <div className="bg-slate-900/60 p-3 rounded-xl border border-sky-800/30">
            <span className="text-[10px] text-slate-400 uppercase tracking-wider block">Total Pipeline Replikasi</span>
            <span className="text-lg font-bold text-sky-300 mt-0.5 block">{pipelines.length} Active Engine</span>
          </div>
          <div className="bg-slate-900/60 p-3 rounded-xl border border-sky-800/30">
            <span className="text-[10px] text-slate-400 uppercase tracking-wider block">Total Record Ter-replikasi</span>
            <span className="text-lg font-bold text-emerald-400 mt-0.5 block">{totalSyncedAll.toLocaleString()} Records</span>
          </div>
          <div className="bg-slate-900/60 p-3 rounded-xl border border-sky-800/30">
            <span className="text-[10px] text-slate-400 uppercase tracking-wider block">Rata-rata Latensi Sync</span>
            <span className="text-lg font-bold text-amber-300 mt-0.5 block">{avgLatency} ms</span>
          </div>
          <div className="bg-slate-900/60 p-3 rounded-xl border border-sky-800/30">
            <span className="text-[10px] text-slate-400 uppercase tracking-wider block">Dead Letter Queue (DLQ)</span>
            <span className={`text-lg font-bold mt-0.5 block ${totalDlq > 0 ? "text-rose-400 animate-pulse" : "text-slate-300"}`}>
              {totalDlq} Record Gagal
            </span>
          </div>
        </div>
      </div>

      {/* Main Navigation Tabs */}
      <div className="flex items-center justify-between border-b border-slate-700/80 pb-2">
        <div className="flex items-center gap-2 overflow-x-auto">
          <button
            type="button"
            onClick={() => setActiveTab("dashboard_supabase_firebase")}
            className={`px-3.5 py-2 rounded-xl text-xs font-bold uppercase transition-all flex items-center gap-2 whitespace-nowrap cursor-pointer ${
              activeTab === "dashboard_supabase_firebase"
                ? "bg-[#facc15] text-black shadow-md shadow-[#facc15]/20 font-black"
                : "text-slate-300 hover:text-white hover:bg-slate-800"
            }`}
          >
            <Zap className="w-4 h-4 text-black fill-black" />
            <span>Dashboard Supabase ➔ Firebase</span>
          </button>

          <button
            type="button"
            onClick={() => setActiveTab("pipelines")}
            className={`px-3.5 py-2 rounded-xl text-xs font-bold uppercase transition-all flex items-center gap-2 whitespace-nowrap cursor-pointer ${
              activeTab === "pipelines"
                ? "bg-sky-500 text-slate-950 shadow-md shadow-sky-500/20"
                : "text-slate-300 hover:text-white hover:bg-slate-800"
            }`}
          >
            <Sliders className="w-4 h-4" />
            <span>Matriks Pipeline ({pipelines.length})</span>
          </button>

          <button
            type="button"
            onClick={() => setActiveTab("topology")}
            className={`px-3.5 py-2 rounded-xl text-xs font-bold uppercase transition-all flex items-center gap-2 whitespace-nowrap cursor-pointer ${
              activeTab === "topology"
                ? "bg-sky-500 text-slate-950 shadow-md shadow-sky-500/20"
                : "text-slate-300 hover:text-white hover:bg-slate-800"
            }`}
          >
            <Boxes className="w-4 h-4" />
            <span>Topologi & Diagram Replikasi</span>
          </button>

          <button
            type="button"
            onClick={() => setActiveTab("logs")}
            className={`px-3.5 py-2 rounded-xl text-xs font-bold uppercase transition-all flex items-center gap-2 whitespace-nowrap cursor-pointer ${
              activeTab === "logs"
                ? "bg-sky-500 text-slate-950 shadow-md shadow-sky-500/20"
                : "text-slate-300 hover:text-white hover:bg-slate-800"
            }`}
          >
            <Terminal className="w-4 h-4" />
            <span>Live Sync Logs ({logs.length})</span>
          </button>

          <button
            type="button"
            onClick={() => setActiveTab("dlq")}
            className={`px-3.5 py-2 rounded-xl text-xs font-bold uppercase transition-all flex items-center gap-2 whitespace-nowrap cursor-pointer ${
              activeTab === "dlq"
                ? "bg-rose-500 text-white shadow-md shadow-rose-500/20"
                : "text-slate-300 hover:text-white hover:bg-slate-800"
            }`}
          >
            <AlertTriangle className="w-4 h-4 text-amber-400" />
            <span>Dead Letter Queue ({totalDlq})</span>
          </button>

          <button
            type="button"
            onClick={() => setActiveTab("backend_sql_triggers_passwords")}
            className={`px-3.5 py-2 rounded-xl text-xs font-bold uppercase transition-all flex items-center gap-2 whitespace-nowrap cursor-pointer ${
              activeTab === "backend_sql_triggers_passwords"
                ? "bg-amber-400 text-slate-950 shadow-md shadow-amber-400/20 font-black"
                : "text-amber-300 hover:text-white hover:bg-slate-800 border border-amber-500/30"
            }`}
          >
            <Database className="w-4 h-4" />
            <span>SQL Backend, Triggers & Passwords</span>
          </button>

          <button
            type="button"
            onClick={() => setActiveTab("apk_build_manager")}
            className={`px-3.5 py-2 rounded-xl text-xs font-bold uppercase transition-all flex items-center gap-2 whitespace-nowrap cursor-pointer ${
              activeTab === "apk_build_manager"
                ? "bg-sky-400 text-slate-950 shadow-md shadow-sky-400/20 font-black"
                : "text-sky-300 hover:text-white hover:bg-slate-800 border border-sky-500/30"
            }`}
          >
            <Smartphone className="w-4 h-4 text-sky-400" />
            <span>📱 Build & Distribusi .APK Tenant</span>
          </button>
        </div>

        <div className="hidden md:flex items-center gap-2 text-xs font-mono text-slate-400">
          <span>Backend Engineer: <strong className="text-sky-300">{currentUser.name}</strong></span>
        </div>
      </div>

      {/* SECTION 0: SUPABASE ➔ FIREBASE REAL-TIME REPLICATION DASHBOARD */}
      {activeTab === "dashboard_supabase_firebase" && (
        <DataReplicationDashboard currentUser={currentUser} employees={employees} />
      )}

      {/* SECTION CTO MOBILE APK BUILD & TENANT DISTRIBUTION MANAGER */}
      {activeTab === "apk_build_manager" && (
        <CtoApkBuildManager currentUser={currentUser} />
      )}

      {/* SECTION 1: PIPELINE MATRIX VIEW */}
      {activeTab === "pipelines" && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          
          {/* Left Column: Pipeline Selector */}
          <div className="space-y-3">
            <h3 className="text-xs font-black uppercase text-slate-400 tracking-wider flex items-center gap-1.5">
              <Layers className="w-4 h-4 text-sky-400" />
              Daftar Middleware Pipeline Active
            </h3>

            <div className="space-y-2">
              {pipelines.map((pipe) => {
                const isSelected = pipe.id === selectedPipelineId;
                return (
                  <div
                    key={pipe.id}
                    onClick={() => setSelectedPipelineId(pipe.id)}
                    className={`p-4 rounded-2xl border transition-all cursor-pointer relative overflow-hidden ${
                      isSelected
                        ? "bg-slate-800/90 border-sky-400 shadow-lg shadow-sky-500/10 ring-1 ring-sky-400/40 text-white"
                        : "bg-slate-900/60 border-slate-800 hover:border-slate-700 text-slate-300 hover:bg-slate-800/50"
                    }`}
                  >
                    <div className="flex items-start justify-between gap-2">
                      <div>
                        <span className="text-[10px] font-mono text-sky-400 font-bold uppercase">
                          {pipe.id} • {pipe.syncMode}
                        </span>
                        <h4 className="text-sm font-bold text-white mt-0.5 line-clamp-1">
                          {pipe.name}
                        </h4>
                      </div>

                      <span className={`px-2 py-0.5 rounded text-[10px] font-mono font-bold uppercase shrink-0 ${
                        pipe.status === "ACTIVE"
                          ? "bg-emerald-500/20 text-emerald-400 border border-emerald-500/30"
                          : "bg-amber-500/20 text-amber-400 border border-amber-500/30"
                      }`}>
                        {pipe.status}
                      </span>
                    </div>

                    {/* Source -> Target Visual Badge */}
                    <div className="mt-3 pt-3 border-t border-slate-800/80 flex items-center justify-between text-[11px] font-mono text-slate-400">
                      <div className="flex items-center gap-1">
                        <Database className="w-3.5 h-3.5 text-blue-400" />
                        <span className="truncate max-w-[100px]">{pipe.sourceDb}</span>
                      </div>
                      <ArrowRight className="w-3.5 h-3.5 text-slate-500 shrink-0" />
                      <div className="flex items-center gap-1">
                        <Server className="w-3.5 h-3.5 text-sky-400" />
                        <span className="truncate max-w-[100px]">{pipe.targetDb}</span>
                      </div>
                    </div>

                    <div className="mt-2 flex items-center justify-between text-[10px] font-mono text-slate-400">
                      <span>Records: <strong className="text-white">{pipe.totalRecordsSynced.toLocaleString()}</strong></span>
                      <span>Latency: <strong className="text-amber-300">{pipe.latencyMs}ms</strong></span>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Right Column: Detailed Configuration & Trigger Controller */}
          <div className="lg:col-span-2 space-y-6">
            
            {/* Simulation Progress Alert Banner */}
            {isSimulatingSync && (
              <div className="bg-sky-950/90 border border-sky-400/50 p-4 rounded-2xl text-white space-y-2 animate-pulse">
                <div className="flex items-center justify-between text-xs font-mono font-bold uppercase">
                  <span className="flex items-center gap-2 text-sky-300">
                    <RefreshCw className="w-4 h-4 animate-spin text-sky-400" />
                    Proses Replikasi Data Sedang Berjalan (Middleware Event CDC)...
                  </span>
                  <span>{simulationProgress}%</span>
                </div>
                <div className="w-full bg-slate-800 h-2 rounded-full overflow-hidden">
                  <div 
                    className="bg-gradient-to-r from-sky-500 to-emerald-400 h-full transition-all duration-300"
                    style={{ width: `${simulationProgress}%` }}
                  ></div>
                </div>
              </div>
            )}

            {/* Selected Pipeline Control Card */}
            <div className="bg-slate-900/80 border border-slate-800 rounded-2xl p-6 space-y-6">
              
              <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 pb-4 border-b border-slate-800">
                <div>
                  <span className="text-[10px] font-mono text-sky-400 font-bold uppercase">
                    DETAIL KONFIGURASI PIPELINE REPLIKASI • {selectedPipeline.id}
                  </span>
                  <h3 className="text-lg font-black text-white mt-0.5">
                    {selectedPipeline.name}
                  </h3>
                </div>

                <div className="flex items-center gap-2">
                  <button
                    onClick={() => togglePipelineStatus(selectedPipeline.id)}
                    className={`px-3 py-1.5 rounded-xl text-xs font-bold uppercase tracking-wider transition-all flex items-center gap-1.5 ${
                      selectedPipeline.status === "ACTIVE"
                        ? "bg-amber-500/20 text-amber-300 border border-amber-500/40 hover:bg-amber-500/30"
                        : "bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 hover:bg-emerald-500/30"
                    }`}
                  >
                    {selectedPipeline.status === "ACTIVE" ? (
                      <>
                        <Pause className="w-3.5 h-3.5" />
                        <span>Jeda Engine</span>
                      </>
                    ) : (
                      <>
                        <Play className="w-3.5 h-3.5" />
                        <span>Aktifkan Engine</span>
                      </>
                    )}
                  </button>

                  <button
                    onClick={() => handleTriggerReplication(selectedPipeline)}
                    disabled={isSimulatingSync || selectedPipeline.status !== "ACTIVE"}
                    className="px-4 py-1.5 bg-gradient-to-r from-emerald-500 to-teal-500 hover:from-emerald-400 hover:to-teal-400 text-slate-950 font-black text-xs uppercase tracking-wider rounded-xl transition-all shadow-md shadow-emerald-500/20 flex items-center gap-1.5 disabled:opacity-50"
                  >
                    <Zap className="w-3.5 h-3.5 text-slate-950" />
                    <span>Jalankan Manual Sync</span>
                  </button>
                </div>
              </div>

              {/* Source vs Target Connection Detail Matrix */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                
                {/* SOURCE ENDPOINT */}
                <div className="bg-slate-950/80 border border-blue-500/30 rounded-xl p-4 space-y-3">
                  <div className="flex items-center justify-between border-b border-slate-800 pb-2">
                    <span className="text-[11px] font-mono font-bold text-blue-400 uppercase flex items-center gap-1.5">
                      <Database className="w-4 h-4 text-blue-400" />
                      SOURCE ENDPOINT (SUMBER)
                    </span>
                    <span className="text-[10px] bg-blue-950 text-blue-300 border border-blue-500/30 px-2 py-0.5 rounded font-mono font-bold">
                      {selectedPipeline.sourceType}
                    </span>
                  </div>

                  <div className="space-y-2 text-xs font-mono">
                    <div>
                      <span className="text-slate-500 block text-[10px]">HOST / CONNECTION STRING:</span>
                      <strong className="text-slate-200">{selectedPipeline.sourceHost}</strong>
                    </div>
                    <div>
                      <span className="text-slate-500 block text-[10px]">DATABASE NAME:</span>
                      <strong className="text-sky-300">{selectedPipeline.sourceDb}</strong>
                    </div>
                    <div>
                      <span className="text-slate-500 block text-[10px]">TABLE / STREAM TOPIC:</span>
                      <strong className="text-emerald-300">{selectedPipeline.sourceTable}</strong>
                    </div>
                  </div>
                </div>

                {/* DESTINATION ENDPOINT */}
                <div className="bg-slate-950/80 border border-sky-500/30 rounded-xl p-4 space-y-3">
                  <div className="flex items-center justify-between border-b border-slate-800 pb-2">
                    <span className="text-[11px] font-mono font-bold text-sky-400 uppercase flex items-center gap-1.5">
                      <Server className="w-4 h-4 text-sky-400" />
                      TARGET ENDPOINT (TUJUAN)
                    </span>
                    <span className="text-[10px] bg-sky-950 text-sky-300 border border-sky-500/30 px-2 py-0.5 rounded font-mono font-bold">
                      {selectedPipeline.targetType}
                    </span>
                  </div>

                  <div className="space-y-2 text-xs font-mono">
                    <div>
                      <span className="text-slate-500 block text-[10px]">HOST / TARGET SINK:</span>
                      <strong className="text-slate-200">{selectedPipeline.targetHost}</strong>
                    </div>
                    <div>
                      <span className="text-slate-500 block text-[10px]">TARGET DB / DATASET:</span>
                      <strong className="text-sky-300">{selectedPipeline.targetDb}</strong>
                    </div>
                    <div>
                      <span className="text-slate-500 block text-[10px]">TARGET TABLE / INDEX:</span>
                      <strong className="text-emerald-300">{selectedPipeline.targetTable}</strong>
                    </div>
                  </div>
                </div>

              </div>

              {/* Middleware Pipeline Rules & Transformation Config */}
              <div className="bg-slate-950/60 border border-slate-800 rounded-xl p-4 space-y-3">
                <h4 className="text-xs font-bold text-slate-300 uppercase tracking-wider flex items-center gap-2 border-b border-slate-800 pb-2">
                  <Sliders className="w-4 h-4 text-sky-400" />
                  Aturan Middleware & Pengaturan Transformasi Data
                </h4>

                <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 font-mono text-xs">
                  <div className="p-3 bg-slate-900 border border-slate-800 rounded-lg">
                    <span className="text-[10px] text-slate-400 block uppercase">Anonymize PII (Privasi):</span>
                    <strong className={`mt-1 block font-bold ${selectedPipeline.anonymizePii ? "text-emerald-400" : "text-slate-400"}`}>
                      {selectedPipeline.anonymizePii ? "AKTIF (Mask NIK/NIP)" : "NON-AKTIF (Raw Data)"}
                    </strong>
                  </div>

                  <div className="p-3 bg-slate-900 border border-slate-800 rounded-lg">
                    <span className="text-[10px] text-slate-400 block uppercase">Strategi Konflik Data:</span>
                    <strong className="text-sky-300 mt-1 block font-bold">
                      {selectedPipeline.conflictStrategy}
                    </strong>
                  </div>

                  <div className="p-3 bg-slate-900 border border-slate-800 rounded-lg">
                    <span className="text-[10px] text-slate-400 block uppercase">Ukuran Batch / Chunk:</span>
                    <strong className="text-amber-300 mt-1 block font-bold">
                      {selectedPipeline.batchSize} records/batch
                    </strong>
                  </div>
                </div>
              </div>

            </div>

          </div>

        </div>
      )}

      {/* SECTION 2: TOPOLOGY DIAGRAM VIEW */}
      {activeTab === "topology" && (
        <div className="bg-slate-900/80 border border-slate-800 rounded-2xl p-6 space-y-6">
          <div className="border-b border-slate-800 pb-4">
            <h3 className="text-base font-black text-white uppercase tracking-tight flex items-center gap-2">
              <Boxes className="w-5 h-5 text-sky-400" />
              Topologi Middleware Replikasi & Data Stream Architecture
            </h3>
            <p className="text-xs text-slate-400 mt-1">
              Visualisasi alur aliran data dari sumber (Source DB) melalui Middleware Change Data Capture (CDC) hingga bermuara ke target (Destination Sink).
            </p>
          </div>

          {/* Interactive Topology Diagram */}
          <div className="p-6 bg-slate-950 border border-slate-800 rounded-2xl space-y-8">
            <div className="grid grid-cols-1 md:grid-cols-5 gap-4 items-center">
              
              {/* Node 1: Source DB */}
              <div className="bg-slate-900 border-2 border-blue-500/50 p-4 rounded-xl text-center space-y-2 relative shadow-lg shadow-blue-500/10">
                <span className="text-[9px] font-mono font-bold uppercase bg-blue-950 text-blue-300 px-2 py-0.5 rounded border border-blue-500/30">
                  SOURCE (SUMBER)
                </span>
                <Database className="w-8 h-8 text-blue-400 mx-auto" />
                <h4 className="text-xs font-bold text-white uppercase">{selectedPipeline.sourceType}</h4>
                <p className="text-[10px] font-mono text-slate-400">{selectedPipeline.sourceDb}</p>
              </div>

              {/* Arrow 1 */}
              <div className="hidden md:flex flex-col items-center justify-center text-sky-400">
                <span className="text-[9px] font-mono text-slate-500 uppercase mb-1">WAL Streaming</span>
                <ArrowRight className="w-6 h-6 animate-pulse" />
              </div>

              {/* Node 2: Replication Middleware Engine */}
              <div className="bg-gradient-to-b from-sky-950 to-slate-900 border-2 border-sky-400 p-5 rounded-xl text-center space-y-2 relative shadow-xl shadow-sky-500/20">
                <span className="text-[9px] font-mono font-bold uppercase bg-sky-500 text-slate-950 px-2 py-0.5 rounded">
                  MIDDLEWARE ENGINE
                </span>
                <Cpu className="w-10 h-10 text-sky-300 mx-auto animate-pulse" />
                <h4 className="text-xs font-black text-white uppercase">CDC Filter & Anonymizer</h4>
                <p className="text-[10px] font-mono text-sky-300">Transforms • Sanitize • Deduplicate</p>
              </div>

              {/* Arrow 2 */}
              <div className="hidden md:flex flex-col items-center justify-center text-sky-400">
                <span className="text-[9px] font-mono text-slate-500 uppercase mb-1">Queue Sink</span>
                <ArrowRight className="w-6 h-6 animate-pulse" />
              </div>

              {/* Node 3: Target Destination DB */}
              <div className="bg-slate-900 border-2 border-emerald-500/50 p-4 rounded-xl text-center space-y-2 relative shadow-lg shadow-emerald-500/10">
                <span className="text-[9px] font-mono font-bold uppercase bg-emerald-950 text-emerald-300 px-2 py-0.5 rounded border border-emerald-500/30">
                  DESTINATION (TUJUAN)
                </span>
                <Server className="w-8 h-8 text-emerald-400 mx-auto" />
                <h4 className="text-xs font-bold text-white uppercase">{selectedPipeline.targetType}</h4>
                <p className="text-[10px] font-mono text-slate-400">{selectedPipeline.targetDb}</p>
              </div>

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

      {/* SECTION 3: LIVE REPLICATION LOGS */}
      {activeTab === "logs" && (
        <div className="bg-slate-900/80 border border-slate-800 rounded-2xl p-6 space-y-4">
          <div className="flex items-center justify-between border-b border-slate-800 pb-3">
            <h3 className="text-sm font-black text-white uppercase tracking-wide flex items-center gap-2">
              <Terminal className="w-4 h-4 text-sky-400" />
              Riwayat & Live Streaming Event Replikasi
            </h3>
            <span className="text-xs font-mono text-slate-400">Total Logs: {logs.length} Event</span>
          </div>

          <div className="space-y-2 font-mono text-xs">
            {logs.map((log) => (
              <div 
                key={log.id} 
                className="p-3 bg-slate-950 border border-slate-800 rounded-xl flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 hover:border-slate-700 transition-colors"
              >
                <div className="flex items-start gap-3">
                  <span className={`px-2 py-0.5 rounded text-[10px] font-bold uppercase shrink-0 ${
                    log.status === "SUCCESS"
                      ? "bg-emerald-500/20 text-emerald-400 border border-emerald-500/30"
                      : "bg-rose-500/20 text-rose-400 border border-rose-500/30"
                  }`}>
                    {log.action}
                  </span>

                  <div>
                    <div className="flex items-center gap-2">
                      <span className="text-slate-400 text-[11px]">{log.timestamp}</span>
                      <strong className="text-white">{log.sourceRecordId}</strong>
                    </div>
                    <p className="text-slate-400 text-[11px] mt-0.5">{log.details}</p>
                  </div>
                </div>

                <div className="text-right shrink-0">
                  <span className="text-amber-300 font-bold">{log.latencyMs}ms</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* SECTION 4: DEAD LETTER QUEUE (DLQ) */}
      {activeTab === "dlq" && (
        <div className="bg-slate-900/80 border border-slate-800 rounded-2xl p-6 space-y-4">
          <div className="flex items-center justify-between border-b border-slate-800 pb-3">
            <div>
              <h3 className="text-sm font-black text-rose-400 uppercase tracking-wide flex items-center gap-2">
                <AlertTriangle className="w-5 h-5 text-rose-400" />
                Dead Letter Queue (DLQ) - Antrean Pesan Gagal
              </h3>
              <p className="text-xs text-slate-400 mt-0.5">
                Pesan atau record data yang gagal direplikasikan ke target sink disimpan di DLQ untuk diinvestigasi dan diproses ulang.
              </p>
            </div>

            {totalDlq > 0 && (
              <button
                onClick={() => handleReprocessDlq(selectedPipeline.id)}
                className="px-4 py-2 bg-emerald-500 hover:bg-emerald-400 text-slate-950 font-black text-xs uppercase tracking-wider rounded-xl transition-all shadow-md shadow-emerald-500/20 flex items-center gap-2"
              >
                <RefreshCw className="w-4 h-4 text-slate-950" />
                <span>Proses Ulang DLQ</span>
              </button>
            )}
          </div>

          {totalDlq === 0 ? (
            <div className="p-8 text-center bg-slate-950 border border-slate-800 rounded-2xl space-y-2">
              <CheckCircle2 className="w-10 h-10 text-emerald-400 mx-auto" />
              <h4 className="text-sm font-bold text-white uppercase">Tidak Ada Record Gagal pada DLQ</h4>
              <p className="text-xs text-slate-400">Seluruh proses replikasi data antara source dan destination berjalan 100% lancar tanpa error.</p>
            </div>
          ) : (
            <div className="p-4 bg-rose-950/20 border border-rose-500/30 rounded-xl space-y-3 font-mono text-xs text-rose-200">
              <p>Terdapat <strong>{totalDlq} record</strong> tertahan pada Dead Letter Queue karena masalah skema atau gangguan jaringan sementara.</p>
              <button
                onClick={() => handleReprocessDlq(selectedPipeline.id)}
                className="px-3 py-1.5 bg-rose-500 text-white font-bold text-xs uppercase rounded-lg hover:bg-rose-400 transition-colors"
              >
                Proses Ulang Sekarang
              </button>
            </div>
          )}
        </div>
      )}

      {/* SECTION 5: BACKEND SQL RE-INIT, TRIGGERS & PASSWORDS MANAGER */}
      {activeTab === "backend_sql_triggers_passwords" && (
        <BackendDatabaseManager
          currentUser={currentUser}
          employees={employees}
        />
      )}

      {/* CREATE NEW PIPELINE MODAL */}
      {isCreateModalOpen && (
        <div className="fixed inset-0 z-50 bg-slate-950/80 backdrop-blur-sm flex items-center justify-center p-4">
          <div className="bg-slate-900 border border-sky-500/40 rounded-2xl max-w-lg w-full p-6 text-white space-y-4 shadow-2xl">
            <div className="flex items-center justify-between border-b border-slate-800 pb-3">
              <h3 className="text-sm font-black uppercase text-sky-400 tracking-wide flex items-center gap-2">
                <Plus className="w-4 h-4" />
                Buat Pipeline Replikasi Baru
              </h3>
              <button onClick={() => setIsCreateModalOpen(false)} className="text-slate-400 hover:text-white font-bold text-xs">Tutup [X]</button>
            </div>

            <form onSubmit={handleCreatePipeline} className="space-y-3 text-xs">
              <div>
                <label className="block text-slate-400 uppercase font-bold text-[10px] mb-1">Nama Pipeline</label>
                <input
                  type="text"
                  required
                  value={newPipeline.name || ""}
                  onChange={(e) => setNewPipeline(prev => ({ ...prev, name: e.target.value }))}
                  className="w-full bg-slate-950 border border-slate-800 rounded-xl p-2.5 text-white focus:outline-hidden focus:border-sky-400"
                />
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-slate-400 uppercase font-bold text-[10px] mb-1">Source Type</label>
                  <select
                    value={newPipeline.sourceType}
                    onChange={(e) => setNewPipeline(prev => ({ ...prev, sourceType: e.target.value as any }))}
                    className="w-full bg-slate-950 border border-slate-800 rounded-xl p-2.5 text-white focus:outline-hidden focus:border-sky-400"
                  >
                    <option value="PostgreSQL Primary">PostgreSQL Primary</option>
                    <option value="MySQL Legacy">MySQL Legacy</option>
                    <option value="Supabase Cloud">Supabase Cloud</option>
                    <option value="MongoDB Cluster">MongoDB Cluster</option>
                    <option value="REST API Feed">REST API Feed</option>
                  </select>
                </div>

                <div>
                  <label className="block text-slate-400 uppercase font-bold text-[10px] mb-1">Target Sink Type</label>
                  <select
                    value={newPipeline.targetType}
                    onChange={(e) => setNewPipeline(prev => ({ ...prev, targetType: e.target.value as any }))}
                    className="w-full bg-slate-950 border border-slate-800 rounded-xl p-2.5 text-white focus:outline-hidden focus:border-sky-400"
                  >
                    <option value="PostgreSQL Read-Replica">PostgreSQL Read-Replica</option>
                    <option value="BigQuery Analytics">BigQuery Analytics</option>
                    <option value="Redis Cache Cluster">Redis Cache Cluster</option>
                    <option value="Elasticsearch Sink">Elasticsearch Sink</option>
                    <option value="Disaster Recovery Node">Disaster Recovery Node</option>
                  </select>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-slate-400 uppercase font-bold text-[10px] mb-1">Source Database</label>
                  <input
                    type="text"
                    required
                    value={newPipeline.sourceDb || ""}
                    onChange={(e) => setNewPipeline(prev => ({ ...prev, sourceDb: e.target.value }))}
                    className="w-full bg-slate-950 border border-slate-800 rounded-xl p-2.5 text-white focus:outline-hidden focus:border-sky-400 font-mono"
                  />
                </div>

                <div>
                  <label className="block text-slate-400 uppercase font-bold text-[10px] mb-1">Target Database</label>
                  <input
                    type="text"
                    required
                    value={newPipeline.targetDb || ""}
                    onChange={(e) => setNewPipeline(prev => ({ ...prev, targetDb: e.target.value }))}
                    className="w-full bg-slate-950 border border-slate-800 rounded-xl p-2.5 text-white focus:outline-hidden focus:border-sky-400 font-mono"
                  />
                </div>
              </div>

              <div className="flex items-center gap-2 pt-2">
                <input
                  type="checkbox"
                  id="anonymizePii"
                  checked={newPipeline.anonymizePii || false}
                  onChange={(e) => setNewPipeline(prev => ({ ...prev, anonymizePii: e.target.checked }))}
                  className="rounded text-sky-500 focus:ring-0"
                />
                <label htmlFor="anonymizePii" className="text-slate-300 text-xs">
                  Aktifkan Anonymize PII Data (Mask NIK & Gaji)
                </label>
              </div>

              <div className="pt-3 border-t border-slate-800 flex items-center justify-end gap-2">
                <button
                  type="button"
                  onClick={() => setIsCreateModalOpen(false)}
                  className="px-4 py-2 bg-slate-800 text-slate-300 font-bold uppercase text-xs rounded-xl"
                >
                  Batal
                </button>
                <button
                  type="submit"
                  className="px-4 py-2 bg-sky-500 hover:bg-sky-400 text-slate-950 font-black uppercase text-xs rounded-xl transition-all shadow-md shadow-sky-500/20"
                >
                  Simpan Pipeline
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

    </div>
  );
}
