import React, { useState, useMemo } from 'react';
import { 
  Calculator, 
  Plus, 
  Edit2, 
  Trash2, 
  Building2, 
  Sparkles, 
  Search, 
  Filter, 
  DollarSign, 
  PieChart, 
  TrendingUp, 
  TrendingDown, 
  AlertTriangle, 
  CheckCircle2, 
  RefreshCw, 
  Layers, 
  FileSpreadsheet, 
  ShieldCheck, 
  Store, 
  Hotel, 
  Cpu, 
  HardHat, 
  Stethoscope, 
  Utensils, 
  Truck, 
  GraduationCap,
  Info,
  X,
  Check,
  ArrowRight,
  Sliders
} from 'lucide-react';
import { BudgetItem, Employee, AuditLog } from '../types';

export interface BusinessPreset {
  id: string;
  name: string;
  categoryName: string;
  icon: React.ElementType;
  description: string;
  recommendedBudgetItems: Omit<BudgetItem, 'realizedAmount'>[];
}

export const BUSINESS_SECTOR_PRESETS: BusinessPreset[] = [
  {
    id: 'saas_tech',
    name: 'SaaS & Enterprise Software Cloud',
    categoryName: 'Teknologi Informasi & SaaS',
    icon: Cpu,
    description: 'Sewa aplikasi cloud, infrastructure AWS/GCP, lisensi API, R&D Tech talent & digital ads.',
    recommendedBudgetItems: [
      {
        code: '5101',
        name: 'Beban Infrastructure Cloud AWS/GCP & Server Rack',
        type: 'Beban',
        division: 'Developer & IT',
        category: 'OPEX Tech',
        annualBudget: 1500000000,
        glAccountDebit: '5101 Beban Server Cloud',
        glAccountCredit: '1103 Bank BCA Operasional',
        description: 'Penyediaan server, database cluster, & CDN global.'
      },
      {
        code: '5102',
        name: 'Beban Lisensi API Third-Party, AI & Cybersecurity Audit',
        type: 'Beban',
        division: 'Developer & IT',
        category: 'OPEX Tech',
        annualBudget: 600000000,
        glAccountDebit: '5102 Beban Lisensi & API',
        glAccountCredit: '1103 Bank BCA Operasional',
        description: 'Langganan LLM AI, Payment Gateway, & Penetration Testing.'
      },
      {
        code: '5103',
        name: 'Beban Gaji, Tunjangan & Bonus Dev Team & Product',
        type: 'Beban',
        division: 'Human Resources & Dev',
        category: 'OPEX SDM',
        annualBudget: 6500000000,
        glAccountDebit: '5103 Beban Gaji Software Dev',
        glAccountCredit: '1104 Bank Mandiri Payroll',
        description: 'Gaji pokok, BPJS, & insentif insinyur software.'
      },
      {
        code: '5104',
        name: 'Beban Digital Marketing Ads, SEO & B2B Tech Event',
        type: 'Beban',
        division: 'Pemasaran & Sales',
        category: 'OPEX Sales',
        annualBudget: 1200000000,
        glAccountDebit: '5104 Beban Marketing SaaS',
        glAccountCredit: '1103 Bank BCA Operasional',
        description: 'Kampanye Google Ads, LinkedIn Ads, & B2B Conference.'
      },
      {
        code: '4101',
        name: 'Pendapatan Sewa Aplikasi SaaS & Monthly Subscription',
        type: 'Pendapatan',
        division: 'Pemasaran & Sales',
        category: 'Revenue Core',
        annualBudget: 14000000000,
        glAccountDebit: '1103 Bank BCA Operasional',
        glAccountCredit: '4101 Pendapatan SaaS Client',
        description: 'Recurring monthly & annual subscription plans dari klien.'
      },
      {
        code: '4102',
        name: 'Pendapatan Custom System Development & Implementation',
        type: 'Pendapatan',
        division: 'Developer & IT',
        category: 'Revenue Service',
        annualBudget: 4500000000,
        glAccountDebit: '1103 Bank BCA Operasional',
        glAccountCredit: '4102 Pendapatan Custom Dev',
        description: 'Jasa integrasi ERP, API custom, & onboarding klien.'
      }
    ]
  },
  {
    id: 'retail_minimarket',
    name: 'Ritel, Supermarket & Minimarket Modern',
    categoryName: 'Ritel & Perdagangan',
    icon: Store,
    description: 'COGS/HPP persediaan barang dagangan, sewa ruko/store, kasir POS, & shrinkage loss.',
    recommendedBudgetItems: [
      {
        code: '5201',
        name: 'HPP / Pembelian Persediaan Barang Dagangan Ritel',
        type: 'Beban',
        division: 'Merchandising & Procurement',
        category: 'COGS',
        annualBudget: 8500000000,
        glAccountDebit: '5201 HPP Persediaan Ritel',
        glAccountCredit: '1103 Bank BCA Operasional',
        description: 'Pengadaan stok FMCG, makanan, minuman & barang toko.'
      },
      {
        code: '5202',
        name: 'Beban Sewa Outlet Ruko, Chiller & Utilitas Listrik Store',
        type: 'Beban',
        division: 'Operasional Store',
        category: 'OPEX Store',
        annualBudget: 1800000000,
        glAccountDebit: '5202 Beban Sewa & Utilitas Toko',
        glAccountCredit: '1103 Bank BCA Operasional',
        description: 'Sewa tempat lokasi toko & listrik freezer/chiller 24 jam.'
      },
      {
        code: '5203',
        name: 'Beban Gaji Pramuniaga, Kasir & Crew Store',
        type: 'Beban',
        division: 'Operasional Store',
        category: 'OPEX SDM',
        annualBudget: 2400000000,
        glAccountDebit: '5203 Beban Gaji Staff Toko',
        glAccountCredit: '1104 Bank Mandiri Payroll',
        description: 'Upah shift pramuniaga, kepala toko & petugas kasir.'
      },
      {
        code: '5204',
        name: 'Beban Shrinkage / Kerusakan & Kerugian Stok Toko',
        type: 'Beban',
        division: 'Audit & Inventory Control',
        category: 'OPEX Store Loss',
        annualBudget: 350000000,
        glAccountDebit: '5204 Beban Shrinkage Stok',
        glAccountCredit: '1101 Kas Utama Operasional',
        description: 'Kerugian barang expired, pecah, atau selisih stok opname.'
      },
      {
        code: '4201',
        name: 'Pendapatan Penjualan Ritel Kasir (POS Cash & QRIS)',
        type: 'Pendapatan',
        division: 'Operasional Store',
        category: 'Revenue Retail',
        annualBudget: 16500000000,
        glAccountDebit: '1103 Bank BCA Operasional',
        glAccountCredit: '4201 Pendapatan Penjualan Ritel',
        description: 'Penjualan langsung toko fisik & platform online ritel.'
      }
    ]
  },
  {
    id: 'hospitality_hotel',
    name: 'Hospitality, Hotel & Resort',
    categoryName: 'Akomodasi & Pariwisata',
    icon: Hotel,
    description: 'Amenities kamar, laundry linen, F&B resto hotel, utilitas AC/boiler, & komisi OTA.',
    recommendedBudgetItems: [
      {
        code: '5301',
        name: 'Beban Guest Amenities, Laundry Linen & Housekeeping',
        type: 'Beban',
        division: 'Housekeeping & Front Office',
        category: 'OPEX Room',
        annualBudget: 1200000000,
        glAccountDebit: '5301 Beban Amenities & Linen',
        glAccountCredit: '1103 Bank BCA Operasional',
        description: 'Perlengkapan mandi kamar, laundry sprei/handuk, & kebersihan.'
      },
      {
        code: '5302',
        name: 'Beban Bahan Baku Dapur Resto & Sarapan Buffet Hotel',
        type: 'Beban',
        division: 'F&B Kitchen',
        category: 'COGS F&B',
        annualBudget: 2100000000,
        glAccountDebit: '5302 Beban Bahan Baku F&B',
        glAccountCredit: '1103 Bank BCA Operasional',
        description: 'Bahan makanan buffet sarapan pagi & menu resto hotel.'
      },
      {
        code: '5303',
        name: 'Beban Utilitas Listrik Chiller, Genset & Air Boiler Hotel',
        type: 'Beban',
        division: 'Engineering & Maintenance',
        category: 'OPEX Utility',
        annualBudget: 1600000000,
        glAccountDebit: '5303 Beban Utilitas Hotel',
        glAccountCredit: '1103 Bank BCA Operasional',
        description: 'Listrik sentral AC, chiller, genset darurat, & air pendorong.'
      },
      {
        code: '5304',
        name: 'Beban Komisi Booking Agent OTA (Traveloka, Agoda, Booking)',
        type: 'Beban',
        division: 'Sales & E-Commerce',
        category: 'OPEX Marketing',
        annualBudget: 950000000,
        glAccountDebit: '5304 Beban Komisi OTA',
        glAccountCredit: '1103 Bank BCA Operasional',
        description: 'Komisi reservasi online travel agent eksternal.'
      },
      {
        code: '4301',
        name: 'Pendapatan Sewa Kamar & Suite Hotel',
        type: 'Pendapatan',
        division: 'Front Office & Sales',
        category: 'Revenue Rooms',
        annualBudget: 12500000000,
        glAccountDebit: '1103 Bank BCA Operasional',
        glAccountCredit: '4301 Pendapatan Sewa Kamar',
        description: 'Hasil reservasi kamar hotel harian, mingguan & grup.'
      },
      {
        code: '4302',
        name: 'Pendapatan Restaurant, Room Service & Ballroom Event',
        type: 'Pendapatan',
        division: 'F&B & Banquet',
        category: 'Revenue F&B',
        annualBudget: 4200000000,
        glAccountDebit: '1103 Bank BCA Operasional',
        glAccountCredit: '4302 Pendapatan Resto & Ballroom',
        description: 'Penjualan resto hotel, catering, room service & sewa gedung.'
      }
    ]
  },
  {
    id: 'construction_contractor',
    name: 'Konstruksi & Kontraktor Bangunan',
    categoryName: 'Jasa Konstruksi & Real Estate',
    icon: HardHat,
    description: 'Material semen & besi, sewa alat berat, K3 safety, biaya subkon, & retensi garansi.',
    recommendedBudgetItems: [
      {
        code: '5401',
        name: 'Beban Material Proyek (Besi, Beton, ReadyMix, Semen)',
        type: 'Beban',
        division: 'Engineering & Site Ops',
        category: 'COGS Material',
        annualBudget: 12500000000,
        glAccountDebit: '5401 Beban Material Proyek',
        glAccountCredit: '1103 Bank BCA Operasional',
        description: 'Pengadaan bahan baku konstruksi sipil & arsitektur.'
      },
      {
        code: '5402',
        name: 'Beban Subkontraktor Spesialis & Upah Tukang Borongan',
        type: 'Beban',
        division: 'Project Management',
        category: 'COGS Labor',
        annualBudget: 6800000000,
        glAccountDebit: '5402 Beban Subkontraktor & Upah',
        glAccountCredit: '1103 Bank BCA Operasional',
        description: 'Jasa pekerjaan spesialis ME, struktur, & tukang lapangan.'
      },
      {
        code: '5403',
        name: 'Beban Sewa Alat Berat (Excavator, Crane) & Mobilisasi',
        type: 'Beban',
        division: 'Equipment & Heavy Machinery',
        category: 'OPEX Equipment',
        annualBudget: 2200000000,
        glAccountDebit: '5403 Beban Alat Berat & Solar',
        glAccountCredit: '1103 Bank BCA Operasional',
        description: 'Sewa excavator, tower crane, BBM solar & biaya pengiriman.'
      },
      {
        code: '5404',
        name: 'Beban Sertifikasi K3, Alat Pelindung Diri & Safety Site',
        type: 'Beban',
        division: 'QSHE & Health Safety',
        category: 'OPEX Safety',
        annualBudget: 450000000,
        glAccountDebit: '5404 Beban Safety K3',
        glAccountCredit: '1101 Kas Utama Operasional',
        description: 'Helm safety, rompi rompi K3, spanduk K3 & sertifikat SMK3.'
      },
      {
        code: '4401',
        name: 'Pendapatan Termijn Konstruksi & Pemborongan Pekerjaan',
        type: 'Pendapatan',
        division: 'Marketing & Commercial',
        category: 'Revenue Project',
        annualBudget: 28000000000,
        glAccountDebit: '1103 Bank BCA Operasional',
        glAccountCredit: '4401 Pendapatan Termijn Proyek',
        description: 'Pencairan invoice progress termijn proyek gedung/infrastruktur.'
      }
    ]
  },
  {
    id: 'healthcare_clinic',
    name: 'Rumah Sakit, Klinik & Farmasi',
    categoryName: 'Pelayanan Kesehatan',
    icon: Stethoscope,
    description: 'Obat-obatan, alkes medis, jasa medis dokter, penanganan limbah B3, & izin Dinkes.',
    recommendedBudgetItems: [
      {
        code: '5501',
        name: 'Beban Obat-Obatan, Reagen Lab & Bahan Medis Habis Pakai',
        type: 'Beban',
        division: 'Farmasi & Laboratorium',
        category: 'COGS Pharma',
        annualBudget: 3800000000,
        glAccountDebit: '5501 Beban Obat & BMHP',
        glAccountCredit: '1103 Bank BCA Operasional',
        description: 'Pengadaan sediaan farmasi, jarum, jarum suntik, reagen lab.'
      },
      {
        code: '5502',
        name: 'Beban Jasa Medis Dokter Spesialis, Dokter Umum & Perawat',
        type: 'Beban',
        division: 'Pelayanan Medis',
        category: 'OPEX Medical Staff',
        annualBudget: 4200000000,
        glAccountDebit: '5502 Beban Jasa Medis Dokter',
        glAccountCredit: '1104 Bank Mandiri Payroll',
        description: 'Honorarium jasa medis dokter, insentif tindakan & perawat.'
      },
      {
        code: '5503',
        name: 'Beban Penanganan Limbah Medis B3 & Kalibrasi Alat Medis',
        type: 'Beban',
        division: 'Sanitasi & Maintenance Alkes',
        category: 'OPEX Compliance',
        annualBudget: 550000000,
        glAccountDebit: '5503 Beban Limbah B3 & Kalibrasi',
        glAccountCredit: '1103 Bank BCA Operasional',
        description: 'Vendor pengolah limbah B3 medis & tera ulang alat kesehatan.'
      },
      {
        code: '4501',
        name: 'Pendapatan Rawat Jalan, Poliklinik & Layanan Farmasi',
        type: 'Pendapatan',
        division: 'Pelayanan Medis',
        category: 'Revenue Medical',
        annualBudget: 11000000000,
        glAccountDebit: '1103 Bank BCA Operasional',
        glAccountCredit: '4501 Pendapatan Klinik & Farmasi',
        description: 'Pendapatan pendaftaran, konsultasi dokter, obat, & BPJS.'
      }
    ]
  },
  {
    id: 'fnb_restaurant',
    name: 'Restoran, Cafe & F&B',
    categoryName: 'Makanan & Minuman',
    icon: Utensils,
    description: 'Bahan baku dapur, kemasan packaging takeaway, gas LPG, royalty franchise & waste.',
    recommendedBudgetItems: [
      {
        code: '5601',
        name: 'HPP / Bahan Baku Dapur Utama (Daging, Sayur, Bumbu, Beras)',
        type: 'Beban',
        division: 'Dapur & Kitchen Head',
        category: 'COGS Food',
        annualBudget: 3200000000,
        glAccountDebit: '5601 HPP Bahan Baku Dapur',
        glAccountCredit: '1103 Bank BCA Operasional',
        description: 'Pembelian bahan makanan segar & bumbu dapur setiap hari.'
      },
      {
        code: '5602',
        name: 'Beban Kemasan Box Takeaway, Cup & Stiker Branding',
        type: 'Beban',
        division: 'Operasional Resto',
        category: 'COGS Packaging',
        annualBudget: 480000000,
        glAccountDebit: '5602 Beban Kemasan Takeaway',
        glAccountCredit: '1103 Bank BCA Operasional',
        description: 'Kantong ramah lingkungan, cup plastik, paper box & kantong.'
      },
      {
        code: '5603',
        name: 'Beban Gas LPG 50kg, Air Bersih & Utilitas Resto',
        type: 'Beban',
        division: 'Operasional Resto',
        category: 'OPEX Utility',
        annualBudget: 360000000,
        glAccountDebit: '5603 Beban Gas & Air Resto',
        glAccountCredit: '1101 Kas Utama Operasional',
        description: 'Tabung gas LPG industri kompor dapur & air PDAM.'
      },
      {
        code: '4601',
        name: 'Pendapatan Penjualan Dine-In, Takeaway & Online Food Delivery',
        type: 'Pendapatan',
        division: 'Operasional Resto',
        category: 'Revenue F&B Sales',
        annualBudget: 7800000000,
        glAccountDebit: '1103 Bank BCA Operasional',
        glAccountCredit: '4601 Pendapatan Penjualan Resto',
        description: 'Hasil kasir makan di tempat, GoFood, GrabFood, & ShopeeFood.'
      }
    ]
  },
  {
    id: 'logistics_fleet',
    name: 'Logistik, Ekspedisi & Transportasi Fleet',
    categoryName: 'Transportasi & Logistik',
    icon: Truck,
    description: 'BBM Solar truk, servis sparepart, asuransi kargo, tol retribusi, KIR & STNK.',
    recommendedBudgetItems: [
      {
        code: '5701',
        name: 'Beban Bahan Bakar Solar Armada Truk & Van Pengiriman',
        type: 'Beban',
        division: 'Fleet & Dispatcher',
        category: 'COGS Fleet Fuel',
        annualBudget: 4500000000,
        glAccountDebit: '5701 Beban BBM Solar Truk',
        glAccountCredit: '1103 Bank BCA Operasional',
        description: 'Pengisian bahan bakar minyak solar armada perjalanan antar kota.'
      },
      {
        code: '5702',
        name: 'Beban Servis Bengkel, Oli, Ban & Sparepart Fleet',
        type: 'Beban',
        division: 'Maintenance Fleet',
        category: 'OPEX Repair',
        annualBudget: 1800000000,
        glAccountDebit: '5702 Beban Servis & Sparepart',
        glAccountCredit: '1103 Bank BCA Operasional',
        description: 'Ganti ban gundul, oli mesin rutin, & perbaikan karoseri.'
      },
      {
        code: '5703',
        name: 'Beban E-Toll, Retribusi Pelabuhan & Timbangan Jalan',
        type: 'Beban',
        division: 'Fleet Operations',
        category: 'COGS Transport Toll',
        annualBudget: 1200000000,
        glAccountDebit: '5703 Beban Tol & Retribusi',
        glAccountCredit: '1101 Kas Utama Operasional',
        description: 'Uang jalan pengemudi untuk tol trans, kapal feri & timbangan.'
      },
      {
        code: '4701',
        name: 'Pendapatan Jasa Pengiriman Kargo & Sewa Truk Kontrak',
        type: 'Pendapatan',
        division: 'Pemasaran & Sales Logistics',
        category: 'Revenue Freight',
        annualBudget: 14500000000,
        glAccountDebit: '1103 Bank BCA Operasional',
        glAccountCredit: '4701 Pendapatan Jasa Kargo',
        description: 'Kontrak sewa angkutan barang tahunan dari manufaktur & ritel.'
      }
    ]
  },
  {
    id: 'education_school',
    name: 'Pendidikan, Sekolah & Universitas',
    categoryName: 'Jasa Pendidikan & Pelatihan',
    icon: GraduationCap,
    description: 'Honor dosen/guru, laboratorium praktikum, beasiswa, pemeliharaan kampus, & akreditasi.',
    recommendedBudgetItems: [
      {
        code: '5801',
        name: 'Beban Honorarium Dosen, Pengajar & Instruktur Laboratorium',
        type: 'Beban',
        division: 'Akademik & Fakultas',
        category: 'OPEX Faculty',
        annualBudget: 5200000000,
        glAccountDebit: '5801 Beban Honor Dosen',
        glAccountCredit: '1104 Bank Mandiri Payroll',
        description: 'Gaji pokok, SKS mengajar, & insentif bimbingan skripsi.'
      },
      {
        code: '5802',
        name: 'Beban Bahan Praktikum, Modul Belajar & Perpustakaan Digital',
        type: 'Beban',
        division: 'Laboratorium & Library',
        category: 'OPEX Academic',
        annualBudget: 850000000,
        glAccountDebit: '5802 Beban Praktikum & Perpustakaan',
        glAccountCredit: '1103 Bank BCA Operasional',
        description: 'Bahan kimia lab, jurnal ilmiah terindeks, & e-book.'
      },
      {
        code: '4801',
        name: 'Pendapatan Uang Kuliah Tunggal (UKT) & Sumbangan Pendidikan',
        type: 'Pendapatan',
        division: 'Keuangan Kampus',
        category: 'Revenue Tuition',
        annualBudget: 11500000000,
        glAccountDebit: '1103 Bank BCA Operasional',
        glAccountCredit: '4801 Pendapatan UKT Mahasiswa',
        description: 'Pembayaran SPP/UKT semesteran dari siswa & mahasiswa.'
      }
    ]
  }
];

