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

import React, { useState, useMemo } from "react";
import { WorkflowRequest, Employee, WorkflowApprovalStep } from "../types";
import { ORDERED_HIERARCHY, ROLE_HIERARCHY } from "../data";
import { sendWorkflowNotificationEmail } from "../services/emailGatewayService";
import { EmailGatewayDrawerModal } from "./EmailGatewayDrawerModal";
import { 
  FileText, 
  CheckCircle, 
  XCircle, 
  Clock, 
  Plus, 
  User, 
  ArrowRight, 
  ShieldCheck,
  Building2,
  DollarSign,
  Users,
  Briefcase,
  Check,
  AlertTriangle,
  CheckCheck,
  Mail,
  Send,
  Sparkles,
  Filter,
  ShieldAlert
} from "lucide-react";

interface WorkflowConsoleProps {
  workflows: WorkflowRequest[];
  employees: Employee[];
  onCreateWorkflow: (wf: WorkflowRequest) => void;
  onApproveWorkflow: (wfId: string, approverName: string, notes: string) => void;
  onRejectWorkflow: (wfId: string, approverName: string, notes: string) => void;
}

export default function WorkflowConsole({
  workflows,
  employees,
  onCreateWorkflow,
  onApproveWorkflow,
  onRejectWorkflow
}: WorkflowConsoleProps) {
  const [filterStatus, setFilterStatus] = useState<"All" | "Pending" | "Approved" | "Rejected">("All");
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [isEmailLogsOpen, setIsEmailLogsOpen] = useState(false);

  // New workflow fields
  const [reqEmployeeId, setReqEmployeeId] = useState("");
  const [wfType, setWfType] = useState<WorkflowRequest["type"]>("Kegiatan Direktorat");
  const [wfDirectorate, setWfDirectorate] = useState("Direktorat Operasional (COO)");
  const [wfTitle, setWfTitle] = useState("");
  const [wfDesc, setWfDesc] = useState("");
  const [wfAmount, setWfAmount] = useState("");
  const [wfHrService, setWfHrService] = useState<NonNullable<WorkflowRequest["hrServiceType"]>>("Rekrutmen & Jenjang Karir");
  const [wfBudgetAmount, setWfBudgetAmount] = useState("");

  // Approval action notes
  const [approvalNotes, setApprovalNotes] = useState<Record<string, string>>({});
  
  // Local state for dynamically updating HR/Finance services in workflows
  const [localWorkflows, setLocalWorkflows] = useState<WorkflowRequest[]>(workflows);

  // Sync when prop workflows change
  React.useEffect(() => {
    setLocalWorkflows(workflows);
  }, [workflows]);

  const filteredWorkflows = useMemo(() => {
    if (filterStatus === "All") return localWorkflows;
    return localWorkflows.filter(w => w.status === filterStatus);
  }, [localWorkflows, filterStatus]);

  // Current Logged In Role Sim (Manager - Dian Ermawan is the user)
  const currentUserSim = useMemo(() => {
    const found = employees.find(e => e.email === "dian.ermawan@gmail.com");
    return found || { name: "Dian Ermawan", position: "Manager Operasional" };
  }, [employees]);

  // Handle HR Service Action
  const handleHrServiceUpdate = (wfId: string, newStatus: WorkflowRequest["hrServiceStatus"], note: string) => {
    setLocalWorkflows(prev => prev.map(w => {
      if (w.id !== wfId) return w;
      return {
        ...w,
        hrServiceStatus: newStatus,
        hrNotes: note
      };
    }));
  };

  // Handle Finance Authorization Action
  const handleFinanceAuthUpdate = (wfId: string, newStatus: WorkflowRequest["financeAuthStatus"], note: string) => {
    setLocalWorkflows(prev => prev.map(w => {
      if (w.id !== wfId) return w;
      return {
        ...w,
        financeAuthStatus: newStatus,
        financeNotes: note
      };
    }));
  };

  // Handle Create Request
  const handleCreate = (e: React.FormEvent) => {
    e.preventDefault();
    if (!reqEmployeeId || !wfTitle || !wfDesc) return;

    const requester = employees.find(e => e.id === reqEmployeeId);
    if (!requester) return;

    // Hierarchy flow: Staff -> Supervisor -> Manager -> Direktur -> CEO
    let startStage: WorkflowRequest["currentStage"] = "Supervisor";
    const reqPosLevel = ROLE_HIERARCHY[requester.position] || 1;
    
    if (reqPosLevel === 1) startStage = "Supervisor";
    else if (reqPosLevel === 2) startStage = "Manager";
    else if (reqPosLevel === 3) startStage = "Direktur";
    else if (reqPosLevel === 4) startStage = "CEO";
    else if (reqPosLevel === 5) startStage = "CEO";

    const newWf: WorkflowRequest = {
      id: `wf-${Math.random().toString(36).substr(2, 9)}`,
      requesterId: requester.id,
      requesterName: requester.name,
      requesterPosition: requester.position,
      directorate: wfDirectorate,
      type: wfType,
      title: wfTitle,
      description: wfDesc,
      amount: wfAmount || undefined,
      status: "Pending",
      currentStage: startStage,
      hrServiceType: wfHrService,
      hrServiceStatus: wfHrService !== "N/A" ? "Menunggu Layanan HR" : "Tidak Perlu",
      hrNotes: "Pengajuan otomatis diteruskan ke Human Resources (CHR).",
      budgetAmount: wfBudgetAmount ? `Rp ${wfBudgetAmount}` : undefined,
      budgetStatus: "Disetujui Dalam Budget",
      financeAuthStatus: wfBudgetAmount ? "Belum Diverifikasi" : "N/A",
      financeNotes: "Menunggu verifikasi ketersediaan anggaran oleh bagian Keuangan (CFO & Bendahara).",
      history: [
        {
          id: `h-start-${Date.now()}`,
          stage: "Staff",
          approverName: requester.name,
          status: "Approved",
          date: new Date().toISOString().replace("T", " ").substring(0, 16),
          notes: "Pengajuan kegiatan/dokumen diajukan ke sistem ERP."
        }
      ]
    };

    onCreateWorkflow(newWf);
    setShowCreateModal(false);

    // Simulate Enterprise API call to Email Gateway
    sendWorkflowNotificationEmail(newWf, employees).catch(err => {
      console.warn("[Workflow] Email gateway notification warning:", err);
    });

    // Reset
    setWfTitle("");
    setWfDesc("");
    setWfAmount("");
    setWfBudgetAmount("");
  };

  return (
    <div className="space-y-6 animate-fadeIn" id="workflow-console-container">
      {/* Header bar */}
      <div className="flex flex-col md:flex-row md:items-end md:justify-between border-b border-[#222] pb-6">
        <div>
          <p className="text-[10px] uppercase tracking-[0.3em] text-[#facc15] font-black mb-1">
            Berjenjang & Otomasi
          </p>
          <h2 className="text-3xl font-black text-white uppercase tracking-tighter leading-none">
            Workflow Approval & Authorization Engine
          </h2>
          <p className="text-xs text-slate-500 font-mono mt-1">Sistem Otomasi Kegiatan Direktorat, Layanan HR & Otoritas Pembayaran Keuangan EMS MEDIAN DEV</p>
        </div>
        <div className="mt-3 md:mt-0 flex flex-wrap items-center gap-2">
          <button
            onClick={() => setIsEmailLogsOpen(true)}
            className="bg-indigo-950/60 hover:bg-indigo-900/80 text-indigo-300 border border-indigo-500/40 text-xs font-black uppercase tracking-wider px-4 py-2.5 rounded-none flex items-center gap-1.5 transition-colors cursor-pointer"
            title="Lihat Log Simulasi API Gateway Email ke Direktur & Manager"
          >
            <Mail className="w-4 h-4 text-indigo-400" />
            <span>Email Gateway Logs</span>
          </button>

          <button 
            onClick={() => setShowCreateModal(true)}
            className="bg-[#facc15] hover:bg-yellow-500 text-black text-xs font-black uppercase tracking-wider px-5 py-2.5 rounded-none flex items-center gap-1.5 transition-colors"
          >
            <Plus className="w-4 h-4" />
            Buat Pengajuan / Kegiatan Baru
          </button>
        </div>
      </div>

      {/* Workflow Rule Hierarchy Banner */}
      <div className="bg-[#050505] border border-[#222] p-4 space-y-3">
        <div className="flex items-center justify-between border-b border-[#222] pb-2">
          <div className="flex items-center gap-2 text-xs font-black text-white uppercase tracking-wider">
            <Building2 className="w-4 h-4 text-[#facc15]" />
            Aturan Hirarki Approval Berjenjang Direktorat
          </div>
          <span className="text-[10px] font-mono text-[#facc15] bg-[#141414] px-2 py-0.5 border border-[#222]">
            Direktur Sejajar (COO, CFO, CTO, CHR) → Atasan: CEO
          </span>
        </div>
        <div className="flex items-center justify-between text-xs font-mono text-slate-300 overflow-x-auto py-1">
          <div className="flex items-center gap-2 font-bold text-slate-400 bg-[#0d0d0d] px-3 py-1 border border-[#222]">
            <span>1. Staff</span>
          </div>
          <ArrowRight className="w-3.5 h-3.5 text-slate-600 flex-shrink-0" />
          <div className="flex items-center gap-2 font-bold text-slate-300 bg-[#0d0d0d] px-3 py-1 border border-[#222]">
            <span>2. Supervisor</span>
          </div>
          <ArrowRight className="w-3.5 h-3.5 text-slate-600 flex-shrink-0" />
          <div className="flex items-center gap-2 font-bold text-amber-400 bg-[#0d0d0d] px-3 py-1 border border-[#222]">
            <span>3. Manager</span>
          </div>
          <ArrowRight className="w-3.5 h-3.5 text-slate-600 flex-shrink-0" />
          <div className="flex items-center gap-2 font-bold text-[#facc15] bg-[#0d0d0d] px-3 py-1 border border-[#facc15]/30">
            <span>4. Direktur (COO/CFO/CTO/CHR)</span>
          </div>
          <ArrowRight className="w-3.5 h-3.5 text-slate-600 flex-shrink-0" />
          <div className="flex items-center gap-2 font-black text-green-400 bg-[#0d0d0d] px-3 py-1 border border-green-500/30">
            <span>5. CEO (Direktur Utama)</span>
          </div>
        </div>
      </div>

      {/* Filter and Simulator indicator */}
      <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4 bg-[#0a0a0a] p-4 rounded-none border border-[#222]">
        <div className="flex gap-1.5">
          {["All", "Pending", "Approved", "Rejected"].map((status) => (
            <button
              key={status}
              onClick={() => setFilterStatus(status as any)}
              className={`px-4 py-2 rounded-none text-xs font-black uppercase tracking-wider border transition-all ${
                filterStatus === status 
                  ? "bg-[#facc15] text-black border-transparent" 
                  : "text-slate-400 border-[#222] bg-[#050505] hover:text-white hover:bg-[#111]"
              }`}
            >
              {status === "All" ? "Semua Pengajuan" : status}
            </button>
          ))}
        </div>

        {/* Simulator Info */}
        <div className="flex items-center gap-2 text-xs font-mono">
          <span className="w-2.5 h-2.5 bg-[#facc15] animate-pulse"></span>
          <p className="text-slate-400">
            Simulasi Akun Aktif: <strong className="text-white font-black">{currentUserSim.name}</strong> ({currentUserSim.position})
          </p>
        </div>
      </div>

      {/* Main Workflow List */}
      <div className="space-y-4" id="workflow-requests-list">
        {filteredWorkflows.length > 0 ? (
          filteredWorkflows.map((wf) => {
            const canUserAction = wf.status === 'Pending' && 
              (wf.currentStage === 'Manager' || wf.currentStage === 'Manager Operasional' || currentUserSim.position.includes(wf.currentStage));

            return (
              <div 
                key={wf.id} 
                className="bg-[#0a0a0a] border border-[#222] hover:border-slate-700 rounded-none p-6 space-y-4 transition-all"
              >
                {/* Request Header */}
                <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-3 border-b border-[#222] pb-4">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-none bg-[#050505] text-[#facc15] border border-[#222] flex items-center justify-center">
                      <FileText className="w-5 h-5" />
                    </div>
                    <div>
                      <div className="flex items-center gap-2 flex-wrap">
                        <h4 className="text-sm font-black text-white uppercase tracking-tight">{wf.title}</h4>
                        <span className="text-[10px] font-black px-2.5 py-0.5 bg-[#111] text-[#facc15] border border-[#222] rounded-none font-mono uppercase">{wf.type}</span>
                        {wf.directorate && (
                          <span className="text-[10px] font-black px-2.5 py-0.5 bg-[#050505] text-slate-300 border border-[#333] rounded-none font-mono uppercase flex items-center gap-1">
                            <Briefcase className="w-3 h-3 text-[#facc15]" />
                            {wf.directorate}
                          </span>
                        )}
                      </div>
                      <p className="text-xs text-slate-400 font-mono mt-0.5">Diajukan oleh: <strong className="text-white">{wf.requesterName}</strong> ({wf.requesterPosition})</p>
                    </div>
                  </div>

                  {/* Status pills */}
                  <div className="flex items-center gap-2">
                    {wf.status === 'Pending' && (
                      <span className="inline-flex items-center gap-1 text-[10px] font-black px-2.5 py-1 rounded-none bg-amber-500/10 text-amber-400 border border-amber-500/20 uppercase font-mono">
                        <Clock className="w-3.5 h-3.5 animate-spin" />
                        Menunggu Stage: {wf.currentStage}
                      </span>
                    )}
                    {wf.status === 'Approved' && (
                      <span className="inline-flex items-center gap-1 text-[10px] font-black px-2.5 py-1 rounded-none bg-green-500/10 text-green-400 border border-green-500/20 uppercase font-mono">
                        <CheckCircle className="w-3.5 h-3.5" />
                        Selesai Disetujui CEO
                      </span>
                    )}
                    {wf.status === 'Rejected' && (
                      <span className="inline-flex items-center gap-1 text-[10px] font-black px-2.5 py-1 rounded-none bg-red-500/10 text-red-400 border border-red-500/20 uppercase font-mono">
                        <XCircle className="w-3.5 h-3.5" />
                        Ditolak
                      </span>
                    )}
                  </div>
                </div>

                {/* Description */}
                <div>
                  <p className="text-xs text-slate-300 leading-relaxed text-justify">{wf.description}</p>
                  {wf.amount && (
                    <p className="text-xs text-slate-400 mt-2 font-mono uppercase tracking-wider">
                      Nilai / Keterangan Tambahan: <strong className="text-[#facc15]">{wf.amount}</strong>
                    </p>
                  )}
                </div>

                {/* INTER-DIRECTORATE SERVICES & FINANCIAL AUTHORIZATION GRID */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 bg-[#050505] p-4 border border-[#222]">
                  {/* HR Service Box */}
                  <div className="bg-[#0a0a0a] border border-[#222] p-3 space-y-2">
                    <div className="flex items-center justify-between border-b border-[#222] pb-1.5">
                      <div className="flex items-center gap-1.5 text-xs font-black text-white uppercase">
                        <Users className="w-3.5 h-3.5 text-[#facc15]" />
                        Layanan Human Resources (CHR)
                      </div>
                      <span className={`text-[9px] font-black px-2 py-0.5 border ${
                        wf.hrServiceStatus === 'Selesai Layanan HR' ? 'bg-green-500/10 text-green-400 border-green-500/30' :
                        wf.hrServiceStatus === 'Diproses HR' ? 'bg-amber-500/10 text-amber-400 border-amber-500/30' :
                        'bg-slate-800/40 text-slate-400 border-slate-700'
                      }`}>
                        {wf.hrServiceStatus || 'N/A'}
                      </span>
                    </div>
                    <div className="text-xs font-mono space-y-1">
                      <p className="text-slate-400">Kebutuhan HR: <strong className="text-white">{wf.hrServiceType || 'Layanan Umum'}</strong></p>
                      <p className="text-[11px] text-slate-300 italic">{wf.hrNotes || 'Belum ada catatan layanan HR.'}</p>
                    </div>
                    {/* Simulated HR Actions */}
                    <div className="pt-2 flex gap-2 border-t border-[#1a1a1a]">
                      <button 
                        onClick={() => handleHrServiceUpdate(wf.id, "Diproses HR", "Permohonan sedang ditindaklanjuti oleh Divisi Rekrutmen / Payroll HR.")}
                        className="text-[10px] font-black uppercase px-2.5 py-1 bg-[#141414] hover:bg-[#222] text-amber-400 border border-[#333] transition-colors"
                      >
                        Proses HR
                      </button>
                      <button 
                        onClick={() => handleHrServiceUpdate(wf.id, "Selesai Layanan HR", "Layanan HR telah selesai diserahterimakan ke direktorat pengaju.")}
                        className="text-[10px] font-black uppercase px-2.5 py-1 bg-green-950/40 hover:bg-green-900/50 text-green-400 border border-green-800/50 transition-colors"
                      >
                        Tandai Selesai HR
                      </button>
                    </div>
                  </div>

                  {/* Finance Authorization Box */}
                  <div className="bg-[#0a0a0a] border border-[#222] p-3 space-y-2">
                    <div className="flex items-center justify-between border-b border-[#222] pb-1.5">
                      <div className="flex items-center gap-1.5 text-xs font-black text-white uppercase">
                        <DollarSign className="w-3.5 h-3.5 text-[#facc15]" />
                        Otoritas Pembayaran Keuangan (CFO)
                      </div>
                      <span className={`text-[9px] font-black px-2 py-0.5 border ${
                        wf.financeAuthStatus === 'Disetujui Otoritas Keuangan' ? 'bg-green-500/10 text-green-400 border-green-500/30' :
                        wf.financeAuthStatus === 'Verifikasi Budget OK' ? 'bg-blue-500/10 text-blue-400 border-blue-500/30' :
                        'bg-amber-500/10 text-amber-400 border-amber-500/30'
                      }`}>
                        {wf.financeAuthStatus || 'Belum Diverifikasi'}
                      </span>
                    </div>
                    <div className="text-xs font-mono space-y-1">
                      <p className="text-slate-400">Anggaran/Budget: <strong className="text-[#facc15]">{wf.budgetAmount || 'Tidak Memerlukan Anggaran'}</strong></p>
                      <p className="text-[11px] text-slate-300 italic">{wf.financeNotes || 'Menunggu otoritas ketersediaan budget oleh Bendahara & CFO.'}</p>
                    </div>
                    {/* Simulated Finance Actions */}
                    <div className="pt-2 flex gap-2 border-t border-[#1a1a1a]">
                      <button 
                        onClick={() => handleFinanceAuthUpdate(wf.id, "Verifikasi Budget OK", "Hasil pengecekan Bendahara: Anggaran tersedia & sesuai plafon direktorat.")}
                        className="text-[10px] font-black uppercase px-2.5 py-1 bg-[#141414] hover:bg-[#222] text-blue-400 border border-[#333] transition-colors"
                      >
                        Verifikasi Budget OK
                      </button>
                      <button 
                        onClick={() => handleFinanceAuthUpdate(wf.id, "Disetujui Otoritas Keuangan", "Otorisasi Pembayaran diterbitkan secara resmi oleh CFO Hendra Wijaya.")}
                        className="text-[10px] font-black uppercase px-2.5 py-1 bg-green-950/40 hover:bg-green-900/50 text-green-400 border border-green-800/50 transition-colors"
                      >
                        Otorisasi Pembayaran CFO
                      </button>
                    </div>
                  </div>
                </div>

                {/* PERSINGGAHAN JALUR HIERARKI VISUALIZATION (Staff -> Supervisor -> Manager -> Direktur -> CEO) */}
                {(() => {
                  const currentStageIdx = ORDERED_HIERARCHY.findIndex(s => 
                    s.toLowerCase().includes((wf.currentStage || "").toLowerCase().substring(0, 4)) || 
                    (wf.currentStage || "").toLowerCase().includes(s.toLowerCase().substring(0, 4))
                  );
                  const validCurrentIdx = currentStageIdx >= 0 ? currentStageIdx : 0;
                  const progressPercent = wf.status === 'Approved' ? 100 : (validCurrentIdx / (ORDERED_HIERARCHY.length - 1)) * 100;

                  return (
                    <div className="bg-[#050505] p-5 border border-[#222] space-y-4 font-mono">
                      <div className="flex flex-wrap items-center justify-between gap-2 border-b border-[#1f1f1f] pb-2">
                        <div className="flex items-center gap-2">
                          <ShieldCheck className="w-4 h-4 text-[#facc15]" />
                          <span className="text-xs font-black text-white uppercase tracking-wider">
                            Progress Approval Berjenjang (Staff → Supervisor → Manager → Direktur → CEO)
                          </span>
                        </div>
                        <div className="flex items-center gap-2 text-[11px]">
                          <span className="text-slate-400">Tahap Aktif:</span>
                          <span className={`font-black uppercase px-2 py-0.5 border ${
                            wf.status === 'Approved' ? 'bg-green-500/10 text-green-400 border-green-500/30' :
                            wf.status === 'Rejected' ? 'bg-red-500/10 text-red-400 border-red-500/30' :
                            'bg-amber-500/10 text-amber-400 border-amber-500/30'
                          }`}>
                            {wf.status === 'Pending' ? `Mengantri: ${wf.currentStage}` : wf.status}
                          </span>
                          <span className="text-slate-400 font-bold">({Math.round(progressPercent)}% Selesai)</span>
                        </div>
                      </div>

                      {/* Step Indicator Progress Bar */}
                      <div className="relative pt-2 pb-1 px-3">
                        {/* Connecting Track */}
                        <div className="absolute top-[26px] left-8 right-8 h-1.5 bg-[#1a1a1a] border border-[#2a2a2a] rounded-full z-0">
                          <div 
                            className={`h-full transition-all duration-500 rounded-full ${
                              wf.status === 'Rejected' ? 'bg-red-500' :
                              wf.status === 'Approved' ? 'bg-green-500' :
                              'bg-gradient-to-r from-emerald-500 via-amber-400 to-[#facc15]'
                            }`}
                            style={{ width: `${progressPercent}%` }}
                          />
                        </div>

                        {/* Steps */}
                        <div className="relative z-10 flex items-center justify-between">
                          {ORDERED_HIERARCHY.map((stage, idx) => {
                            const histStep = wf.history?.find(h => 
                              h.stage.toLowerCase().includes(stage.toLowerCase().substring(0, 4)) ||
                              stage.toLowerCase().includes(h.stage.toLowerCase().substring(0, 4))
                            );
                            const isCompleted = wf.status === 'Approved' || (histStep && histStep.status === 'Approved') || (wf.status === 'Pending' && idx < validCurrentIdx);
                            const isRejected = (wf.status === 'Rejected' && idx === validCurrentIdx) || (histStep && histStep.status === 'Rejected');
                            const isCurrent = wf.status === 'Pending' && idx === validCurrentIdx;

                            return (
                              <div key={stage} className="flex flex-col items-center">
                                {/* Step Node */}
                                <div className={`w-8 h-8 rounded-full flex items-center justify-center font-black text-xs border transition-all ${
                                  isCompleted ? "bg-green-500 text-black border-green-400 shadow-md shadow-green-500/20" :
                                  isRejected ? "bg-red-600 text-white border-red-400" :
                                  isCurrent ? "bg-[#facc15] text-black border-yellow-300 ring-4 ring-amber-500/20 animate-pulse scale-110" :
                                  "bg-[#0d0d0d] text-slate-500 border-[#2a2a2a]"
                                }`}>
                                  {isCompleted ? (
                                    <Check className="w-4 h-4 stroke-[3]" />
                                  ) : isRejected ? (
                                    <XCircle className="w-4 h-4" />
                                  ) : isCurrent ? (
                                    <Clock className="w-4 h-4 text-black animate-spin" />
                                  ) : (
                                    idx + 1
                                  )}
                                </div>

                                {/* Label & Approver Subtitle */}
                                <div className="mt-2 text-center space-y-0.5">
                                  <span className={`block text-[10px] font-black uppercase tracking-wider ${
                                    isCurrent ? "text-[#facc15]" :
                                    isCompleted ? "text-green-400" :
                                    isRejected ? "text-red-400" :
                                    "text-slate-500"
                                  }`}>
                                    {stage}
                                  </span>
                                  <span className="block text-[9px] text-slate-400 font-mono max-w-[85px] truncate">
                                    {histStep?.approverName ? histStep.approverName : (isCurrent ? `Antrian ${stage}` : `Tingkat ${idx + 1}`)}
                                  </span>
                                </div>
                              </div>
                            );
                          })}
                        </div>
                      </div>
                    </div>
                  );
                })()}

                {/* Workflow History Logs / Comments */}
                {wf.history && wf.history.length > 0 && (
                  <div className="space-y-2">
                    <span className="text-[10px] font-black text-slate-500 uppercase tracking-widest block">Log Aktivitas Approval:</span>
                    <div className="space-y-2">
                      {wf.history.map((hist, hIdx) => (
                        <div key={hIdx} className="flex gap-2.5 text-xs">
                          <div className="w-1.5 h-1.5 bg-[#facc15] mt-1.5"></div>
                          <div className="text-slate-400 flex-1">
                            <strong className="text-white uppercase font-black">{hist.approverName || hist.stage}</strong> 
                            {hist.status === 'Approved' ? (
                              <span className="text-green-400 font-bold mx-1.5">menyetujui</span>
                            ) : hist.status === 'Rejected' ? (
                              <span className="text-red-400 font-bold mx-1.5">menolak</span>
                            ) : (
                              <span className="text-amber-400 font-bold mx-1.5">mengantri</span>
                            )}
                            {hist.date && <span className="text-slate-500 font-mono">({hist.date})</span>}
                            {hist.notes && (
                              <span className="block mt-1 text-[11px] text-slate-300 italic bg-[#050505] p-2.5 border border-[#222] rounded-none">
                                "{hist.notes}"
                              </span>
                            )}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Interactive Actions for authorized simulated user */}
                {canUserAction && (
                  <div className="pt-4 border-t border-[#222] space-y-3 bg-[#0c0c0c] p-4 rounded-none border border-[#222]">
                    <p className="text-xs font-black text-[#facc15] uppercase tracking-wider flex items-center gap-1.5">
                      <ShieldCheck className="w-4 h-4" />
                      Tindakan Approval Diperlukan ({currentUserSim.name} — Stage: {wf.currentStage})
                    </p>
                    <div className="flex flex-col sm:flex-row gap-3">
                      <input 
                        type="text"
                        placeholder="Berikan catatan/alasan persetujuan..."
                        value={approvalNotes[wf.id] || ""}
                        onChange={(e) => setApprovalNotes(prev => ({ ...prev, [wf.id]: e.target.value }))}
                        className="flex-1 border border-[#222] bg-[#050505] text-white rounded-none px-3 py-2 text-xs focus:outline-hidden focus:border-[#facc15] font-mono"
                      />
                      <div className="flex gap-2">
                        <button 
                          onClick={() => {
                            onApproveWorkflow(wf.id, currentUserSim.name, approvalNotes[wf.id] || "Disetujui.");
                            setApprovalNotes(prev => ({ ...prev, [wf.id]: "" }));
                          }}
                          className="bg-[#facc15] hover:bg-yellow-500 text-black font-black uppercase tracking-wider text-xs px-5 py-2.5 rounded-none flex items-center gap-1 transition-colors"
                        >
                          Setujui & Teruskan
                        </button>
                        <button 
                          onClick={() => {
                            onRejectWorkflow(wf.id, currentUserSim.name, approvalNotes[wf.id] || "Ditolak.");
                            setApprovalNotes(prev => ({ ...prev, [wf.id]: "" }));
                          }}
                          className="bg-red-950 border border-red-800 text-red-400 hover:bg-red-900 hover:text-white font-black uppercase tracking-wider text-xs px-5 py-2.5 rounded-none flex items-center gap-1 transition-colors"
                        >
                          Tolak
                        </button>
                      </div>
                    </div>
                  </div>
                )}

              </div>
            );
          })
        ) : (
          <div className="text-center py-16 text-slate-500 bg-[#0a0a0a] border border-[#222] font-mono uppercase text-xs">
            Tidak ada pengajuan persetujuan yang cocok dengan filter status saat ini.
          </div>
        )}
      </div>

      {/* Creation Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black/80 flex items-center justify-center p-4 z-50 overflow-y-auto">
          <form onSubmit={handleCreate} className="bg-[#0a0a0a] border-4 border-[#222] rounded-none max-w-lg w-full p-6 shadow-none space-y-4 text-white my-8">
            <h3 className="text-sm font-black text-[#facc15] uppercase tracking-wider border-b border-[#222] pb-2">Buat Pengajuan Kegiatan / Layanan Direktorat Baru</h3>
            
            <div className="space-y-3 text-xs">
              <div>
                <label className="block font-black uppercase text-slate-400 mb-1">Pengaju Pegawai <span className="text-red-500">*</span></label>
                <select 
                  value={reqEmployeeId} 
                  onChange={e => setReqEmployeeId(e.target.value)}
                  className="w-full border border-[#222] bg-[#050505] text-white focus:border-[#facc15] rounded-none px-3 py-2 text-xs font-mono"
                  required
                >
                  <option value="">-- Pilih Pegawai --</option>
                  {employees.map(e => (
                    <option key={e.id} value={e.id}>{e.name} ({e.position} - {e.division})</option>
                  ))}
                </select>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block font-black uppercase text-slate-400 mb-1">Direktorat Pengaju</label>
                  <select 
                    value={wfDirectorate} 
                    onChange={e => setWfDirectorate(e.target.value)}
                    className="w-full border border-[#222] bg-[#050505] text-white focus:border-[#facc15] rounded-none px-3 py-2 text-xs font-mono"
                  >
                    <option value="Direktorat Operasional (COO)">Direktorat Operasional (COO)</option>
                    <option value="Direktorat Keuangan (CFO)">Direktorat Keuangan (CFO)</option>
                    <option value="Direktorat IT (CTO)">Direktorat IT (CTO)</option>
                    <option value="Direktorat Human Resources (CHR)">Direktorat HR (CHR)</option>
                  </select>
                </div>

                <div>
                  <label className="block font-black uppercase text-slate-400 mb-1">Jenis Pengajuan</label>
                  <select 
                     value={wfType} 
                     onChange={e => setWfType(e.target.value as any)}
                     className="w-full border border-[#222] bg-[#050505] text-white focus:border-[#facc15] rounded-none px-3 py-2 text-xs font-mono"
                  >
                    <option value="Kegiatan Direktorat">Kegiatan Direktorat</option>
                    <option value="Pengadaan & Server">Pengadaan & Server</option>
                    <option value="SK Baru">SK Baru</option>
                    <option value="Promosi">Promosi</option>
                    <option value="Mutasi">Mutasi</option>
                    <option value="Cuti">Cuti</option>
                    <option value="Lembur">Lembur</option>
                    <option value="Dinas Luar">Dinas Luar</option>
                  </select>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block font-black uppercase text-slate-400 mb-1">Layanan HR Yang Dibutuhkan</label>
                  <select 
                     value={wfHrService} 
                     onChange={e => setWfHrService(e.target.value as any)}
                     className="w-full border border-[#222] bg-[#050505] text-white focus:border-[#facc15] rounded-none px-3 py-2 text-xs font-mono"
                  >
                    <option value="Rekrutmen & Jenjang Karir">Rekrutmen & Jenjang Karir</option>
                    <option value="Payroll & Kesejahteraan">Payroll & Kesejahteraan</option>
                    <option value="Pelatihan & SK">Pelatihan & SK</option>
                    <option value="Layanan Umum HR">Layanan Umum HR</option>
                    <option value="N/A">Tidak Perlu Layanan HR</option>
                  </select>
                </div>

                <div>
                  <label className="block font-black uppercase text-slate-400 mb-1">Estimasi Budget (Rp)</label>
                  <input 
                    type="text" 
                    value={wfBudgetAmount} 
                    onChange={e => setWfBudgetAmount(e.target.value)} 
                    placeholder="e.g. 15.000.000" 
                    className="w-full border border-[#222] bg-[#050505] text-white focus:border-[#facc15] rounded-none px-3 py-2 text-xs font-mono" 
                  />
                </div>
              </div>

              <div>
                <label className="block font-black uppercase text-slate-400 mb-1">Judul Dokumen / Kegiatan <span className="text-red-500">*</span></label>
                <input 
                  type="text" 
                  value={wfTitle} 
                  onChange={e => setWfTitle(e.target.value)} 
                  placeholder="e.g. Pengadaan Infrastruktur Server Web App" 
                  className="w-full border border-[#222] bg-[#050505] text-white focus:border-[#facc15] rounded-none px-3 py-2 text-xs font-mono" 
                  required
                />
              </div>

              <div>
                <label className="block font-black uppercase text-slate-400 mb-1">Isi Detail Pengajuan Kegiatan <span className="text-red-500">*</span></label>
                <textarea 
                  rows={3}
                  value={wfDesc} 
                  onChange={e => setWfDesc(e.target.value)} 
                  placeholder="Tuliskan permohonan lengkap beserta tujuan kegiatan..." 
                  className="w-full border border-[#222] bg-[#050505] text-white focus:border-[#facc15] rounded-none px-3 py-2 text-xs font-mono" 
                  required
                />
              </div>
            </div>

            <div className="flex justify-end gap-2.5 pt-4 border-t border-[#222]">
              <button 
                type="button"
                onClick={() => setShowCreateModal(false)}
                className="px-4 py-2 text-xs font-black uppercase tracking-wider border border-[#222] bg-[#111] text-slate-300 hover:bg-[#222] rounded-none"
              >
                Batal
              </button>
              <button 
                type="submit"
                className="px-4 py-2 text-xs font-black uppercase tracking-wider bg-[#facc15] hover:bg-yellow-500 text-black rounded-none"
              >
                Ajukan Kegiatan
              </button>
            </div>
          </form>
        </div>
      )}

      {/* Email Gateway Drawer Modal */}
      {isEmailLogsOpen && (
        <EmailGatewayDrawerModal
          isOpen={isEmailLogsOpen}
          onClose={() => setIsEmailLogsOpen(false)}
        />
      )}
    </div>
  );
}
