import React, { useState, useEffect, useMemo } from "react";
import { 
  OfficialTravelRequest, 
  TravelType, 
  DestinationType, 
  TravelStatus,
  TRAVEL_GRADE_RATES_MATRIX
} from "../../types/travel";
import { Employee } from "../../types";
import { INITIAL_OFFICIAL_TRAVELS } from "../../data/travelData";
import { OfficialTravelPrintDoc } from "./OfficialTravelPrintDoc";
import { TravelRequestFormModal } from "./TravelRequestFormModal";
import { TravelRatesTableModal } from "./TravelRatesTableModal";
import { TravelSettlementModal } from "./TravelSettlementModal";
import { 
  Plane, 
  Plus, 
  Search, 
  Filter, 
  FileText, 
  Printer, 
  CheckCircle2, 
  XCircle, 
  Clock, 
  MapPin, 
  Calendar, 
  User, 
  DollarSign, 
  Building2, 
  ShieldCheck, 
  ChevronRight, 
  Receipt, 
  Download, 
  HelpCircle, 
  Eye, 
  Edit2, 
  Sparkles,
  Layers,
  ArrowUpRight,
  TrendingUp,
  RefreshCw,
  Send,
  Calculator
} from "lucide-react";

interface OfficialTravelModuleProps {
  employees: Employee[];
  currentUser: Employee;
  onNavigateTab?: (tab: string) => void;
}