interface BudgetDivisionModuleProps {
  currentUser: Employee;
  budgetItems: BudgetItem[];
  onUpdateBudgetItems: React.Dispatch<React.SetStateAction<BudgetItem[]>>;
  onAddAuditLog?: (employeeId: string, log: Omit<AuditLog, 'id' | 'timestamp'>) => void;
}

export const BudgetDivisionModule: React.FC<BudgetDivisionModuleProps> = ({
  currentUser,
  budgetItems,
  onUpdateBudgetItems,
  onAddAuditLog
}) => {
  // State for Filters & Search
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedDivision, setSelectedDivision] = useState<string>('ALL');
  const [selectedType, setSelectedType] = useState<string>('ALL');

  // State for Preset Generator Modal
  const [isPresetModalOpen, setIsPresetModalOpen] = useState(false);
  const [selectedPresetId, setSelectedPresetId] = useState<string>('saas_tech');
  const [presetApplyMode, setPresetApplyMode] = useState<'reset' | 'append'>('reset');

  // State for Create / Edit Budget Item Modal
  const [isItemModalOpen, setIsItemModalOpen] = useState(false);
  const [editingItem, setEditingItem] = useState<BudgetItem | null>(null);

  // Form State
  const [formCode, setFormCode] = useState('');
  const [formName, setFormName] = useState('');
  const [formType, setFormType] = useState<'Beban' | 'Pendapatan'>('Beban');
  const [formDivision, setFormDivision] = useState('');
  const [formCategory, setFormCategory] = useState('OPEX');
  const [formAnnualBudget, setFormAnnualBudget] = useState('');
  const [formGlDebit, setFormGlDebit] = useState('');
  const [formGlCredit, setFormGlCredit] = useState('');
  const [formDescription, setFormDescription] = useState('');

  // State for Toast Notification
  const [toastMessage, setToastMessage] = useState<string | null>(null);

  const triggerToast = (msg: string) => {
    setToastMessage(msg);
    setTimeout(() => setToastMessage(null), 4000);
  };

  // Helper formatting IDR
  const formatIDR = (amount: number) => {
    return new Intl.NumberFormat('id-ID', {
      style: 'currency',
      currency: 'IDR',
      maximumFractionDigits: 0
    }).format(amount);
  };

  // Distinct Divisions list
  const divisionList = useMemo(() => {
    const setDivs = new Set<string>();
    budgetItems.forEach(b => {
      if (b.division) setDivs.add(b.division);
    });
    return Array.from(setDivs);
  }, [budgetItems]);

  // Filtered Budget Items
  const filteredItems = useMemo(() => {
    return budgetItems.filter(item => {
      const q = searchQuery.toLowerCase();
      const matchSearch = 
        item.code.toLowerCase().includes(q) ||
        item.name.toLowerCase().includes(q) ||
        item.division.toLowerCase().includes(q) ||
        (item.category && item.category.toLowerCase().includes(q)) ||
        item.glAccountDebit.toLowerCase().includes(q);

      const matchDiv = selectedDivision === 'ALL' || item.division === selectedDivision;
      const matchType = selectedType === 'ALL' || item.type === selectedType;

      return matchSearch && matchDiv && matchType;
    });
  }, [budgetItems, searchQuery, selectedDivision, selectedType]);

  // KPI Calculations
  const stats = useMemo(() => {
    const totalAllocatedBeban = budgetItems.filter(b => b.type === 'Beban').reduce((s, b) => s + b.annualBudget, 0);
    const totalRealizedBeban = budgetItems.filter(b => b.type === 'Beban').reduce((s, b) => s + b.realizedAmount, 0);
    const totalSisaBeban = totalAllocatedBeban - totalRealizedBeban;

    const totalAllocatedIncome = budgetItems.filter(b => b.type === 'Pendapatan').reduce((s, b) => s + b.annualBudget, 0);
    const totalRealizedIncome = budgetItems.filter(b => b.type === 'Pendapatan').reduce((s, b) => s + b.realizedAmount, 0);

    const globalRealizationPct = totalAllocatedBeban > 0 ? Math.round((totalRealizedBeban / totalAllocatedBeban) * 100) : 0;

    const overbudgetCount = budgetItems.filter(b => b.type === 'Beban' && b.realizedAmount > b.annualBudget).length;

    return {
      totalAllocatedBeban,
      totalRealizedBeban,
      totalSisaBeban,
      totalAllocatedIncome,
      totalRealizedIncome,
      globalRealizationPct,
      overbudgetCount,
      itemCount: budgetItems.length
    };
  }, [budgetItems]);

  // Open Create Modal
  const handleOpenCreate = () => {
    setEditingItem(null);
    setFormCode(`5${Math.floor(100 + Math.random() * 899)}`);
    setFormName('');
    setFormType('Beban');
    setFormDivision(currentUser.division || 'Operasional');
    setFormCategory('OPEX Operasional');
    setFormAnnualBudget('500000000');
    setFormGlDebit('5100 Beban Operasional');
    setFormGlCredit('1103 Bank BCA Operasional');
    setFormDescription('Mata anggaran operasional baru.');
    setIsItemModalOpen(true);
  };

  // Open Edit Modal
  const handleOpenEdit = (item: BudgetItem) => {
    setEditingItem(item);
    setFormCode(item.code);
    setFormName(item.name);
    setFormType(item.type);
    setFormDivision(item.division);
    setFormCategory(item.category || 'OPEX');
    setFormAnnualBudget(String(item.annualBudget));
    setFormGlDebit(item.glAccountDebit);
    setFormGlCredit(item.glAccountCredit);
    setFormDescription(item.description || '');
    setIsItemModalOpen(true);
  };

  // Handle Save (Create or Update)
  const handleSaveItem = (e: React.FormEvent) => {
    e.preventDefault();

    if (!formCode.trim() || !formName.trim() || !formDivision.trim()) {
      alert('Mohon isi Kode, Nama Mata Anggaran, dan Divisi secara lengkap!');
      return;
    }

    const budgetVal = parseFloat(formAnnualBudget.replace(/[^0-9]/g, '')) || 0;

    if (editingItem) {
      // Edit existing
      onUpdateBudgetItems(prev => prev.map(item => {
        if (item.code !== editingItem.code) return item;
        return {
          ...item,
          code: formCode.trim(),
          name: formName.trim(),
          type: formType,
          division: formDivision.trim(),
          category: formCategory.trim(),
          annualBudget: budgetVal,
          glAccountDebit: formGlDebit.trim() || '5101 Beban Operasional',
          glAccountCredit: formGlCredit.trim() || '1103 Bank BCA',
          description: formDescription.trim(),
          isCustom: true
        };
      }));

      triggerToast(`Mata Anggaran ${formCode} - ${formName} berhasil diperbarui!`);

      if (onAddAuditLog) {
        onAddAuditLog(currentUser.id, {
          action: 'UPDATE',
          category: 'Biodata',
          actorName: currentUser.name,
          actorPosition: `${currentUser.position} (Divisi Anggaran)`,
          details: `Mengubah parameter Mata Anggaran [${formCode}] ${formName}. Pagu disesuaikan: ${formatIDR(budgetVal)}`
        });
      }
    } else {
      // Check duplicate code
      if (budgetItems.some(b => b.code.toLowerCase() === formCode.trim().toLowerCase())) {
        alert(`Kode Mata Anggaran "${formCode}" sudah digunakan! Gunakan kode unik lain.`);
        return;
      }

      const newItem: BudgetItem = {
        code: formCode.trim(),
        name: formName.trim(),
        type: formType,
        division: formDivision.trim(),
        category: formCategory.trim(),
        annualBudget: budgetVal,
        realizedAmount: 0,
        glAccountDebit: formGlDebit.trim() || '5101 Beban Operasional',
        glAccountCredit: formGlCredit.trim() || '1103 Bank BCA',
        description: formDescription.trim(),
        isCustom: true
      };

      onUpdateBudgetItems(prev => [newItem, ...prev]);
      triggerToast(`Mata Anggaran baru ${newItem.code} - ${newItem.name} berhasil ditambahkan!`);

      if (onAddAuditLog) {
        onAddAuditLog(currentUser.id, {
          action: 'CREATE',
          category: 'Biodata',
          actorName: currentUser.name,
          actorPosition: `${currentUser.position} (Divisi Anggaran)`,
          details: `Membuat Mata Anggaran Baru [${newItem.code}] ${newItem.name} untuk Divisi ${newItem.division} dengan pagu ${formatIDR(budgetVal)}`
        });
      }
    }

    setIsItemModalOpen(false);
  };

  // Handle Delete Budget Item
  const handleDeleteItem = (item: BudgetItem) => {
    if (item.realizedAmount > 0) {
      const confirmDelete = window.confirm(
        `PERINGATAN AUDIT: Mata Anggaran [${item.code}] ${item.name} memiliki realisasi sebesar ${formatIDR(item.realizedAmount)}.\n\nYakin tetap ingin menghapus mata anggaran ini?`
      );
      if (!confirmDelete) return;
    } else {
      if (!window.confirm(`Yakin ingin menghapus Mata Anggaran [${item.code}] ${item.name}?`)) return;
    }

    onUpdateBudgetItems(prev => prev.filter(b => b.code !== item.code));
    triggerToast(`Mata Anggaran [${item.code}] berhasil dihapus.`);

    if (onAddAuditLog) {
      onAddAuditLog(currentUser.id, {
        action: 'DELETE',
        category: 'Biodata',
        actorName: currentUser.name,
        actorPosition: `${currentUser.position} (Divisi Anggaran)`,
        details: `Menghapus Mata Anggaran [${item.code}] ${item.name} Divisi ${item.division}`
      });
    }
  };

  // Handle Apply Business Preset
  const handleApplyPreset = () => {
    const selectedPreset = BUSINESS_SECTOR_PRESETS.find(p => p.id === selectedPresetId);
    if (!selectedPreset) return;

    const formattedItems: BudgetItem[] = selectedPreset.recommendedBudgetItems.map(item => ({
      ...item,
      realizedAmount: presetApplyMode === 'reset' ? 0 : (budgetItems.find(b => b.code === item.code)?.realizedAmount || 0)
    }));

    if (presetApplyMode === 'reset') {
      const confirmReset = window.confirm(
        `APLIKASI CLIENT RENTAL / WHITE-LABEL:\n\nApakah Anda yakin ingin RESET & PENYESUAIAN OTOMATIS seluruh Mata Anggaran ke Sektor Industri "${selectedPreset.name}"?\n\nLangkah ini akan mengganti susunan mata anggaran sesuai standar bisnis ${selectedPreset.categoryName}.`
      );
      if (!confirmReset) return;

      onUpdateBudgetItems(formattedItems);
      triggerToast(`Berhasil Penyesuaian Otomatis Presets Bisnis Client: "${selectedPreset.name}" (${formattedItems.length} Mata Anggaran)!`);
    } else {
      // Append mode (merge non-duplicate)
      const existingCodes = new Set(budgetItems.map(b => b.code));
      const itemsToAdd = formattedItems.filter(item => !existingCodes.has(item.code));

      if (itemsToAdd.length === 0) {
        alert('Semua mata anggaran dari preset ini sudah ada di daftar Anda!');
        return;
      }

      onUpdateBudgetItems(prev => [...itemsToAdd, ...prev]);
      triggerToast(`Berhasil menambahkan ${itemsToAdd.length} Mata Anggaran dari Preset "${selectedPreset.name}".`);
    }

    if (onAddAuditLog) {
      onAddAuditLog(currentUser.id, {
        action: 'UPDATE',
        category: 'Biodata',
        actorName: currentUser.name,
        actorPosition: `${currentUser.position} (Divisi Anggaran SaaS)`,
        details: `Menerapkan Penyesuaian Otomatis Presets Bisnis Client: [${selectedPreset.name}] Mode: ${presetApplyMode.toUpperCase()}`
      });
    }

    setIsPresetModalOpen(false);
  };

  const selectedPresetObj = BUSINESS_SECTOR_PRESETS.find(p => p.id === selectedPresetId) || BUSINESS_SECTOR_PRESETS[0];

  return (
    <div className="space-y-6 font-sans text-slate-100">

      {/* Toast Notification */}
      {toastMessage && (
        <div className="fixed bottom-5 right-5 z-50 bg-[#0f172a] border-2 border-[#facc15] text-[#facc15] px-5 py-3 shadow-2xl flex items-center gap-3 font-mono text-xs animate-bounce">
          <CheckCircle2 className="w-5 h-5 text-[#facc15] shrink-0" />
          <span>{toastMessage}</span>
        </div>
      )}

      {/* Top Banner: Divisi Anggaran & Preset Client White-Label */}
      <div className="bg-gradient-to-r from-[#0c0f18] via-[#121726] to-[#0c0f18] border-2 border-[#facc15]/40 p-5 sm:p-6 shadow-2xl relative overflow-hidden">
        <div className="absolute top-0 right-0 w-80 h-80 bg-[#facc15]/5 rounded-full blur-3xl pointer-events-none"></div>

        <div className="flex flex-col lg:flex-row items-start lg:items-center justify-between gap-5 relative z-10">
          <div className="space-y-1.5">
            <div className="flex items-center gap-2">
              <span className="bg-[#facc15] text-black text-[10px] font-black px-2 py-0.5 uppercase tracking-wider">
                DIVISI ANGGARAN & FINANCING MANAGEMENT
              </span>
              <span className="bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 text-[10px] font-mono font-bold px-2 py-0.5 uppercase tracking-wider flex items-center gap-1">
                <ShieldCheck className="w-3 h-3 text-emerald-400" />
                SAAS MULTI-TENANT READY
              </span>
            </div>

            <h2 className="text-xl sm:text-2xl font-black uppercase tracking-tight text-white flex items-center gap-2.5">
              <Calculator className="w-6 h-6 text-[#facc15]" />
              Pengelolaan Mata Anggaran & Adaptasi Preset Bisnis
            </h2>

            <p className="text-xs text-slate-300 max-w-3xl leading-relaxed">
              Portal Otorisasi Divisi Anggaran untuk membuat (create), memperbarui (update), dan menghapus (delete) kode mata anggaran perusahaan. Dilengkapi <strong className="text-[#facc15]">Generator Auto-Preset Bisnis Client</strong> yang menyesuaikan struktur COA & Pagu Anggaran secara otomatis saat aplikasi ini disewakan ke berbagai jenis industri client.
            </p>
          </div>

          <div className="flex flex-wrap items-center gap-2.5 w-full lg:w-auto shrink-0">
            <button
              type="button"
              onClick={() => setIsPresetModalOpen(true)}
              className="flex-1 lg:flex-none bg-gradient-to-r from-[#facc15] to-amber-500 hover:from-yellow-400 hover:to-amber-400 text-black font-black text-xs uppercase tracking-wider px-4 py-3 shadow-lg flex items-center justify-center gap-2 transition-all cursor-pointer active:scale-95"
            >
              <Sparkles className="w-4 h-4 text-black" />
              Adaptasi Preset Bisnis Client
            </button>

            <button
              type="button"
              onClick={handleOpenCreate}
              className="flex-1 lg:flex-none bg-[#1e2333] hover:bg-[#282e42] text-white font-bold text-xs uppercase tracking-wider px-4 py-3 border border-[#facc15]/40 flex items-center justify-center gap-2 transition-all cursor-pointer"
            >
              <Plus className="w-4 h-4 text-[#facc15]" />
              Tambah Mata Anggaran
            </button>
          </div>
        </div>

        {/* Realtime KPI Overview */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mt-6 pt-4 border-t border-[#222] font-mono text-xs">
          <div className="bg-[#050608] p-3 border border-[#2e3752]">
            <span className="text-[10px] text-slate-400 uppercase font-bold block">Total Pagu Beban Alokasi:</span>
            <span className="text-sm font-black text-[#facc15] block mt-0.5">
              {formatIDR(stats.totalAllocatedBeban)}
            </span>
          </div>

          <div className="bg-[#050608] p-3 border border-[#2e3752]">
            <span className="text-[10px] text-slate-400 uppercase font-bold block">Total Realisasi Pengeluaran:</span>
            <span className="text-sm font-black text-rose-400 block mt-0.5">
              {formatIDR(stats.totalRealizedBeban)}
            </span>
          </div>

          <div className="bg-[#050608] p-3 border border-[#2e3752]">
            <span className="text-[10px] text-slate-400 uppercase font-bold block">Sisa Pagu Anggaran Beban:</span>
            <span className="text-sm font-black text-emerald-400 block mt-0.5">
              {formatIDR(stats.totalSisaBeban)}
            </span>
          </div>

          <div className="bg-[#050608] p-3 border border-[#2e3752]">
            <span className="text-[10px] text-slate-400 uppercase font-bold block">Persentase Penyerapan Global:</span>
            <span className="text-sm font-black text-sky-400 block mt-0.5 flex items-center justify-between">
              <span>{stats.globalRealizationPct}%</span>
              <span className="text-[10px] text-slate-500 font-sans">{stats.itemCount} Pos Anggaran</span>
            </span>
          </div>
        </div>

      </div>

      {/* Main Filter & Search Control Bar */}
      <div className="bg-[#0f131d] p-4 border border-[#222] flex flex-col md:flex-row items-center justify-between gap-4 font-sans text-xs">
        
        {/* Search Input */}
        <div className="relative w-full md:w-80">
          <Search className="w-4 h-4 text-slate-400 absolute left-3 top-2.5" />
          <input
            type="text"
            value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
            placeholder="Cari kode, nama, divisi, GL..."
            className="w-full bg-[#050608] border border-[#333] pl-9 pr-3 py-2 text-white placeholder-slate-500 text-xs focus:border-[#facc15] outline-none"
          />
        </div>

        {/* Division & Type Dropdown Filters */}
        <div className="flex flex-wrap items-center gap-3 w-full md:w-auto">
          <div className="flex items-center gap-2">
            <Filter className="w-3.5 h-3.5 text-[#facc15]" />
            <span className="text-slate-400 font-mono text-[11px]">Divisi:</span>
            <select
              value={selectedDivision}
              onChange={e => setSelectedDivision(e.target.value)}
              className="bg-[#050608] border border-[#333] text-xs font-mono font-bold text-slate-200 px-2.5 py-1.5 focus:border-[#facc15] outline-none cursor-pointer"
            >
              <option value="ALL">-- Semua Divisi ({divisionList.length}) --</option>
              {divisionList.map(div => (
                <option key={div} value={div}>{div}</option>
              ))}
            </select>
          </div>

          <div className="flex items-center gap-2">
            <span className="text-slate-400 font-mono text-[11px]">Jenis:</span>
            <select
              value={selectedType}
              onChange={e => setSelectedType(e.target.value)}
              className="bg-[#050608] border border-[#333] text-xs font-mono font-bold text-slate-200 px-2.5 py-1.5 focus:border-[#facc15] outline-none cursor-pointer"
            >
              <option value="ALL">Semua Jenis</option>
              <option value="Beban">Beban (Pengeluaran)</option>
              <option value="Pendapatan">Pendapatan (Penerimaan)</option>
            </select>
          </div>
        </div>

      </div>

      {/* Budget Items Table Grid */}
      <div className="bg-[#0f131d] border border-[#222] overflow-hidden shadow-2xl">
        <div className="p-4 bg-[#141824] border-b border-[#222] flex items-center justify-between">
          <div className="flex items-center gap-2 font-mono text-xs">
            <Layers className="w-4 h-4 text-[#facc15]" />
            <span className="font-bold text-white uppercase">
              Daftar Pos Mata Anggaran ({filteredItems.length} Records)
            </span>
          </div>

          {stats.overbudgetCount > 0 && (
            <span className="bg-rose-500/20 text-rose-400 border border-rose-500/40 text-[10px] font-mono font-bold px-2.5 py-1 uppercase tracking-wider flex items-center gap-1.5">
              <AlertTriangle className="w-3.5 h-3.5 text-rose-400" />
              {stats.overbudgetCount} Pos Overbudget!
            </span>
          )}
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-left font-sans text-xs">
            <thead className="bg-[#080a10] border-b border-[#222] font-mono text-[11px] text-slate-400 uppercase tracking-wider">
              <tr>
                <th className="py-3 px-4 font-bold">Kode</th>
                <th className="py-3 px-4 font-bold">Nama Mata Anggaran & Kategori</th>
                <th className="py-3 px-4 font-bold">Divisi Cost Center</th>
                <th className="py-3 px-4 font-bold text-right">Alokasi Pagu (IDR)</th>
                <th className="py-3 px-4 font-bold text-right">Realisasi (IDR)</th>
                <th className="py-3 px-4 font-bold text-center">Penyerapan %</th>
                <th className="py-3 px-4 font-bold text-center">Status Pagu</th>
                <th className="py-3 px-4 font-bold text-center">Aksi (CRUD)</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#1e2333] text-slate-200">
              {filteredItems.map(item => {
                const isBeban = item.type === 'Beban';
                const pct = item.annualBudget > 0 ? Math.round((item.realizedAmount / item.annualBudget) * 100) : 0;
                const sisa = item.annualBudget - item.realizedAmount;

                let statusBadge = (
                  <span className="bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 text-[10px] font-mono px-2 py-0.5 uppercase font-bold">
                    NORMAL
                  </span>
                );

                if (pct >= 100) {
                  statusBadge = (
                    <span className="bg-rose-500/20 text-rose-400 border border-rose-500/40 text-[10px] font-mono px-2 py-0.5 uppercase font-bold flex items-center justify-center gap-1">
                      <AlertTriangle className="w-3 h-3 text-rose-400" />
                      OVERBUDGET
                    </span>
                  );
                } else if (pct >= 85) {
                  statusBadge = (
                    <span className="bg-amber-500/20 text-amber-300 border border-amber-500/40 text-[10px] font-mono px-2 py-0.5 uppercase font-bold">
                      PERHATIAN ({pct}%)
                    </span>
                  );
                }

                return (
                  <tr key={item.code} className="hover:bg-[#161b2a] transition-colors">
                    
                    {/* Kode */}
                    <td className="py-3 px-4 font-mono font-bold text-[#facc15]">
                      {item.code}
                    </td>

                    {/* Nama & GL */}
                    <td className="py-3 px-4 max-w-xs">
                      <div className="font-bold text-white text-xs">{item.name}</div>
                      <div className="flex items-center gap-2 mt-0.5 font-mono text-[10px] text-slate-400">
                        <span className={`px-1.5 py-0.2 ${isBeban ? 'bg-rose-950 text-rose-300' : 'bg-emerald-950 text-emerald-300'}`}>
                          {item.type}
                        </span>
                        <span>{item.category || 'OPEX'}</span>
                        <span className="text-slate-500">• GL: {item.glAccountDebit}</span>
                      </div>
                    </td>

                    {/* Divisi */}
                    <td className="py-3 px-4 font-semibold text-slate-300">
                      {item.division}
                    </td>

                    {/* Alokasi Pagu */}
                    <td className="py-3 px-4 font-mono font-bold text-right text-white">
                      {formatIDR(item.annualBudget)}
                    </td>

                    {/* Realisasi */}
                    <td className="py-3 px-4 font-mono text-right">
                      <span className={isBeban ? 'text-rose-400 font-bold' : 'text-emerald-400 font-bold'}>
                        {formatIDR(item.realizedAmount)}
                      </span>
                      <div className="text-[10px] font-mono text-slate-500">
                        Sisa: {formatIDR(sisa)}
                      </div>
                    </td>

                    {/* Progress % */}
                    <td className="py-3 px-4 text-center font-mono">
                      <div className="text-xs font-bold text-slate-200 mb-1">{pct}%</div>
                      <div className="w-20 bg-slate-800 h-1.5 mx-auto overflow-hidden">
                        <div 
                          className={`h-full transition-all ${pct >= 100 ? 'bg-rose-500' : pct >= 80 ? 'bg-amber-400' : 'bg-emerald-400'}`}
                          style={{ width: `${Math.min(pct, 100)}%` }}
                        ></div>
                      </div>
                    </td>

                    {/* Status Badge */}
                    <td className="py-3 px-4 text-center">
                      {statusBadge}
                    </td>

                    {/* Actions */}
                    <td className="py-3 px-4 text-center">
                      <div className="flex items-center justify-center gap-1.5">
                        <button
                          type="button"
                          onClick={() => handleOpenEdit(item)}
                          className="p-1.5 bg-[#1e2333] hover:bg-[#2c334a] text-slate-200 border border-[#3b4666] cursor-pointer"
                          title="Edit Parameter Mata Anggaran"
                        >
                          <Edit2 className="w-3.5 h-3.5 text-sky-400" />
                        </button>

                        <button
                          type="button"
                          onClick={() => handleDeleteItem(item)}
                          className="p-1.5 bg-[#1e2333] hover:bg-rose-950/60 text-slate-200 border border-[#3b4666] hover:border-rose-700 cursor-pointer"
                          title="Hapus Mata Anggaran"
                        >
                          <Trash2 className="w-3.5 h-3.5 text-rose-400" />
                        </button>
                      </div>
                    </td>

                  </tr>
                );
              })}

              {filteredItems.length === 0 && (
                <tr>
                  <td colSpan={8} className="py-8 text-center text-slate-400 font-mono text-xs">
                    Tidak ada data mata anggaran yang cocok dengan kriteria pencarian.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* MODAL 1: PRESET GENERATOR CLIENT WHITE-LABEL (AUTO-ADAPTATION) */}
      {isPresetModalOpen && (
        <div className="fixed inset-0 z-50 overflow-y-auto bg-black/80 backdrop-blur-sm flex items-center justify-center p-4">
          <div className="bg-[#0a0d14] border-2 border-[#facc15]/50 w-full max-w-4xl shadow-2xl p-6 font-sans text-slate-100 relative">
            
            {/* Modal Header */}
            <div className="flex items-center justify-between border-b border-[#222] pb-4 mb-5">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-[#facc15]/10 border border-[#facc15]/40 text-[#facc15]">
                  <Sparkles className="w-6 h-6 text-[#facc15]" />
                </div>
                <div>
                  <div className="flex items-center gap-2">
                    <span className="bg-[#facc15] text-black text-[9px] font-black px-1.5 py-0.5 uppercase">
                      CLIENT RENTAL PRESET ADAPTOR
                    </span>
                    <span className="text-xs font-mono text-slate-400">Generasi Otomatis COA Bisnis</span>
                  </div>
                  <h3 className="text-lg font-black uppercase text-white tracking-tight mt-0.5">
                    Penyesuaian Presets Jenis Bisnis Baru Client
                  </h3>
                </div>
              </div>

              <button
                type="button"
                onClick={() => setIsPresetModalOpen(false)}
                className="p-1.5 text-slate-400 hover:text-white bg-[#1a1e2b] border border-[#333] cursor-pointer"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Modal Body */}
            <div className="space-y-6">

              <p className="text-xs text-slate-300 leading-relaxed font-sans">
                Saat aplikasi ERP disewakan ke tenant client baru, pilih jenis industri di bawah untuk <strong className="text-[#facc15]">mengatur ulang atau menyesuaikan secara otomatis</strong> seluruh struktur mata anggaran, divisi cost center, dan alokasi pagu standar industri tersebut.
              </p>

              {/* Grid of Sector Presets */}
              <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-3">
                {BUSINESS_SECTOR_PRESETS.map(preset => {
                  const IconComp = preset.icon;
                  const isSelected = preset.id === selectedPresetId;

                  return (
                    <button
                      key={preset.id}
                      type="button"
                      onClick={() => setSelectedPresetId(preset.id)}
                      className={`p-3 text-left border transition-all cursor-pointer relative flex flex-col justify-between ${
                        isSelected 
                          ? 'bg-[#181e30] border-[#facc15] shadow-lg shadow-[#facc15]/10' 
                          : 'bg-[#0f131d] border-[#222] hover:border-[#444]'
                      }`}
                    >
                      <div>
                        <div className="flex items-center justify-between mb-2">
                          <IconComp className={`w-5 h-5 ${isSelected ? 'text-[#facc15]' : 'text-slate-400'}`} />
                          {isSelected && (
                            <span className="w-2 h-2 rounded-full bg-[#facc15] animate-ping"></span>
                          )}
                        </div>

                        <div className="font-bold text-xs text-white uppercase tracking-tight">
                          {preset.name}
                        </div>
                        <div className="text-[10px] text-slate-400 font-mono mt-0.5">
                          {preset.categoryName}
                        </div>
                      </div>

                      <div className="mt-3 pt-2 border-t border-[#222] text-[10px] text-slate-400 font-mono">
                        {preset.recommendedBudgetItems.length} Pos Anggaran Standard
                      </div>
                    </button>
                  );
                })}
              </div>

              {/* Selected Preset Details Preview Box */}
              <div className="bg-[#101420] border border-[#2e3752] p-4 space-y-3 font-sans">
                <div className="flex items-center justify-between border-b border-[#2e3752] pb-2">
                  <span className="text-xs font-bold text-[#facc15] uppercase tracking-wider flex items-center gap-2">
                    <Sliders className="w-4 h-4 text-[#facc15]" />
                    Pratinjau Struktur Mata Anggaran Industri: {selectedPresetObj.name}
                  </span>
                  <span className="text-[11px] font-mono text-slate-300">
                    Total Estimasi Pagu Presets: <strong className="text-emerald-400">{formatIDR(selectedPresetObj.recommendedBudgetItems.reduce((s, i) => s + i.annualBudget, 0))}</strong>
                  </span>
                </div>

                <p className="text-xs text-slate-300 italic">
                  "{selectedPresetObj.description}"
                </p>

                {/* List of recommended items */}
                <div className="space-y-1.5 max-h-48 overflow-y-auto pr-2 font-mono text-xs">
                  {selectedPresetObj.recommendedBudgetItems.map(item => (
                    <div key={item.code} className="bg-[#07090f] p-2 border border-[#222] flex items-center justify-between text-[11px]">
                      <div>
                        <span className="text-[#facc15] font-bold mr-2">[{item.code}]</span>
                        <span className="text-white font-semibold">{item.name}</span>
                        <span className="text-slate-500 text-[10px] ml-2">({item.division})</span>
                      </div>
                      <div className="text-right">
                        <span className="font-bold text-slate-200">{formatIDR(item.annualBudget)}</span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              {/* Mode Selection */}
              <div className="bg-[#0a0d14] p-3 border border-[#333] flex flex-col sm:flex-row items-center justify-between gap-3 text-xs font-mono">
                <span className="text-slate-300 font-bold">Pilih Mode Penerapan Preset:</span>

                <div className="flex items-center gap-4">
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="radio"
                      name="presetMode"
                      value="reset"
                      checked={presetApplyMode === 'reset'}
                      onChange={() => setPresetApplyMode('reset')}
                      className="text-[#facc15] focus:ring-0 cursor-pointer"
                    />
                    <span className="text-rose-300 font-bold">Reset & Ganti Total (Client Baru)</span>
                  </label>

                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="radio"
                      name="presetMode"
                      value="append"
                      checked={presetApplyMode === 'append'}
                      onChange={() => setPresetApplyMode('append')}
                      className="text-[#facc15] focus:ring-0 cursor-pointer"
                    />
                    <span className="text-sky-300 font-bold">Gabungkan / Append ke Data Saat Ini</span>
                  </label>
                </div>
              </div>

            </div>

            {/* Modal Footer Actions */}
            <div className="mt-6 pt-4 border-t border-[#222] flex items-center justify-end gap-3">
              <button
                type="button"
                onClick={() => setIsPresetModalOpen(false)}
                className="bg-[#1a1e2b] hover:bg-[#272d40] text-slate-300 font-bold text-xs uppercase px-4 py-2.5 border border-[#333] cursor-pointer"
              >
                Batal
              </button>

              <button
                type="button"
                onClick={handleApplyPreset}
                className="bg-[#facc15] hover:bg-yellow-400 text-black font-black text-xs uppercase tracking-wider px-5 py-2.5 flex items-center gap-2 shadow-lg transition-all cursor-pointer"
              >
                <Check className="w-4 h-4 text-black" />
                Terapkan Preset Bisnis Ini
              </button>
            </div>

          </div>
        </div>
      )}

      {/* MODAL 2: CREATE / EDIT MATA ANGGARAN (CRUD) */}
      {isItemModalOpen && (
        <div className="fixed inset-0 z-50 overflow-y-auto bg-black/80 backdrop-blur-sm flex items-center justify-center p-4">
          <div className="bg-[#0a0d14] border-2 border-[#facc15]/50 w-full max-w-2xl shadow-2xl p-6 font-sans text-slate-100 relative">
            
            {/* Modal Header */}
            <div className="flex items-center justify-between border-b border-[#222] pb-4 mb-5">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-[#facc15]/10 border border-[#facc15]/40 text-[#facc15]">
                  <Calculator className="w-5 h-5 text-[#facc15]" />
                </div>
                <div>
                  <h3 className="text-base font-black uppercase text-white tracking-tight">
                    {editingItem ? 'Edit Parameter Mata Anggaran' : 'Tambah Mata Anggaran Baru'}
                  </h3>
                  <p className="text-xs text-slate-400 font-mono">
                    {editingItem ? `Mengubah parameter untuk kode [${editingItem.code}]` : 'Buat pos anggaran baru untuk divisi tertentu'}
                  </p>
                </div>
              </div>

              <button
                type="button"
                onClick={() => setIsItemModalOpen(false)}
                className="p-1.5 text-slate-400 hover:text-white bg-[#1a1e2b] border border-[#333] cursor-pointer"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Form Form */}
            <form onSubmit={handleSaveItem} className="space-y-4 text-xs font-sans">
              
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                
                {/* Kode Mata Anggaran */}
                <div>
                  <label className="text-slate-300 font-mono font-bold block mb-1">
                    Kode Mata Anggaran <span className="text-rose-400">*</span>
                  </label>
                  <input
                    type="text"
                    value={formCode}
                    onChange={e => setFormCode(e.target.value)}
                    required
                    placeholder="misal: 5106"
                    className="w-full bg-[#050608] border border-[#333] text-white font-mono font-bold text-xs p-2.5 focus:border-[#facc15] outline-none"
                  />
                </div>

                {/* Jenis */}
                <div>
                  <label className="text-slate-300 font-mono font-bold block mb-1">
                    Jenis Pos Anggaran <span className="text-rose-400">*</span>
                  </label>
                  <select
                    value={formType}
                    onChange={e => setFormType(e.target.value as 'Beban' | 'Pendapatan')}
                    className="w-full bg-[#050608] border border-[#333] text-white font-mono font-bold text-xs p-2.5 focus:border-[#facc15] outline-none cursor-pointer"
                  >
                    <option value="Beban">Beban (Pengeluaran)</option>
                    <option value="Pendapatan">Pendapatan (Penerimaan)</option>
                  </select>
                </div>

              </div>

              {/* Nama Mata Anggaran */}
              <div>
                <label className="text-slate-300 font-mono font-bold block mb-1">
                  Nama Mata Anggaran / Pos Biaya <span className="text-rose-400">*</span>
                </label>
                <input
                  type="text"
                  value={formName}
                  onChange={e => setFormName(e.target.value)}
                  required
                  placeholder="misal: Beban Sewa Cloud Server & API Integrasi"
                  className="w-full bg-[#050608] border border-[#333] text-white font-semibold text-xs p-2.5 focus:border-[#facc15] outline-none"
                />
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                
                {/* Divisi */}
                <div>
                  <label className="text-slate-300 font-mono font-bold block mb-1">
                    Divisi Cost Center <span className="text-rose-400">*</span>
                  </label>
                  <input
                    type="text"
                    value={formDivision}
                    onChange={e => setFormDivision(e.target.value)}
                    required
                    placeholder="misal: Operasional, Developer, Pemasaran"
                    className="w-full bg-[#050608] border border-[#333] text-white text-xs p-2.5 focus:border-[#facc15] outline-none"
                  />
                </div>

                {/* Kategori */}
                <div>
                  <label className="text-slate-300 font-mono font-bold block mb-1">
                    Kategori Finansial
                  </label>
                  <input
                    type="text"
                    value={formCategory}
                    onChange={e => setFormCategory(e.target.value)}
                    placeholder="misal: OPEX, CAPEX, COGS, Revenue"
                    className="w-full bg-[#050608] border border-[#333] text-white text-xs p-2.5 focus:border-[#facc15] outline-none"
                  />
                </div>

              </div>

              {/* Alokasi Pagu Anggaran Tahunan */}
              <div>
                <label className="text-slate-300 font-mono font-bold block mb-1">
                  Alokasi Pagu Anggaran Tahunan (IDR) <span className="text-rose-400">*</span>
                </label>
                <input
                  type="text"
                  value={formAnnualBudget}
                  onChange={e => setFormAnnualBudget(e.target.value)}
                  required
                  placeholder="misal: 1200000000"
                  className="w-full bg-[#050608] border border-[#333] text-[#facc15] font-mono font-black text-sm p-2.5 focus:border-[#facc15] outline-none"
                />
                <span className="text-[10px] text-slate-400 font-mono mt-1 block">
                  Format Angka: {formatIDR(parseFloat(formAnnualBudget.replace(/[^0-9]/g, '')) || 0)}
                </span>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                
                {/* GL Debit */}
                <div>
                  <label className="text-slate-300 font-mono font-bold block mb-1">
                    Akun GL Debet Default
                  </label>
                  <input
                    type="text"
                    value={formGlDebit}
                    onChange={e => setFormGlDebit(e.target.value)}
                    placeholder="misal: 5101 Beban Operasional"
                    className="w-full bg-[#050608] border border-[#333] text-white text-xs p-2.5 focus:border-[#facc15] outline-none font-mono"
                  />
                </div>

                {/* GL Credit */}
                <div>
                  <label className="text-slate-300 font-mono font-bold block mb-1">
                    Akun GL Kredit Default
                  </label>
                  <input
                    type="text"
                    value={formGlCredit}
                    onChange={e => setFormGlCredit(e.target.value)}
                    placeholder="misal: 1103 Bank BCA Operasional"
                    className="w-full bg-[#050608] border border-[#333] text-white text-xs p-2.5 focus:border-[#facc15] outline-none font-mono"
                  />
                </div>

              </div>

              {/* Deskripsi */}
              <div>
                <label className="text-slate-300 font-mono font-bold block mb-1">
                  Deskripsi Peruntukan Anggaran
                </label>
                <textarea
                  value={formDescription}
                  onChange={e => setFormDescription(e.target.value)}
                  rows={2}
                  placeholder="Catatan tujuan alokasi atau peruntukan anggaran..."
                  className="w-full bg-[#050608] border border-[#333] text-white text-xs p-2.5 focus:border-[#facc15] outline-none"
                ></textarea>
              </div>

              {/* Submit Buttons */}
              <div className="pt-4 border-t border-[#222] flex items-center justify-end gap-3">
                <button
                  type="button"
                  onClick={() => setIsItemModalOpen(false)}
                  className="bg-[#1a1e2b] hover:bg-[#272d40] text-slate-300 font-bold text-xs uppercase px-4 py-2.5 border border-[#333] cursor-pointer"
                >
                  Batal
                </button>

                <button
                  type="submit"
                  className="bg-emerald-600 hover:bg-emerald-500 text-white font-black text-xs uppercase tracking-wider px-5 py-2.5 flex items-center gap-2 shadow-lg transition-all cursor-pointer"
                >
                  <Check className="w-4 h-4 text-emerald-100" />
                  Simpan Mata Anggaran
                </button>
              </div>

            </form>

          </div>
        </div>
      )}

    </div>
  );
};
