import React, { useState } from "react";
import { 
  TRAVEL_GRADE_RATES_MATRIX, 
  TravelGradeRate, 
  USD_TO_IDR_RATE 
} from "../../types/travel";
import { 
  X, 
  Building2, 
  Plane, 
  Train, 
  Ship, 
  Bus, 
  DollarSign, 
  Coffee, 
  Car, 
  CheckCircle2, 
  Sparkles,
  Info,
  ShieldCheck,
  Calculator
} from "lucide-react";

interface TravelRatesTableModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export const TravelRatesTableModal: React.FC<TravelRatesTableModalProps> = ({
  isOpen,
  onClose
}) => {
  const [activeTab, setActiveTab] = useState<"MATRIX" | "SIMULATOR">("MATRIX");
  const [simGrade, setSimGrade] = useState<string>("grade-10");
  const [simDestination, setSimDestination] = useState<"Luar kota" | "Dalam kota" | "Luar negeri">("Luar kota");
  const [simDays, setSimDays] = useState<number>(3);
  const [simTicket, setSimTicket] = useState<number>(3500000);

  if (!isOpen) return null;

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

  const ratesList = Object.values(TRAVEL_GRADE_RATES_MATRIX);
  const simRate = TRAVEL_GRADE_RATES_MATRIX[simGrade] || TRAVEL_GRADE_RATES_MATRIX["grade-10"];
  const simNights = simDestination === "Dalam kota" ? 0 : Math.max(0, simDays - 1);

  const simHotelPerNight = simDestination === "Luar negeri" 
    ? simRate.hotel.abroad.ratePerNightIdr 
    : simDestination === "Luar kota" 
    ? simRate.hotel.outOfTown.ratePerNight 
    : simRate.hotel.inTown.ratePerNight;

  const simDailyPerDay = simDestination === "Luar negeri" 
    ? simRate.dailyAllowance.abroadIdr 
    : simDestination === "Luar kota" 
    ? simRate.dailyAllowance.outOfTown 
    : simRate.dailyAllowance.inTown;

  const simMealPerDay = simDestination === "Luar negeri" 
    ? simRate.mealAllowance.abroadIdr 
    : simDestination === "Luar kota" 
    ? simRate.mealAllowance.outOfTown 
    : simRate.mealAllowance.inTown;

  const simTaxiPerDay = simDestination === "Luar negeri" 
    ? simRate.localTaxiAllowance.abroadIdr 
    : simDestination === "Luar kota" 
    ? simRate.localTaxiAllowance.outOfTown 
    : simRate.localTaxiAllowance.inTown;

  const totalSimHotel = simNights * simHotelPerNight;
  const totalSimDaily = simDays * simDailyPerDay;
  const totalSimMeal = simDays * simMealPerDay;
  const totalSimTaxi = simDays * simTaxiPerDay;
  const totalSimEstimated = totalSimHotel + simTicket + totalSimDaily + totalSimMeal + totalSimTaxi;

  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-5xl shadow-2xl overflow-hidden flex flex-col max-h-[92vh]">
        
        {/* Header */}
        <div className="bg-slate-800/90 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-emerald-500/20 border border-emerald-400/40 rounded-xl text-emerald-400">
              <Building2 className="w-5 h-5" />
            </div>
            <div>
              <h2 className="text-base sm:text-lg font-bold text-white flex items-center gap-2">
                Tabel Standar Fasilitas & Tarif Perjalanan Dinas
                <span className="text-xs bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 px-2 py-0.5 rounded font-mono">
                  SK Direksi No. 018/SK-DIR/PERJALANAN-DINAS/2026
                </span>
              </h2>
              <p className="text-xs text-slate-400">
                Plafon Resmi Sesuai Grade Golongan Gaji Pegawai PT Media Ekosistem Digital Aplikasi Nasional (MEDIAN CLOUD)
              </p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <div className="flex bg-slate-950 p-1 rounded-lg border border-slate-700 text-xs font-bold">
              <button
                onClick={() => setActiveTab("MATRIX")}
                className={`px-3 py-1 rounded-md transition-all ${
                  activeTab === "MATRIX" ? "bg-sky-500 text-slate-950" : "text-slate-400 hover:text-white"
                }`}
              >
                Matriks Tarif
              </button>
              <button
                onClick={() => setActiveTab("SIMULATOR")}
                className={`px-3 py-1 rounded-md transition-all ${
                  activeTab === "SIMULATOR" ? "bg-sky-500 text-slate-950" : "text-slate-400 hover:text-white"
                }`}
              >
                Simulator Kalkulator
              </button>
            </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>
        </div>

        {/* Content */}
        <div className="p-6 overflow-y-auto space-y-6 flex-1 text-slate-200">
          
          {activeTab === "MATRIX" ? (
            <div className="space-y-6">
              
              {/* Info Note */}
              <div className="bg-sky-950/40 border border-sky-500/30 rounded-xl p-3 text-xs text-sky-200 flex items-start gap-2.5">
                <Info className="w-4 h-4 text-sky-400 shrink-0 mt-0.5" />
                <div className="text-[11px] space-y-1">
                  <p>
                    <strong>Ketentuan Tarif Perjalanan Dinas:</strong> Seluruh perhitungan tarif bersifat batas maksimal (Plafon Standar). Biaya Hotel dan Tiket Transportasi dapat dibayarkan secara <em>at-cost</em> sesuai bukti riil atau sistem booking korporat.
                  </p>
                  <p className="text-slate-400">
                    Nilai tukar patokan dinas luar negeri: <strong>USD 1 = Rp 16.000,-</strong> (Disesuaikan kurs tanggal keberangkatan).
                  </p>
                </div>
              </div>

              {/* Matrix Cards for Each Grade */}
              <div className="space-y-4">
                {ratesList.map((rate) => (
                  <div 
                    key={rate.gradeId} 
                    className="bg-slate-800/70 border border-slate-700 rounded-xl overflow-hidden shadow-sm hover:border-slate-600 transition-all"
                  >
                    {/* Grade Header */}
                    <div className="bg-slate-800 px-4 py-3 border-b border-slate-700/80 flex flex-col sm:flex-row sm:items-center justify-between gap-2">
                      <div className="flex items-center gap-2.5">
                        <span className="p-1.5 bg-sky-500/20 border border-sky-400/30 rounded text-sky-300 font-mono font-bold text-xs">
                          {rate.gradeId.toUpperCase()}
                        </span>
                        <div>
                          <h3 className="text-sm font-bold text-white">{rate.gradeName}</h3>
                          <p className="text-[11px] text-slate-400">{rate.description}</p>
                        </div>
                      </div>

                      <span className="text-[11px] bg-slate-900 border border-slate-700 text-slate-300 px-2.5 py-1 rounded font-mono font-semibold self-start sm:self-auto">
                        Tarif Plafon Standar Korporat
                      </span>
                    </div>

                    {/* Rates Grid */}
                    <div className="p-4 grid grid-cols-1 md:grid-cols-5 gap-3 text-xs">
                      
                      {/* 1. Hotel */}
                      <div className="bg-slate-900/70 border border-slate-800 rounded-lg p-3 space-y-2">
                        <div className="flex items-center gap-1.5 text-sky-400 font-bold uppercase text-[11px]">
                          <Building2 className="w-3.5 h-3.5" />
                          <span>1. Hotel / Akomodasi</span>
                        </div>
                        <div className="space-y-1 text-[11px]">
                          <div className="text-slate-300 font-semibold">{rate.hotel.outOfTown.standard}</div>
                          <div className="flex justify-between text-slate-400">
                            <span>Luar Kota:</span>
                            <span className="font-mono text-white font-bold">{formatRupiah(rate.hotel.outOfTown.ratePerNight)}/mlm</span>
                          </div>
                          <div className="flex justify-between text-slate-400">
                            <span>Luar Negeri:</span>
                            <span className="font-mono text-sky-300 font-bold">${rate.hotel.abroad.ratePerNightUsd}/mlm</span>
                          </div>
                          <div className="flex justify-between text-slate-400">
                            <span>Dalam Kota:</span>
                            <span className="font-mono text-slate-300">{formatRupiah(rate.hotel.inTown.ratePerNight)}/mlm</span>
                          </div>
                        </div>
                      </div>

                      {/* 2. Transportasi Tiket */}
                      <div className="bg-slate-900/70 border border-slate-800 rounded-lg p-3 space-y-2">
                        <div className="flex items-center gap-1.5 text-blue-400 font-bold uppercase text-[11px]">
                          <Plane className="w-3.5 h-3.5" />
                          <span>2. Moda Transportasi</span>
                        </div>
                        <div className="space-y-1 text-[10px] leading-tight">
                          <div className="text-slate-300">
                            <strong>Pesawat:</strong> {rate.transportation.flight}
                          </div>
                          <div className="text-slate-300">
                            <strong>Kereta:</strong> {rate.transportation.train}
                          </div>
                          <div className="text-slate-300">
                            <strong>Kapal/Bis:</strong> {rate.transportation.bus}
                          </div>
                        </div>
                      </div>

                      {/* 3. Uang Saku */}
                      <div className="bg-slate-900/70 border border-slate-800 rounded-lg p-3 space-y-2">
                        <div className="flex items-center gap-1.5 text-amber-400 font-bold uppercase text-[11px]">
                          <DollarSign className="w-3.5 h-3.5" />
                          <span>3. Uang Saku / Hari</span>
                        </div>
                        <div className="space-y-1 text-[11px]">
                          <div className="flex justify-between text-slate-400">
                            <span>Luar Kota:</span>
                            <span className="font-mono text-amber-300 font-bold">{formatRupiah(rate.dailyAllowance.outOfTown)}</span>
                          </div>
                          <div className="flex justify-between text-slate-400">
                            <span>Luar Negeri:</span>
                            <span className="font-mono text-amber-300 font-bold">${rate.dailyAllowance.abroadUsd}</span>
                          </div>
                          <div className="flex justify-between text-slate-400">
                            <span>Dalam Kota:</span>
                            <span className="font-mono text-slate-300">{formatRupiah(rate.dailyAllowance.inTown)}</span>
                          </div>
                        </div>
                      </div>

                      {/* 4. Uang Makan */}
                      <div className="bg-slate-900/70 border border-slate-800 rounded-lg p-3 space-y-2">
                        <div className="flex items-center gap-1.5 text-emerald-400 font-bold uppercase text-[11px]">
                          <Coffee className="w-3.5 h-3.5" />
                          <span>4. Uang Makan / Hari</span>
                        </div>
                        <div className="space-y-1 text-[11px]">
                          <div className="flex justify-between text-slate-400">
                            <span>Luar Kota:</span>
                            <span className="font-mono text-emerald-300 font-bold">{formatRupiah(rate.mealAllowance.outOfTown)}</span>
                          </div>
                          <div className="flex justify-between text-slate-400">
                            <span>Luar Negeri:</span>
                            <span className="font-mono text-emerald-300 font-bold">${rate.mealAllowance.abroadUsd}</span>
                          </div>
                          <div className="flex justify-between text-slate-400">
                            <span>Dalam Kota:</span>
                            <span className="font-mono text-slate-300">{formatRupiah(rate.mealAllowance.inTown)}</span>
                          </div>
                        </div>
                      </div>

                      {/* 5. Taksi Dalam Kota */}
                      <div className="bg-slate-900/70 border border-slate-800 rounded-lg p-3 space-y-2">
                        <div className="flex items-center gap-1.5 text-purple-400 font-bold uppercase text-[11px]">
                          <Car className="w-3.5 h-3.5" />
                          <span>5. Taksi / Transport</span>
                        </div>
                        <div className="space-y-1 text-[11px]">
                          <div className="flex justify-between text-slate-400">
                            <span>Luar Kota:</span>
                            <span className="font-mono text-purple-300 font-bold">{formatRupiah(rate.localTaxiAllowance.outOfTown)}</span>
                          </div>
                          <div className="flex justify-between text-slate-400">
                            <span>Luar Negeri:</span>
                            <span className="font-mono text-purple-300 font-bold">${rate.localTaxiAllowance.abroadUsd}</span>
                          </div>
                          <div className="flex justify-between text-slate-400">
                            <span>Dalam Kota:</span>
                            <span className="font-mono text-slate-300">{formatRupiah(rate.localTaxiAllowance.inTown)}</span>
                          </div>
                        </div>
                      </div>

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

            </div>
          ) : (
            /* Simulator Tab */
            <div className="bg-slate-800/80 border border-slate-700 rounded-xl p-6 space-y-6">
              <div className="flex items-center gap-2 border-b border-slate-700 pb-3">
                <Calculator className="w-5 h-5 text-sky-400" />
                <h3 className="text-sm font-bold text-white">Simulator Perhitungan Estimasi Biaya & Lampiran Voucher</h3>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-4 gap-4 text-xs">
                <div>
                  <label className="block text-slate-400 mb-1 font-semibold">Grade Golongan Pegawai</label>
                  <select
                    value={simGrade}
                    onChange={(e) => setSimGrade(e.target.value)}
                    className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-white font-medium focus:outline-none focus:border-sky-400"
                  >
                    {ratesList.map(r => (
                      <option key={r.gradeId} value={r.gradeId}>{r.gradeName}</option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="block text-slate-400 mb-1 font-semibold">Tujuan Dinas</label>
                  <select
                    value={simDestination}
                    onChange={(e) => setSimDestination(e.target.value as any)}
                    className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-white font-medium focus:outline-none focus:border-sky-400"
                  >
                    <option value="Luar kota">Luar Kota (Antar Provinsi)</option>
                    <option value="Luar negeri">Luar Negeri (International)</option>
                    <option value="Dalam kota">Dalam Kota (Jabodetabek)</option>
                  </select>
                </div>

                <div>
                  <label className="block text-slate-400 mb-1 font-semibold">Durasi Dinas (Hari)</label>
                  <input
                    type="number"
                    min={1}
                    max={30}
                    value={simDays}
                    onChange={(e) => setSimDays(Math.max(1, Number(e.target.value) || 1))}
                    className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-white font-mono focus:outline-none focus:border-sky-400"
                  />
                </div>

                <div>
                  <label className="block text-slate-400 mb-1 font-semibold">Estimasi Tiket PP (Rp)</label>
                  <input
                    type="number"
                    value={simTicket}
                    onChange={(e) => setSimTicket(Number(e.target.value) || 0)}
                    className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sky-300 font-mono focus:outline-none focus:border-sky-400"
                  />
                </div>
              </div>

              {/* Simulation Result Box */}
              <div className="bg-slate-950 border border-slate-800 rounded-xl p-5 space-y-3 font-mono text-xs">
                <div className="flex justify-between text-slate-400 pb-2 border-b border-slate-800">
                  <span className="font-sans font-semibold">Komponen Tarif Sesuai Plafon</span>
                  <span className="font-sans font-semibold">Perhitungan & Total</span>
                </div>

                <div className="flex justify-between text-slate-300">
                  <span className="font-sans">1. Hotel ({simNights} Malam x {formatRupiah(simHotelPerNight)}):</span>
                  <span className="font-bold text-white">{formatRupiah(totalSimHotel)}</span>
                </div>

                <div className="flex justify-between text-slate-300">
                  <span className="font-sans">2. Tiket Transportasi PP:</span>
                  <span className="font-bold text-white">{formatRupiah(simTicket)}</span>
                </div>

                <div className="flex justify-between text-slate-300">
                  <span className="font-sans">3. Uang Saku ({simDays} Hari x {formatRupiah(simDailyPerDay)}):</span>
                  <span className="font-bold text-white">{formatRupiah(totalSimDaily)}</span>
                </div>

                <div className="flex justify-between text-slate-300">
                  <span className="font-sans">4. Uang Makan ({simDays} Hari x {formatRupiah(simMealPerDay)}):</span>
                  <span className="font-bold text-white">{formatRupiah(totalSimMeal)}</span>
                </div>

                <div className="flex justify-between text-slate-300">
                  <span className="font-sans">5. Taksi Dalam Kota ({simDays} Hari x {formatRupiah(simTaxiPerDay)}):</span>
                  <span className="font-bold text-white">{formatRupiah(totalSimTaxi)}</span>
                </div>

                <div className="flex justify-between text-sky-300 pt-3 border-t-2 border-sky-500/40 text-sm font-bold">
                  <span className="font-sans uppercase">Total Estimasi Voucher Keuangan:</span>
                  <span className="text-base font-black">{formatRupiah(totalSimEstimated)}</span>
                </div>
              </div>
            </div>
          )}

        </div>

        {/* Footer */}
        <div className="bg-slate-800/80 px-6 py-3 border-t border-slate-700 flex justify-end">
          <button
            onClick={onClose}
            className="px-5 py-2 bg-slate-700 hover:bg-slate-600 text-white text-xs font-bold rounded-lg transition-colors"
          >
            Tutup
          </button>
        </div>

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

export default TravelRatesTableModal;