export const OfficialTravelModule: React.FC<OfficialTravelModuleProps> = ({
  employees,
  currentUser,
  onNavigateTab
}) => {
  // Master Travel State with LocalStorage Persistence
  const [travelList, setTravelList] = useState<OfficialTravelRequest[]>(() => {
    const cached = localStorage.getItem("official_travel_requests");
    if (cached) {
      try {
        return JSON.parse(cached);
      } catch (e) {
        return INITIAL_OFFICIAL_TRAVELS;
      }
    }
    return INITIAL_OFFICIAL_TRAVELS;
  });

  useEffect(() => {
    localStorage.setItem("official_travel_requests", JSON.stringify(travelList));
  }, [travelList]);

  // Active Sub-Tab
  const [subTab, setSubTab] = useState<"LIST" | "FINANCE_VOUCHER" | "RATES_MATRIX">("LIST");

  // Filters & Search
  const [searchQuery, setSearchQuery] = useState("");
  const [filterTripType, setFilterTripType] = useState<string>("ALL");
  const [filterDestination, setFilterDestination] = useState<string>("ALL");
  const [filterStatus, setFilterStatus] = useState<string>("ALL");

  // Modals
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [isRatesModalOpen, setIsRatesModalOpen] = useState(false);
  const [selectedTravelForPrint, setSelectedTravelForPrint] = useState<{ travel: OfficialTravelRequest; type: 'SPPD' | 'VOUCHER_LPJ' | 'BOTH' } | null>(null);
  const [selectedTravelForSettlement, setSelectedTravelForSettlement] = useState<OfficialTravelRequest | null>(null);

  const formatRupiah = (amount: number) => {
    return new Intl.NumberFormat("id-ID", {
      style: "currency",
      currency: "IDR",
      maximumFractionDigits: 0
    }).format(amount);
  };

  const formatDateIndo = (dateStr: string) => {
    if (!dateStr) return "-";
    try {
      const d = new Date(dateStr);
      return d.toLocaleDateString("id-ID", {
        day: "numeric",
        month: "short",
        year: "numeric"
      });
    } catch {
      return dateStr;
    }
  };

  // Filtered List
  const filteredTravels = useMemo(() => {
    return travelList.filter((item) => {
      // Search
      const q = searchQuery.toLowerCase();
      const matchSearch = 
        !q ||
        item.employeeName.toLowerCase().includes(q) ||
        item.employeeNip.toLowerCase().includes(q) ||
        item.sppdNumber.toLowerCase().includes(q) ||
        item.destinationCity.toLowerCase().includes(q) ||
        item.purpose.toLowerCase().includes(q);

      // Filters
      const matchTripType = filterTripType === "ALL" || item.tripType === filterTripType;
      const matchDestination = filterDestination === "ALL" || item.destinationType === filterDestination;
      const matchStatus = filterStatus === "ALL" || item.status === filterStatus;

      return matchSearch && matchTripType && matchDestination && matchStatus;
    });
  }, [travelList, searchQuery, filterTripType, filterDestination, filterStatus]);

  // Quick Metrics
  const totalTravels = travelList.length;
  const pendingApprovals = travelList.filter(t => t.status === "Menunggu Approval Atasan").length;
  const activeTrips = travelList.filter(t => t.status === "Disetujui (Approved)" || t.status === "Sedang Berjalan (Active)").length;
  const waitingSettlement = travelList.filter(t => t.status === "Menunggu LPJ Keuangan" || (t.voucher && t.voucher.settlementStatus === "Menunggu Settlement LPJ")).length;
  const totalBudgetSpent = travelList.reduce((sum, t) => sum + (t.voucher.totalActualRealization || t.totalEstimatedCost), 0);

  // Handlers
  const handleCreateTravel = (newTravel: OfficialTravelRequest) => {
    setTravelList(prev => [newTravel, ...prev]);
  };

  const handleUpdateTravel = (updated: OfficialTravelRequest) => {
    setTravelList(prev => prev.map(item => item.id === updated.id ? updated : item));
  };

  const handleApprove = (id: string) => {
    setTravelList(prev => prev.map(item => {
      if (item.id === id) {
        return {
          ...item,
          status: "Disetujui (Approved)",
          approvedBy: currentUser.name,
          approvedByNip: currentUser.nip,
          approvedAt: new Date().toISOString().replace("T", " ").substring(0, 16)
        };
      }
      return item;
    }));
  };

  const handleReject = (id: string) => {
    setTravelList(prev => prev.map(item => {
      if (item.id === id) {
        return {
          ...item,
          status: "Ditolak (Rejected)"
        };
      }
      return item;
    }));
  };

  return (
    <div className="space-y-6 text-slate-100">
      
      {/* 1. Header Banner & Actions */}
      <div className="bg-gradient-to-r from-slate-900 via-sky-950/80 to-slate-900 border border-sky-500/30 rounded-2xl p-6 shadow-xl relative overflow-hidden">
        <div className="absolute top-0 right-0 w-96 h-96 bg-sky-500/5 rounded-full blur-3xl pointer-events-none" />
        
        <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-6 relative z-10">
          <div className="space-y-2">
            <div className="flex items-center gap-2.5">
              <div className="p-2.5 bg-gradient-to-br from-sky-500 to-blue-600 rounded-xl text-slate-950 shadow-md shadow-sky-500/20">
                <Plane className="w-6 h-6 text-slate-950 font-black" />
              </div>
              <div>
                <h1 className="text-xl sm:text-2xl font-black text-white tracking-tight flex items-center gap-2">
                  Aplikasi Perjalanan Dinas Pegawai
                  <span className="text-xs bg-sky-500/20 text-sky-300 border border-sky-400/40 px-2.5 py-0.5 rounded-full font-mono font-bold">
                    SPPD & Financial Voucher
                  </span>
                </h1>
                <p className="text-xs sm:text-sm text-slate-300">
                  Pengelolaan Surat Perintah Perjalanan Dinas, Standar Fasilitas Sesuai Grade, & Lampiran Voucher Keuangan (LPJ)
                </p>
              </div>
            </div>

            {/* Current Logged In Account NIP Badge */}
            <div className="flex items-center gap-2 text-xs pt-1">
              <span className="text-slate-400">Akun Saat Ini:</span>
              <span className="font-bold text-white bg-slate-800/80 border border-slate-700 px-2 py-0.5 rounded">
                {currentUser.name} ({currentUser.position})
              </span>
              <span className="font-mono font-bold text-sky-300 bg-sky-950 border border-sky-500/40 px-2 py-0.5 rounded">
                NIP: {currentUser.nip}
              </span>
            </div>
          </div>

          <div className="flex flex-wrap items-center gap-3">
            <button
              onClick={() => setIsRatesModalOpen(true)}
              className="px-4 py-2.5 bg-slate-800 hover:bg-slate-700 text-slate-200 font-bold text-xs uppercase tracking-wider rounded-xl border border-slate-700 hover:border-slate-600 shadow-sm flex items-center gap-2 transition-all cursor-pointer"
            >
              <Building2 className="w-4 h-4 text-emerald-400" />
              <span>Tabel Fasilitas & Tarif Grade</span>
            </button>

            <button
              onClick={() => setIsCreateModalOpen(true)}
              className="px-5 py-2.5 bg-gradient-to-r from-sky-500 via-sky-600 to-blue-600 hover:from-sky-400 hover:to-blue-500 text-slate-950 font-black text-xs uppercase tracking-wider rounded-xl shadow-lg shadow-sky-500/30 flex items-center gap-2 transition-all cursor-pointer"
            >
              <Plus className="w-4 h-4" />
              <span>Ajukan SPPD Baru</span>
            </button>
          </div>
        </div>

        {/* 4 Summary Stats Cards */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3.5 mt-6 pt-6 border-t border-slate-800/80">
          
          <div className="bg-slate-900/80 border border-slate-800 p-3.5 rounded-xl">
            <span className="text-[11px] font-bold text-slate-400 uppercase block mb-1">Total SPPD Terbit</span>
            <div className="flex items-baseline justify-between">
              <span className="text-xl font-black text-white font-mono">{totalTravels}</span>
              <span className="text-[10px] text-sky-400 bg-sky-500/10 px-1.5 py-0.5 rounded font-semibold">Tahun 2026</span>
            </div>
          </div>

          <div className="bg-slate-900/80 border border-slate-800 p-3.5 rounded-xl">
            <span className="text-[11px] font-bold text-slate-400 uppercase block mb-1">Menunggu Approval</span>
            <div className="flex items-baseline justify-between">
              <span className="text-xl font-black text-amber-400 font-mono">{pendingApprovals}</span>
              <span className="text-[10px] text-amber-400 bg-amber-500/10 px-1.5 py-0.5 rounded font-semibold">Otorisasi</span>
            </div>
          </div>

          <div className="bg-slate-900/80 border border-slate-800 p-3.5 rounded-xl">
            <span className="text-[11px] font-bold text-slate-400 uppercase block mb-1">Perjalanan Aktif</span>
            <div className="flex items-baseline justify-between">
              <span className="text-xl font-black text-emerald-400 font-mono">{activeTrips}</span>
              <span className="text-[10px] text-emerald-400 bg-emerald-500/10 px-1.5 py-0.5 rounded font-semibold">On-Duty</span>
            </div>
          </div>

          <div className="bg-slate-900/80 border border-slate-800 p-3.5 rounded-xl">
            <span className="text-[11px] font-bold text-slate-400 uppercase block mb-1">Total Realisasi Anggaran</span>
            <div className="flex items-baseline justify-between">
              <span className="text-base sm:text-lg font-black text-sky-300 font-mono truncate">{formatRupiah(totalBudgetSpent)}</span>
              <span className="text-[10px] text-purple-400 bg-purple-500/10 px-1.5 py-0.5 rounded font-semibold">Voucher</span>
            </div>
          </div>

        </div>
      </div>

      {/* 2. Sub-Tab Switcher & Filter Controls */}
      <div className="bg-slate-900/90 border border-slate-800 rounded-2xl p-4 space-y-4 shadow-sm">
        
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b border-slate-800 pb-3">
          
          {/* Sub Navigation */}
          <div className="flex items-center gap-1.5 bg-slate-950 p-1 rounded-xl border border-slate-800 text-xs font-bold">
            <button
              onClick={() => setSubTab("LIST")}
              className={`px-4 py-2 rounded-lg transition-all flex items-center gap-2 ${
                subTab === "LIST" 
                  ? "bg-sky-500 text-slate-950 shadow-md shadow-sky-500/20 font-black" 
                  : "text-slate-400 hover:text-white"
              }`}
            >
              <FileText className="w-3.5 h-3.5" />
              <span>Daftar SPPD & Monitoring</span>
              <span className="bg-slate-900 text-white px-1.5 py-0.2 rounded-full text-[10px] font-mono">
                {travelList.length}
              </span>
            </button>

            <button
              onClick={() => setSubTab("FINANCE_VOUCHER")}
              className={`px-4 py-2 rounded-lg transition-all flex items-center gap-2 ${
                subTab === "FINANCE_VOUCHER" 
                  ? "bg-sky-500 text-slate-950 shadow-md shadow-sky-500/20 font-black" 
                  : "text-slate-400 hover:text-white"
              }`}
            >
              <Receipt className="w-3.5 h-3.5" />
              <span>Voucher Keuangan & LPJ</span>
              {waitingSettlement > 0 && (
                <span className="bg-amber-500 text-slate-950 px-1.5 py-0.2 rounded-full text-[10px] font-mono font-bold">
                  {waitingSettlement}
                </span>
              )}
            </button>

            <button
              onClick={() => setSubTab("RATES_MATRIX")}
              className={`px-4 py-2 rounded-lg transition-all flex items-center gap-2 ${
                subTab === "RATES_MATRIX" 
                  ? "bg-sky-500 text-slate-950 shadow-md shadow-sky-500/20 font-black" 
                  : "text-slate-400 hover:text-white"
              }`}
            >
              <Building2 className="w-3.5 h-3.5" />
              <span>Matriks Tarif Grade</span>
            </button>
          </div>

          <div className="text-xs text-slate-400 font-mono">
            Menampilkan: <strong className="text-sky-300">{filteredTravels.length}</strong> dari {travelList.length} SPPD
          </div>
        </div>

        {/* Search & Select Filters */}
        <div className="grid grid-cols-1 sm:grid-cols-12 gap-3 text-xs">
          
          {/* Search Box */}
          <div className="sm:col-span-4 relative">
            <Search className="w-4 h-4 absolute left-3 top-2.5 text-slate-400" />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Cari NIP Pegawai, Nama, No. SPPD, Kota Tujuan..."
              className="w-full bg-slate-950 border border-slate-700 rounded-xl pl-9 pr-4 py-2 text-white placeholder-slate-500 focus:outline-none focus:border-sky-400 text-xs"
            />
            {searchQuery && (
              <button 
                onClick={() => setSearchQuery("")}
                className="absolute right-3 top-2.5 text-slate-400 hover:text-white"
              >
                <XCircle className="w-3.5 h-3.5" />
              </button>
            )}
          </div>

          {/* Filter Jenis Dinas */}
          <div className="sm:col-span-3">
            <select
              value={filterTripType}
              onChange={(e) => setFilterTripType(e.target.value)}
              className="w-full bg-slate-950 border border-slate-700 rounded-xl px-3 py-2 text-slate-200 focus:outline-none focus:border-sky-400 text-xs"
            >
              <option value="ALL">A. Semua Jenis Dinas</option>
              <option value="Hubungan kerja eksternal">1. Hubungan kerja eksternal</option>
              <option value="Hubungan kerja di internal perusahaan">2. Hubungan kerja di internal perusahaan</option>
              <option value="Tugas belajar">3. Tugas belajar</option>
            </select>
          </div>

          {/* Filter Tempat Tujuan */}
          <div className="sm:col-span-3">
            <select
              value={filterDestination}
              onChange={(e) => setFilterDestination(e.target.value)}
              className="w-full bg-slate-950 border border-slate-700 rounded-xl px-3 py-2 text-slate-200 focus:outline-none focus:border-sky-400 text-xs"
            >
              <option value="ALL">B. Semua Tempat Tujuan</option>
              <option value="Dalam kota">1. Dalam kota</option>
              <option value="Luar kota">2. Luar kota</option>
              <option value="Luar negeri">3. Luar negeri</option>
            </select>
          </div>

          {/* Filter Status */}
          <div className="sm:col-span-2">
            <select
              value={filterStatus}
              onChange={(e) => setFilterStatus(e.target.value)}
              className="w-full bg-slate-950 border border-slate-700 rounded-xl px-3 py-2 text-slate-200 focus:outline-none focus:border-sky-400 text-xs"
            >
              <option value="ALL">Semua Status</option>
              <option value="Menunggu Approval Atasan">Menunggu Approval</option>
              <option value="Disetujui (Approved)">Disetujui</option>
              <option value="Menunggu LPJ Keuangan">Menunggu LPJ</option>
              <option value="Selesai (Completed)">Selesai</option>
            </select>
          </div>

        </div>

      </div>

      {/* 3. Main Content Views based on SubTab */}
      {subTab === "LIST" && (
        <div className="space-y-4">
          
          {filteredTravels.length === 0 ? (
            <div className="bg-slate-900/60 border border-slate-800 rounded-2xl p-12 text-center space-y-3">
              <Plane className="w-12 h-12 text-slate-600 mx-auto" />
              <h3 className="text-base font-bold text-white">Tidak ada data Perjalanan Dinas yang sesuai filter</h3>
              <p className="text-xs text-slate-400 max-w-md mx-auto">
                Silakan ubah filter pencarian atau buat pengajuan Surat Perintah Perjalanan Dinas (SPPD) baru.
              </p>
              <button
                onClick={() => setIsCreateModalOpen(true)}
                className="mt-2 px-4 py-2 bg-sky-500 hover:bg-sky-400 text-slate-950 font-bold text-xs rounded-xl"
              >
                + Ajukan SPPD Sekarang
              </button>
            </div>
          ) : (
            <div className="grid grid-cols-1 gap-4">
              {filteredTravels.map((travel) => {
                const isApproved = travel.status === "Disetujui (Approved)";
                const isCompleted = travel.status === "Selesai (Completed)";
                const isPending = travel.status === "Menunggu Approval Atasan";
                const isRejected = travel.status === "Ditolak (Rejected)";

                return (
                  <div
                    key={travel.id}
                    className="bg-slate-900/90 border border-slate-800 hover:border-slate-700 rounded-2xl p-5 shadow-sm transition-all space-y-4"
                  >
                    {/* Header Row */}
                    <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b border-slate-800/80 pb-3">
                      
                      <div className="flex flex-wrap items-center gap-2.5">
                        <span className="px-2.5 py-1 bg-sky-950 border border-sky-500/40 text-sky-300 font-mono font-bold text-xs rounded-lg">
                          {travel.sppdNumber}
                        </span>
                        
                        {/* Wajib NIP Pegawai Badge */}
                        <span className="px-2.5 py-1 bg-slate-800 border border-slate-700 text-slate-200 font-mono text-xs rounded-lg flex items-center gap-1.5">
                          <User className="w-3.5 h-3.5 text-sky-400" />
                          <span>NIP: <strong className="text-white">{travel.employeeNip}</strong></span>
                        </span>

                        <span className="font-bold text-white text-sm">
                          {travel.employeeName}
                        </span>
                        <span className="text-xs text-slate-400">
                          ({travel.employeePosition} - {travel.employeeDivision})
                        </span>
                      </div>

                      {/* Status Badge */}
                      <div className="flex items-center gap-2 self-start sm:self-auto">
                        <span className={`px-3 py-1 rounded-full text-xs font-bold flex items-center gap-1.5 ${
                          isApproved ? "bg-emerald-500/20 text-emerald-300 border border-emerald-500/30" :
                          isCompleted ? "bg-sky-500/20 text-sky-300 border border-sky-500/30" :
                          isPending ? "bg-amber-500/20 text-amber-300 border border-amber-500/30 animate-pulse" :
                          "bg-rose-500/20 text-rose-300 border border-rose-500/30"
                        }`}>
                          {isApproved && <CheckCircle2 className="w-3.5 h-3.5 text-emerald-400" />}
                          {isPending && <Clock className="w-3.5 h-3.5 text-amber-400" />}
                          {isCompleted && <CheckCircle2 className="w-3.5 h-3.5 text-sky-400" />}
                          {isRejected && <XCircle className="w-3.5 h-3.5 text-rose-400" />}
                          <span>{travel.status}</span>
                        </span>
                      </div>

                    </div>

                    {/* Content Details Grid */}
                    <div className="grid grid-cols-1 md:grid-cols-4 gap-4 text-xs">
                      
                      {/* A. Jenis & Tujuan */}
                      <div className="space-y-1.5">
                        <span className="text-[11px] font-bold uppercase text-slate-400 block">
                          A. Jenis & B. Tujuan Dinas
                        </span>
                        <div>
                          <span className="font-bold text-white block">{travel.tripType}</span>
                          <span className="inline-block mt-1 px-2 py-0.5 rounded font-mono text-[11px] bg-emerald-950/70 border border-emerald-500/30 text-emerald-300 font-bold mr-1.5">
                            {travel.destinationType}
                          </span>
                          <span className="text-slate-300 font-semibold">{travel.destinationCity}</span>
                        </div>
                      </div>

                      {/* D. Lamanya Dinas / Hari */}
                      <div className="space-y-1.5">
                        <span className="text-[11px] font-bold uppercase text-slate-400 block">
                          D. Lamanya Dinas / Hari
                        </span>
                        <div className="space-y-0.5">
                          <span className="text-white font-bold block">
                            {travel.durationDays} Hari ({travel.hotelNights} Malam Inap)
                          </span>
                          <span className="text-slate-400 font-mono text-[11px]">
                            {formatDateIndo(travel.startDate)} s/d {formatDateIndo(travel.endDate)}
                          </span>
                        </div>
                      </div>

                      {/* C. Moda & Fasilitas */}
                      <div className="space-y-1.5">
                        <span className="text-[11px] font-bold uppercase text-slate-400 block">
                          C. Fasilitas & Plafon Grade
                        </span>
                        <div className="space-y-0.5 text-slate-300">
                          <div><strong>Transport:</strong> {travel.transportationMode}</div>
                          <div><strong>Hotel:</strong> {travel.hotelClass}</div>
                        </div>
                      </div>

                      {/* Anggaran Voucher */}
                      <div className="space-y-1.5 bg-slate-950/80 p-3 rounded-xl border border-slate-800">
                        <span className="text-[10px] font-bold uppercase text-slate-400 block">
                          Estimasi Voucher Keuangan
                        </span>
                        <div className="font-mono font-black text-sky-400 text-sm">
                          {formatRupiah(travel.totalEstimatedCost)}
                        </div>
                        <div className="text-[10px] text-slate-400 flex items-center justify-between">
                          <span>Voucher: {travel.voucher.voucherNumber}</span>
                          <span className="text-emerald-400 font-semibold">{travel.voucher.settlementStatus}</span>
                        </div>
                      </div>

                    </div>

                    {/* Purpose Statement */}
                    <div className="bg-slate-950/40 p-3 rounded-xl border border-slate-800/60 text-xs text-slate-300">
                      <span className="text-slate-400 font-bold uppercase text-[10px] block mb-0.5">Maksud & Tujuan Tugas:</span>
                      <p className="line-clamp-2 leading-relaxed">{travel.purpose}</p>
                    </div>

                    {/* Actions Bar */}
                    <div className="flex flex-wrap items-center justify-between gap-3 pt-2 border-t border-slate-800/60 text-xs">
                      
                      <div className="text-[11px] text-slate-400 flex items-center gap-2 font-mono">
                        <span>Surat Tugas: {travel.assignmentLetterNumber}</span>
                        {travel.approvedBy && (
                          <span>| Disetujui: <strong className="text-slate-200">{travel.approvedBy}</strong></span>
                        )}
                      </div>

                      <div className="flex flex-wrap items-center gap-2">
                        
                        {/* Approval buttons for Directors/HR if pending */}
                        {isPending && (
                          <>
                            <button
                              onClick={() => handleReject(travel.id)}
                              className="px-3 py-1.5 bg-rose-950/80 hover:bg-rose-900 border border-rose-500/40 text-rose-300 font-bold rounded-lg transition-colors"
                            >
                              Tolak
                            </button>
                            <button
                              onClick={() => handleApprove(travel.id)}
                              className="px-4 py-1.5 bg-emerald-600 hover:bg-emerald-500 text-slate-950 font-black rounded-lg transition-colors shadow-sm"
                            >
                              Setujui SPPD
                            </button>
                          </>
                        )}

                        {/* LPJ & Voucher Settlement Button */}
                        <button
                          onClick={() => setSelectedTravelForSettlement(travel)}
                          className="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-200 font-bold rounded-lg border border-slate-700 flex items-center gap-1.5 transition-colors"
                          title="Input Pertanggungjawaban Realisasi Biaya & Kwitansi"
                        >
                          <Receipt className="w-3.5 h-3.5 text-amber-400" />
                          <span>Input LPJ Keuangan</span>
                        </button>

                        {/* Print SPPD Document */}
                        <button
                          onClick={() => setSelectedTravelForPrint({ travel, type: 'SPPD' })}
                          className="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-200 font-bold rounded-lg border border-slate-700 flex items-center gap-1.5 transition-colors"
                          title="Cetak Surat Perintah Perjalanan Dinas Resmi"
                        >
                          <Printer className="w-3.5 h-3.5 text-sky-400" />
                          <span>Cetak SPPD</span>
                        </button>

                        {/* Print Financial Voucher Document */}
                        <button
                          onClick={() => setSelectedTravelForPrint({ travel, type: 'VOUCHER_LPJ' })}
                          className="px-3 py-1.5 bg-gradient-to-r from-sky-600 to-blue-600 hover:from-sky-500 hover:to-blue-500 text-white font-bold rounded-lg shadow-sm flex items-center gap-1.5 transition-all"
                          title="Cetak Lampiran Voucher Pertanggungjawaban Keuangan"
                        >
                          <FileText className="w-3.5 h-3.5" />
                          <span>Cetak Voucher LPJ</span>
                        </button>

                      </div>

                    </div>

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

        </div>
      )}

      {/* SUB-TAB 2: VOUCHER KEUANGAN & LPJ */}
      {subTab === "FINANCE_VOUCHER" && (
        <div className="space-y-4">
          <div className="bg-slate-900 border border-slate-800 rounded-2xl p-6 space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <h3 className="text-base font-bold text-white flex items-center gap-2">
                  <Receipt className="w-5 h-5 text-emerald-400" />
                  Rekapitulasi Voucher Keuangan & Pertanggungjawaban (LPJ)
                </h3>
                <p className="text-xs text-slate-400">
                  Dokumen lampiran voucher keuangan yang wajib dipertanggungjawabkan sesuai Peraturan Perusahaan.
                </p>
              </div>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full text-xs text-left border-collapse">
                <thead>
                  <tr className="bg-slate-950 border-b border-slate-800 text-[11px] uppercase font-bold text-slate-400">
                    <th className="p-3">No. Voucher</th>
                    <th className="p-3">NIP Pegawai</th>
                    <th className="p-3">Nama & Jabatan</th>
                    <th className="p-3">Tujuan Dinas</th>
                    <th className="p-3 text-right">Uang Muka (Advance)</th>
                    <th className="p-3 text-right">Realisasi (LPJ)</th>
                    <th className="p-3 text-right">Selisih (+/-)</th>
                    <th className="p-3 text-center">Status Settlement</th>
                    <th className="p-3 text-center">Aksi</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-800">
                  {filteredTravels.map((travel) => (
                    <tr key={travel.id} className="hover:bg-slate-800/40">
                      <td className="p-3 font-mono font-bold text-sky-400">
                        {travel.voucher.voucherNumber}
                      </td>
                      <td className="p-3 font-mono font-bold text-white">
                        {travel.employeeNip}
                      </td>
                      <td className="p-3">
                        <strong className="text-white block">{travel.employeeName}</strong>
                        <span className="text-[11px] text-slate-400">{travel.employeePosition}</span>
                      </td>
                      <td className="p-3">
                        <span className="text-slate-300 font-semibold">{travel.destinationCity}</span>
                        <span className="block text-[10px] text-slate-500">{travel.tripType}</span>
                      </td>
                      <td className="p-3 text-right font-mono text-slate-200">
                        {formatRupiah(travel.voucher.advanceAmount)}
                      </td>
                      <td className="p-3 text-right font-mono font-bold text-emerald-400">
                        {formatRupiah(travel.voucher.totalActualRealization || travel.totalEstimatedCost)}
                      </td>
                      <td className={`p-3 text-right font-mono font-bold ${
                        travel.voucher.balanceAmount >= 0 ? "text-emerald-400" : "text-rose-400"
                      }`}>
                        {travel.voucher.balanceAmount >= 0 ? "+" : ""}{formatRupiah(travel.voucher.balanceAmount)}
                      </td>
                      <td className="p-3 text-center">
                        <span className="px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30">
                          {travel.voucher.settlementStatus}
                        </span>
                      </td>
                      <td className="p-3 text-center">
                        <div className="flex items-center justify-center gap-1.5">
                          <button
                            onClick={() => setSelectedTravelForSettlement(travel)}
                            className="p-1.5 bg-slate-800 hover:bg-slate-700 text-amber-300 rounded-lg"
                            title="Edit Realisasi LPJ"
                          >
                            <Edit2 className="w-3.5 h-3.5" />
                          </button>
                          <button
                            onClick={() => setSelectedTravelForPrint({ travel, type: 'VOUCHER_LPJ' })}
                            className="p-1.5 bg-sky-600 hover:bg-sky-500 text-white rounded-lg"
                            title="Cetak Voucher LPJ"
                          >
                            <Printer className="w-3.5 h-3.5" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* SUB-TAB 3: MATRIKS TARIF GRADE */}
      {subTab === "RATES_MATRIX" && (
        <div className="bg-slate-900 border border-slate-800 rounded-2xl p-6 space-y-6">
          <div className="flex items-center justify-between border-b border-slate-800 pb-4">
            <div>
              <h3 className="text-base font-bold text-white flex items-center gap-2">
                <Building2 className="w-5 h-5 text-sky-400" />
                Matriks Plafon Fasilitas & Tarif Perjalanan Dinas Menurut Grade
              </h3>
              <p className="text-xs text-slate-400">
                Plafon standar pengajuan biaya dinas, uang saku harian, uang makan, hotel, dan tiket transportasi.
              </p>
            </div>
            <button
              onClick={() => setIsRatesModalOpen(true)}
              className="px-3 py-1.5 bg-sky-600 hover:bg-sky-500 text-white text-xs font-bold rounded-lg flex items-center gap-1.5"
            >
              <Calculator className="w-3.5 h-3.5" />
              <span>Buka Simulator Biaya</span>
            </button>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {Object.values(TRAVEL_GRADE_RATES_MATRIX).map((rate) => (
              <div key={rate.gradeId} className="bg-slate-950/80 border border-slate-800 rounded-xl p-4 space-y-3">
                <div className="flex items-center justify-between border-b border-slate-800 pb-2">
                  <strong className="text-sm text-white">{rate.gradeName}</strong>
                  <span className="text-[10px] font-mono bg-sky-950 text-sky-300 border border-sky-500/40 px-2 py-0.5 rounded font-bold">
                    {rate.gradeId.toUpperCase()}
                  </span>
                </div>

                <div className="space-y-2 text-xs">
                  <div className="flex justify-between border-b border-slate-800/60 pb-1">
                    <span className="text-slate-400">Hotel Luar Kota:</span>
                    <span className="font-mono text-slate-200 font-bold">{formatRupiah(rate.hotel.outOfTown.ratePerNight)}/mlm ({rate.hotel.outOfTown.standard})</span>
                  </div>
                  <div className="flex justify-between border-b border-slate-800/60 pb-1">
                    <span className="text-slate-400">Transport Pesawat:</span>
                    <span className="text-slate-200 font-medium text-[11px]">{rate.transportation.flight}</span>
                  </div>
                  <div className="flex justify-between border-b border-slate-800/60 pb-1">
                    <span className="text-slate-400">Transport Kereta:</span>
                    <span className="text-slate-200 font-medium text-[11px]">{rate.transportation.train}</span>
                  </div>
                  <div className="flex justify-between border-b border-slate-800/60 pb-1">
                    <span className="text-slate-400">Uang Saku Luar Kota:</span>
                    <span className="font-mono text-amber-300 font-bold">{formatRupiah(rate.dailyAllowance.outOfTown)}/hari</span>
                  </div>
                  <div className="flex justify-between border-b border-slate-800/60 pb-1">
                    <span className="text-slate-400">Uang Makan:</span>
                    <span className="font-mono text-emerald-300 font-bold">{formatRupiah(rate.mealAllowance.outOfTown)}/hari</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-400">Taksi Dalam Kota Tujuan:</span>
                    <span className="font-mono text-purple-300 font-bold">{formatRupiah(rate.localTaxiAllowance.outOfTown)}/hari</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 4. Modals */}
      <TravelRequestFormModal
        isOpen={isCreateModalOpen}
        onClose={() => setIsCreateModalOpen(false)}
        onSubmit={handleCreateTravel}
        currentUser={currentUser}
        employees={employees}
      />

      <TravelRatesTableModal
        isOpen={isRatesModalOpen}
        onClose={() => setIsRatesModalOpen(false)}
      />

      {selectedTravelForPrint && (
        <OfficialTravelPrintDoc
          travel={selectedTravelForPrint.travel}
          documentType={selectedTravelForPrint.type}
          onClose={() => setSelectedTravelForPrint(null)}
        />
      )}

      {selectedTravelForSettlement && (
        <TravelSettlementModal
          isOpen={!!selectedTravelForSettlement}
          onClose={() => setSelectedTravelForSettlement(null)}
          travel={selectedTravelForSettlement}
          onSaveSettlement={handleUpdateTravel}
        />
      )}

    </div>
  );
};

export default OfficialTravelModule;
