import React, { useState, useEffect } from "react";
import { 
  OfficialTravelRequest, 
  TravelType, 
  DestinationType, 
  TransportationMode, 
  TRAVEL_GRADE_RATES_MATRIX, 
  getGradeKeyFromEmployee, 
  calculateDaysBetween,
  TravelExpenseItem,
  USD_TO_IDR_RATE
} from "../../types/travel";
import { Employee } from "../../types";
import { 
  X, 
  Send, 
  Calendar, 
  MapPin, 
  Building2, 
  Plane, 
  Train, 
  Ship, 
  Bus, 
  DollarSign, 
  Sparkles, 
  Info, 
  FileText, 
  UserCheck, 
  CreditCard,
  CheckCircle2,
  AlertCircle
} from "lucide-react";

interface TravelRequestFormModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: (travel: OfficialTravelRequest) => void;
  currentUser: Employee;
  employees: Employee[];
}

export const TravelRequestFormModal: React.FC<TravelRequestFormModalProps> = ({
  isOpen,
  onClose,
  onSubmit,
  currentUser,
  employees
}) => {
  // Employee Selection (Defaults to logged-in user with their mandatory NIP)
  const [selectedEmployeeId, setSelectedEmployeeId] = useState<string>(currentUser.id);
  const selectedEmployee = employees.find(e => e.id === selectedEmployeeId) || currentUser;

  // Grade Key & Standards
  const gradeKey = getGradeKeyFromEmployee(
    selectedEmployee.salarySettings?.payGrade, 
    selectedEmployee.position
  );
  const standardRates = TRAVEL_GRADE_RATES_MATRIX[gradeKey] || TRAVEL_GRADE_RATES_MATRIX["grade-1-4"];

  // A. Jenis Dinas
  const [tripType, setTripType] = useState<TravelType>("Hubungan kerja eksternal");

  // B. Tempat Tujuan Dinas
  const [destinationType, setDestinationType] = useState<DestinationType>("Luar kota");
  const [originCity, setOriginCity] = useState("Jakarta (Kantor Pusat)");
  const [destinationCity, setDestinationCity] = useState("Surabaya, Jawa Timur");
  const [destinationDetail, setDestinationDetail] = useState("");

  // C. Moda Transportasi & Standar Fasilitas
  const [transportationMode, setTransportationMode] = useState<TransportationMode>("Pesawat Terbang");
  const [ticketBudget, setTicketBudget] = useState<number>(3500000);

  // D. Lamanya Dinas / Hari (Tanggal Berangkat - Pulang)
  const todayStr = new Date().toISOString().split("T")[0];
  const nextThreeDays = new Date(Date.now() + 2 * 24 * 60 * 60 * 1000).toISOString().split("T")[0];
  const [startDate, setStartDate] = useState<string>(todayStr);
  const [endDate, setEndDate] = useState<string>(nextThreeDays);

  // Purpose & Details
  const [purpose, setPurpose] = useState("");
  const [detailedAgenda, setDetailedAgenda] = useState("");
  const [assignmentLetterNumber, setAssignmentLetterNumber] = useState(`0${Math.floor(Math.random() * 90 + 10)}/ST-DIR/VIII/2026`);

  // Calculated Days
  const durationDays = calculateDaysBetween(startDate, endDate);
  const hotelNights = destinationType === "Dalam kota" ? 0 : Math.max(0, durationDays - 1);

  // Rate calculations based on Destination & Grade
  const hotelRatePerNight = destinationType === "Luar negeri" 
    ? standardRates.hotel.abroad.ratePerNightIdr 
    : destinationType === "Luar kota" 
    ? standardRates.hotel.outOfTown.ratePerNight 
    : standardRates.hotel.inTown.ratePerNight;

  const dailyAllowancePerDay = destinationType === "Luar negeri" 
    ? standardRates.dailyAllowance.abroadIdr 
    : destinationType === "Luar kota" 
    ? standardRates.dailyAllowance.outOfTown 
    : standardRates.dailyAllowance.inTown;

  const mealAllowancePerDay = destinationType === "Luar negeri" 
    ? standardRates.mealAllowance.abroadIdr 
    : destinationType === "Luar kota" 
    ? standardRates.mealAllowance.outOfTown 
    : standardRates.mealAllowance.inTown;

  const localTaxiPerDay = destinationType === "Luar negeri" 
    ? standardRates.localTaxiAllowance.abroadIdr 
    : destinationType === "Luar kota" 
    ? standardRates.localTaxiAllowance.outOfTown 
    : standardRates.localTaxiAllowance.inTown;

  // Total sub-calculations
  const totalHotel = hotelNights * hotelRatePerNight;
  const totalDailyAllowance = durationDays * dailyAllowancePerDay;
  const totalMealAllowance = durationDays * mealAllowancePerDay;
  const totalLocalTaxi = durationDays * localTaxiPerDay;
  const totalEstimatedCost = totalHotel + ticketBudget + totalDailyAllowance + totalMealAllowance + totalLocalTaxi;

  // Update default ticket budget on mode / destination change
  useEffect(() => {
    if (destinationType === "Luar negeri") {
      setTicketBudget(12000000);
      setTransportationMode("Pesawat Terbang");
    } else if (destinationType === "Dalam kota") {
      setTicketBudget(250000);
      setTransportationMode("Kendaraan Operasional / Rental");
    } else {
      if (transportationMode === "Pesawat Terbang") setTicketBudget(3500000);
      else if (transportationMode === "Kereta Api") setTicketBudget(850000);
      else if (transportationMode === "Kapal Laut") setTicketBudget(1200000);
      else setTicketBudget(500000);
    }
  }, [destinationType, transportationMode]);

  if (!isOpen) return null;

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

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    if (!purpose.trim()) {
      alert("Mohon isi Maksud dan Tujuan Perjalanan Dinas!");
      return;
    }

    const sppdSeq = Math.floor(Math.random() * 900 + 100);
    const newId = `sppd-${Date.now()}`;
    const newSppdNumber = `0${sppdSeq}/SPPD-MEDIAN/VIII/2026`;
    const newVoucherNumber = `VCH-SPD-2026-${sppdSeq}`;

    // Construct itemized expenses
    const expenses: TravelExpenseItem[] = [];

    if (hotelNights > 0) {
      expenses.push({
        id: `exp-${Date.now()}-1`,
        category: "Hotel",
        description: `Akomodasi Hotel (${destinationType === 'Luar negeri' ? standardRates.hotel.abroad.standard : destinationType === 'Luar kota' ? standardRates.hotel.outOfTown.standard : standardRates.hotel.inTown.standard})`,
        quantity: hotelNights,
        unit: "Malam",
        unitPrice: hotelRatePerNight,
        totalEstimated: totalHotel,
        notes: `Plafon Grade: ${standardRates.gradeName}`
      });
    }

    expenses.push({
      id: `exp-${Date.now()}-2`,
      category: "Transportasi Tiket",
      description: `Tiket Transportasi ${transportationMode} PP (${originCity} - ${destinationCity} PP)`,
      quantity: 1,
      unit: "Tiket PP",
      unitPrice: ticketBudget,
      totalEstimated: ticketBudget
    });

    expenses.push({
      id: `exp-${Date.now()}-3`,
      category: "Uang Saku",
      description: `Uang Saku Harian Dinas (${durationDays} Hari @ ${formatRupiah(dailyAllowancePerDay)})`,
      quantity: durationDays,
      unit: "Hari",
      unitPrice: dailyAllowancePerDay,
      totalEstimated: totalDailyAllowance,
      notes: "Tarif Standar Plafon Grade"
    });

    expenses.push({
      id: `exp-${Date.now()}-4`,
      category: "Uang Makan",
      description: `Uang Makan Harian Dinas (${durationDays} Hari @ ${formatRupiah(mealAllowancePerDay)})`,
      quantity: durationDays,
      unit: "Hari",
      unitPrice: mealAllowancePerDay,
      totalEstimated: totalMealAllowance
    });

    expenses.push({
      id: `exp-${Date.now()}-5`,
      category: "Taksi Dalam Kota",
      description: `Taksi / Transport Lokal Dalam Kota Tujuan (${durationDays} Hari @ ${formatRupiah(localTaxiPerDay)})`,
      quantity: durationDays,
      unit: "Hari",
      unitPrice: localTaxiPerDay,
      totalEstimated: totalLocalTaxi
    });

    const newTravel: OfficialTravelRequest = {
      id: newId,
      sppdNumber: newSppdNumber,
      assignmentLetterNumber: assignmentLetterNumber,
      employeeId: selectedEmployee.id,
      employeeNip: selectedEmployee.nip, // Wajib NIP Pegawai
      employeeName: selectedEmployee.name,
      employeePosition: selectedEmployee.position,
      employeeDivision: selectedEmployee.division,
      employeeGrade: selectedEmployee.salarySettings?.payGrade || standardRates.gradeName,
      tripType: tripType,
      destinationType: destinationType,
      originCity: originCity,
      destinationCity: destinationCity,
      destinationLocationDetail: destinationDetail,
      transportationMode: transportationMode,
      transportationClass: transportationMode === "Pesawat Terbang" 
        ? standardRates.transportation.flight 
        : transportationMode === "Kereta Api" 
        ? standardRates.transportation.train 
        : transportationMode === "Kapal Laut" 
        ? standardRates.transportation.ship 
        : standardRates.transportation.bus,
      hotelClass: destinationType === "Luar negeri" 
        ? standardRates.hotel.abroad.standard 
        : destinationType === "Luar kota" 
        ? standardRates.hotel.outOfTown.standard 
        : standardRates.hotel.inTown.standard,
      startDate: startDate,
      endDate: endDate,
      durationDays: durationDays,
      hotelNights: hotelNights,
      purpose: purpose,
      detailedAgenda: detailedAgenda,
      expenses: expenses,
      totalEstimatedCost: totalEstimatedCost,
      voucher: {
        voucherNumber: newVoucherNumber,
        issueDate: todayStr,
        advanceAmount: totalEstimatedCost,
        totalEstimatedBudget: totalEstimatedCost,
        totalActualRealization: 0,
        balanceAmount: 0,
        settlementStatus: "Diajukan",
        bankAccountInfo: {
          bankName: selectedEmployee.salarySettings?.bankName || "Bank Mandiri",
          accountNumber: selectedEmployee.salarySettings?.bankAccountNumber || "123-45-67890",
          accountHolder: selectedEmployee.salarySettings?.bankAccountHolder || selectedEmployee.name
        },
        notes: "Uang muka biaya perjalanan dinas wajib dipertanggungjawabkan maksimal 5 hari kerja setelah selesai dinas."
      },
      status: "Menunggu Approval Atasan",
      submittedAt: new Date().toISOString().replace("T", " ").substring(0, 16)
    };

    onSubmit(newTravel);
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto bg-slate-950/80 backdrop-blur-sm flex justify-center items-center p-3 sm:p-6">
      <div className="bg-slate-900 border border-slate-700 rounded-2xl w-full max-w-4xl shadow-2xl overflow-hidden flex flex-col max-h-[92vh]">
        
        {/* Header */}
        <div className="bg-gradient-to-r from-sky-900/60 via-slate-800 to-slate-900 px-6 py-4 border-b border-slate-700 flex items-center justify-between shrink-0">
          <div className="flex items-center gap-3">
            <div className="p-2.5 bg-sky-500/20 border border-sky-400/40 rounded-xl text-sky-400">
              <Plane className="w-5 h-5" />
            </div>
            <div>
              <h2 className="text-base sm:text-lg font-bold text-white flex items-center gap-2">
                Formulir Pengajuan Surat Perintah Perjalanan Dinas (SPPD)
                <span className="text-xs bg-sky-500/20 text-sky-300 border border-sky-500/30 px-2 py-0.5 rounded font-mono">
                  MEDIAN-SPPD-FORM
                </span>
              </h2>
              <p className="text-xs text-slate-400">
                Penerbitan Surat Tugas & Lampiran Voucher Keuangan Wajib Dipertanggungjawabkan
              </p>
            </div>
          </div>

          <button
            onClick={onClose}
            className="p-2 text-slate-400 hover:text-white hover:bg-slate-800 rounded-lg transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Form Body */}
        <form onSubmit={handleSubmit} className="p-6 overflow-y-auto space-y-6 flex-1 text-slate-200">
          
          {/* 1. Mandatory Identity Section (NIP Pegawai Wajib) */}
          <div className="bg-sky-950/40 border border-sky-500/30 rounded-xl p-4 space-y-3">
            <div className="flex items-center justify-between">
              <span className="text-xs font-bold uppercase tracking-wider text-sky-400 flex items-center gap-2">
                <UserCheck className="w-4 h-4" />
                1. Data Identitas Pegawai (Khusus Akun Ini - NIP Pegawai Wajib)
              </span>
              <span className="text-[11px] font-mono bg-sky-500/20 border border-sky-400/30 text-sky-300 px-2 py-0.5 rounded font-bold">
                Grade: {standardRates.gradeName.split(" - ")[0]}
              </span>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 text-xs">
              <div>
                <label className="block text-slate-400 font-semibold mb-1">Nama Pegawai</label>
                <select
                  value={selectedEmployeeId}
                  onChange={(e) => setSelectedEmployeeId(e.target.value)}
                  className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-white font-medium focus:outline-none focus:border-sky-400"
                >
                  {employees.map(emp => (
                    <option key={emp.id} value={emp.id}>
                      {emp.name} ({emp.position})
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-slate-400 font-semibold mb-1">
                  Nomor Induk Pegawai (NIP) <span className="text-sky-400 font-bold">*Wajib</span>
                </label>
                <input
                  type="text"
                  readOnly
                  value={selectedEmployee.nip}
                  className="w-full bg-slate-950 border border-sky-500/40 rounded-lg px-3 py-2 text-sky-300 font-mono font-bold focus:outline-none cursor-not-allowed"
                />
              </div>

              <div>
                <label className="block text-slate-400 font-semibold mb-1">Jabatan & Divisi</label>
                <input
                  type="text"
                  readOnly
                  value={`${selectedEmployee.position} - ${selectedEmployee.division}`}
                  className="w-full bg-slate-950 border border-slate-700 rounded-lg px-3 py-2 text-slate-300 font-medium focus:outline-none cursor-not-allowed"
                />
              </div>
            </div>
          </div>

          {/* 2. Jenis Dinas & Tempat Tujuan */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            
            {/* A. Jenis Dinas */}
            <div className="bg-slate-800/60 border border-slate-700 rounded-xl p-4 space-y-3">
              <label className="text-xs font-bold uppercase tracking-wider text-slate-300 flex items-center gap-2">
                <FileText className="w-4 h-4 text-sky-400" />
                A. Jenis Dinas
              </label>

              <div className="space-y-2">
                {[
                  { value: "Hubungan kerja eksternal", desc: "Kunjungan Klien, Kemitraan B2B, Pemerintah, Vendor, Seminar Industri" },
                  { value: "Hubungan kerja di internal perusahaan", desc: "Konsolidasi Cabang/Site, Raker Direksi, Audit Internal, Supervisi DC" },
                  { value: "Tugas belajar", desc: "Sertifikasi Profesional, Pelatihan Teknis/Manajerial, Workshop Eksekutif" }
                ].map((item) => (
                  <label
                    key={item.value}
                    className={`flex items-start gap-3 p-2.5 rounded-lg border cursor-pointer transition-all ${
                      tripType === item.value
                        ? "bg-sky-500/15 border-sky-400 text-white"
                        : "bg-slate-900/50 border-slate-700/80 text-slate-300 hover:border-slate-600"
                    }`}
                  >
                    <input
                      type="radio"
                      name="tripType"
                      checked={tripType === item.value}
                      onChange={() => setTripType(item.value as TravelType)}
                      className="mt-0.5 text-sky-500 focus:ring-sky-400"
                    />
                    <div className="text-xs">
                      <strong className="block font-semibold">{item.value}</strong>
                      <span className="text-[11px] text-slate-400">{item.desc}</span>
                    </div>
                  </label>
                ))}
              </div>
            </div>

            {/* B. Tempat Tujuan Dinas */}
            <div className="bg-slate-800/60 border border-slate-700 rounded-xl p-4 space-y-3">
              <label className="text-xs font-bold uppercase tracking-wider text-slate-300 flex items-center gap-2">
                <MapPin className="w-4 h-4 text-emerald-400" />
                B. Tempat Tujuan Dinas
              </label>

              <div className="grid grid-cols-3 gap-2">
                {(["Dalam kota", "Luar kota", "Luar negeri"] as DestinationType[]).map((dest) => (
                  <button
                    key={dest}
                    type="button"
                    onClick={() => setDestinationType(dest)}
                    className={`py-2 px-2 text-xs font-bold rounded-lg border transition-all text-center ${
                      destinationType === dest
                        ? "bg-emerald-500/20 border-emerald-400 text-emerald-300 shadow-sm"
                        : "bg-slate-900/60 border-slate-700 text-slate-400 hover:text-white"
                    }`}
                  >
                    {dest}
                  </button>
                ))}
              </div>

              <div className="space-y-2 pt-1 text-xs">
                <div>
                  <label className="block text-slate-400 mb-1">Kota / Negara Tujuan</label>
                  <input
                    type="text"
                    required
                    value={destinationCity}
                    onChange={(e) => setDestinationCity(e.target.value)}
                    placeholder="e.g. Surabaya, Jawa Timur / Singapura"
                    className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-white focus:outline-none focus:border-emerald-400"
                  />
                </div>

                <div>
                  <label className="block text-slate-400 mb-1">Venue / Alamat Lokasi Kunjungan</label>
                  <input
                    type="text"
                    value={destinationDetail}
                    onChange={(e) => setDestinationDetail(e.target.value)}
                    placeholder="e.g. Marina Bay Sands Expo / Kantor BUMN Jatim"
                    className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-white focus:outline-none focus:border-emerald-400"
                  />
                </div>
              </div>
            </div>

          </div>

          {/* 3. D. Lamanya Dinas / Hari (Tanggal Berangkat - Pulang) */}
          <div className="bg-slate-800/60 border border-slate-700 rounded-xl p-4 space-y-3">
            <div className="flex items-center justify-between">
              <label className="text-xs font-bold uppercase tracking-wider text-slate-300 flex items-center gap-2">
                <Calendar className="w-4 h-4 text-amber-400" />
                D. Lamanya Dinas / Hari (Tanggal Berangkat - Pulang)
              </label>

              <div className="text-xs font-mono font-bold bg-amber-500/20 border border-amber-500/30 text-amber-300 px-3 py-1 rounded-lg">
                Total: {durationDays} Hari ({hotelNights} Malam Inap)
              </div>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-xs">
              <div>
                <label className="block text-slate-400 font-semibold mb-1">Tanggal Berangkat</label>
                <input
                  type="date"
                  required
                  value={startDate}
                  onChange={(e) => setStartDate(e.target.value)}
                  className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-white font-mono focus:outline-none focus:border-amber-400"
                />
              </div>

              <div>
                <label className="block text-slate-400 font-semibold mb-1">Tanggal Pulang</label>
                <input
                  type="date"
                  required
                  value={endDate}
                  min={startDate}
                  onChange={(e) => setEndDate(e.target.value)}
                  className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-white font-mono focus:outline-none focus:border-amber-400"
                />
              </div>
            </div>
          </div>

          {/* 4. C. Fasilitas Transportasi & Tarif Sesuai Grade */}
          <div className="bg-slate-800/80 border border-slate-700 rounded-xl p-4 space-y-4">
            <div className="flex items-center justify-between">
              <label className="text-xs font-bold uppercase tracking-wider text-slate-300 flex items-center gap-2">
                <CreditCard className="w-4 h-4 text-sky-400" />
                C. Rincian Fasilitas & Tarif Sesuai Grade Golongan Gaji
              </label>
              <span className="text-[11px] text-slate-400 font-mono">
                Plafon Resmi PT MEDIAN CLOUD
              </span>
            </div>

            {/* Transport Mode Buttons */}
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-xs">
              {[
                { mode: "Pesawat Terbang", icon: Plane, label: "Pesawat" },
                { mode: "Kereta Api", icon: Train, label: "Kereta Api" },
                { mode: "Kapal Laut", icon: Ship, label: "Kapal Laut" },
                { mode: "Bis / Mobil Travel", icon: Bus, label: "Bis / Travel" }
              ].map((item) => {
                const Icon = item.icon;
                const isSelected = transportationMode === item.mode;
                return (
                  <button
                    key={item.mode}
                    type="button"
                    onClick={() => setTransportationMode(item.mode as TransportationMode)}
                    className={`p-2.5 rounded-lg border text-left flex items-center gap-2 transition-all ${
                      isSelected
                        ? "bg-sky-500/20 border-sky-400 text-sky-200"
                        : "bg-slate-900/50 border-slate-700 text-slate-400 hover:text-white"
                    }`}
                  >
                    <Icon className="w-4 h-4 text-sky-400" />
                    <div>
                      <strong className="block text-xs">{item.label}</strong>
                    </div>
                  </button>
                );
              })}
            </div>

            {/* Breakdown Table of Grade Allowances */}
            <div className="bg-slate-950/70 border border-slate-800 rounded-xl overflow-hidden text-xs">
              <table className="w-full border-collapse">
                <thead>
                  <tr className="bg-slate-900 border-b border-slate-800 text-[11px] uppercase font-bold text-slate-400">
                    <th className="p-2.5 text-left">Komponen Fasilitas Sesuai Grade</th>
                    <th className="p-2.5 text-center">Standar Plafon</th>
                    <th className="p-2.5 text-center">Volume</th>
                    <th className="p-2.5 text-right">Tarif Satuan</th>
                    <th className="p-2.5 text-right">Total Estimasi</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-800/60 font-mono text-[11px]">
                  {/* Hotel */}
                  {hotelNights > 0 && (
                    <tr>
                      <td className="p-2.5 font-sans font-semibold text-slate-200">
                        1. Hotel / Akomodasi
                      </td>
                      <td className="p-2.5 text-center font-sans text-slate-400">
                        {destinationType === 'Luar negeri' ? standardRates.hotel.abroad.standard : destinationType === 'Luar kota' ? standardRates.hotel.outOfTown.standard : standardRates.hotel.inTown.standard}
                      </td>
                      <td className="p-2.5 text-center text-slate-300">{hotelNights} Malam</td>
                      <td className="p-2.5 text-right text-slate-400">{formatRupiah(hotelRatePerNight)}</td>
                      <td className="p-2.5 text-right font-bold text-white">{formatRupiah(totalHotel)}</td>
                    </tr>
                  )}

                  {/* Tiket Transport */}
                  <tr>
                    <td className="p-2.5 font-sans font-semibold text-slate-200">
                      2. Tiket {transportationMode}
                    </td>
                    <td className="p-2.5 text-center font-sans text-slate-400">
                      {transportationMode === 'Pesawat Terbang' ? standardRates.transportation.flight : standardRates.transportation.train}
                    </td>
                    <td className="p-2.5 text-center text-slate-300">1 Tiket PP</td>
                    <td className="p-2.5 text-right">
                      <input
                        type="number"
                        value={ticketBudget}
                        onChange={(e) => setTicketBudget(Number(e.target.value) || 0)}
                        className="w-28 bg-slate-800 border border-slate-700 rounded px-2 py-1 text-right text-sky-300 font-mono text-xs focus:outline-none focus:border-sky-400"
                      />
                    </td>
                    <td className="p-2.5 text-right font-bold text-white">{formatRupiah(ticketBudget)}</td>
                  </tr>

                  {/* Uang Saku */}
                  <tr>
                    <td className="p-2.5 font-sans font-semibold text-slate-200">
                      3. Uang Saku Harian
                    </td>
                    <td className="p-2.5 text-center font-sans text-slate-400">
                      Plafon {standardRates.gradeName.split(" - ")[0]}
                    </td>
                    <td className="p-2.5 text-center text-slate-300">{durationDays} Hari</td>
                    <td className="p-2.5 text-right text-slate-400">{formatRupiah(dailyAllowancePerDay)}</td>
                    <td className="p-2.5 text-right font-bold text-white">{formatRupiah(totalDailyAllowance)}</td>
                  </tr>

                  {/* Uang Makan */}
                  <tr>
                    <td className="p-2.5 font-sans font-semibold text-slate-200">
                      4. Uang Makan Harian
                    </td>
                    <td className="p-2.5 text-center font-sans text-slate-400">
                      3x Makan / Hari
                    </td>
                    <td className="p-2.5 text-center text-slate-300">{durationDays} Hari</td>
                    <td className="p-2.5 text-right text-slate-400">{formatRupiah(mealAllowancePerDay)}</td>
                    <td className="p-2.5 text-right font-bold text-white">{formatRupiah(totalMealAllowance)}</td>
                  </tr>

                  {/* Taksi Dalam Kota */}
                  <tr>
                    <td className="p-2.5 font-sans font-semibold text-slate-200">
                      5. Taksi Dalam Kota / Transport Lokal
                    </td>
                    <td className="p-2.5 text-center font-sans text-slate-400">
                      Lumpsum Harian
                    </td>
                    <td className="p-2.5 text-center text-slate-300">{durationDays} Hari</td>
                    <td className="p-2.5 text-right text-slate-400">{formatRupiah(localTaxiPerDay)}</td>
                    <td className="p-2.5 text-right font-bold text-white">{formatRupiah(totalLocalTaxi)}</td>
                  </tr>
                </tbody>
                <tfoot>
                  <tr className="bg-sky-950/60 border-t-2 border-sky-500/40 text-xs">
                    <td colSpan={4} className="p-3 font-bold uppercase text-right text-sky-200">
                      Total Estimasi Anggaran Biaya Dinas (Lampiran Voucher Keuangan):
                    </td>
                    <td className="p-3 text-right font-mono font-black text-sky-300 text-sm">
                      {formatRupiah(totalEstimatedCost)}
                    </td>
                  </tr>
                </tfoot>
              </table>
            </div>
          </div>

          {/* 5. Purpose & Agenda */}
          <div className="space-y-3 text-xs">
            <div>
              <label className="block text-slate-300 font-semibold mb-1">
                Maksud & Tujuan Perjalanan Dinas <span className="text-rose-400">*</span>
              </label>
              <textarea
                required
                rows={2}
                value={purpose}
                onChange={(e) => setPurpose(e.target.value)}
                placeholder="Jelaskan maksud dan tujuan penugasan secara spesifik..."
                className="w-full bg-slate-800 border border-slate-600 rounded-lg p-3 text-white focus:outline-none focus:border-sky-400"
              />
            </div>

            <div>
              <label className="block text-slate-300 font-semibold mb-1">
                Rincian Agenda Kegiatan (Opsional)
              </label>
              <textarea
                rows={2}
                value={detailedAgenda}
                onChange={(e) => setDetailedAgenda(e.target.value)}
                placeholder="Hari 1: ..., Hari 2: ..., Hari 3: ..."
                className="w-full bg-slate-800 border border-slate-600 rounded-lg p-3 text-white focus:outline-none focus:border-sky-400"
              />
            </div>
          </div>

          {/* Legal Notice */}
          <div className="bg-amber-500/10 border border-amber-500/30 rounded-xl p-3 text-xs text-amber-200 flex items-start gap-2.5">
            <Info className="w-4 h-4 text-amber-400 shrink-0 mt-0.5" />
            <p className="text-[11px] leading-relaxed">
              <strong>Pemberitahuan Wajib:</strong> Dokumen pengajuan ini secara otomatis menghasilkan lampiran voucher keuangan advance. Seluruh biaya dinas <strong>wajib dipertanggungjawabkan (LPJ)</strong> dengan melampirkan bukti kwitansi sah, tiket/boarding pass, dan tagihan hotel maksimal 5 hari kerja setelah kepulangan dinas.
            </p>
          </div>

          {/* Footer Actions */}
          <div className="pt-2 flex items-center justify-end gap-3 border-t border-slate-700">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2.5 bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-bold rounded-lg transition-colors"
            >
              Batal
            </button>
            <button
              type="submit"
              className="px-6 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-lg shadow-lg shadow-sky-500/25 flex items-center gap-2 transition-all cursor-pointer"
            >
              <Send className="w-4 h-4" />
              <span>Terbitkan SPPD & Ajukan Voucher</span>
            </button>
          </div>

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

export default TravelRequestFormModal;
