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

import React, { useState, useEffect } from 'react';
import { 
  Building2, BedDouble, Shield, Terminal, Database, RefreshCw, CheckCircle, 
  XCircle, Filter, Search, Plus, CalendarDays, DollarSign, Download, 
  Layers, Compass, Eye, Server, Cpu, HardDrive, Network, Play, Trash2, 
  PlusCircle, Info, Calendar, FileSpreadsheet, Printer, Users, Key, Webhook, 
  Globe, Copy, Check, Activity
} from 'lucide-react';
import { Property, Room, User, Transaction } from '../types';

interface SuperadminConsoleProps {
  currentUser: User;
  properties: Property[];
  rooms: Room[];
  transactions: Transaction[];
  onRefreshAll: () => void;
}

export default function SuperadminConsole({
  currentUser,
  properties,
  rooms,
  transactions,
  onRefreshAll
}: SuperadminConsoleProps) {
  const [activeSubTab, setActiveSubTab] = useState<'consolidation' | 'room-utilization' | 'backend-access'>('consolidation');
  const [loadingLogs, setLoadingLogs] = useState(false);
  const [systemLogs, setSystemLogs] = useState<any[]>([]);
  
  // Quick Room Form State
  const [showAddRoomModal, setShowAddRoomModal] = useState(false);
  const [newRoomForm, setNewRoomForm] = useState({
    propertyId: properties[0]?.id || '',
    roomNumber: '',
    type: 'Deluxe Suite',
    priceDay: 500000,
    status: 'available' as 'available' | 'occupied',
    position: 'Lantai 1',
    facing: 'Utara',
    view: 'Pemandangan Kota',
    facilitiesString: 'AC, Smart TV, Wi-Fi, Water Heater',
    imageUrl: ''
  });

  // Quick Check-in form
  const [showCheckInModal, setShowCheckInModal] = useState<Room | null>(null);
  const [checkInForm, setCheckInForm] = useState({
    buyerName: 'Guest Superadmin',
    buyerPhone: '081234567890',
    startDate: new Date().toISOString().substring(0, 10),
    endDate: new Date(Date.now() + 86400000 * 3).toISOString().substring(0, 10), // 3 days later
    paymentCycle: 'lunas' as 'DP' | 'lunas',
    amountPaid: 0,
    notes: 'Pemesanan cepat langsung dari Konsol Superadmin.'
  });

  // Integration API Keys and Webhooks States
  const [apiKeys, setApiKeys] = useState<any[]>([]);
  const [webhooks, setWebhooks] = useState<any[]>([]);
  const [newKeyName, setNewKeyName] = useState('');
  const [newKeyPerms, setNewKeyPerms] = useState('all');
  const [newWhName, setNewWhName] = useState('');
  const [newWhUrl, setNewWhUrl] = useState('');
  const [newWhEvents, setNewWhEvents] = useState<string[]>(['check_in', 'check_out']);
  const [testingWhId, setTestingWhId] = useState<string | null>(null);
  const [whTestResults, setWhTestResults] = useState<Record<string, { success: boolean; status?: number; error?: string }>>({});

  const fetchApiKeys = async () => {
    try {
      const res = await fetch('/api/api-keys');
      if (res.ok) setApiKeys(await res.json());
    } catch (e) {
      console.error(e);
    }
  };

  const fetchWebhooks = async () => {
    try {
      const res = await fetch('/api/webhooks');
      if (res.ok) setWebhooks(await res.json());
    } catch (e) {
      console.error(e);
    }
  };

  const handleCreateApiKey = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newKeyName.trim()) return;
    try {
      const res = await fetch('/api/api-keys', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: newKeyName, permissions: newKeyPerms })
      });
      if (res.ok) {
        setNewKeyName('');
        showToast('Kunci API baru berhasil dibuat!', 'success');
        fetchApiKeys();
        fetchLogs();
      }
    } catch (err) {
      showToast('Gagal membuat kunci API', 'error');
    }
  };

  const handleDeleteApiKey = async (id: string) => {
    if (!confirm('Apakah Anda yakin ingin mencabut Kunci API ini?')) return;
    try {
      const res = await fetch(`/api/api-keys/${id}`, { method: 'DELETE' });
      if (res.ok) {
        showToast('Kunci API berhasil dicabut!', 'success');
        fetchApiKeys();
        fetchLogs();
      }
    } catch (err) {
      showToast('Gagal mencabut kunci API', 'error');
    }
  };

  const handleCreateWebhook = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newWhName.trim() || !newWhUrl.trim()) return;
    try {
      const res = await fetch('/api/webhooks', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: newWhName, url: newWhUrl, events: newWhEvents })
      });
      if (res.ok) {
        setNewWhName('');
        setNewWhUrl('');
        setNewWhEvents(['check_in', 'check_out']);
        showToast('Webhook baru berhasil didaftarkan!', 'success');
        fetchWebhooks();
        fetchLogs();
      }
    } catch (err) {
      showToast('Gagal mendaftarkan webhook', 'error');
    }
  };

  const handleToggleWebhook = async (wh: any) => {
    const newStatus = wh.status === 'active' ? 'inactive' : 'active';
    try {
      const res = await fetch(`/api/webhooks/${wh.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: newStatus })
      });
      if (res.ok) {
        showToast(`Webhook berhasil ${newStatus === 'active' ? 'diaktifkan' : 'dinonaktifkan'}!`, 'success');
        fetchWebhooks();
        fetchLogs();
      }
    } catch (err) {
      showToast('Gagal mengubah status webhook', 'error');
    }
  };

  const handleDeleteWebhook = async (id: string) => {
    if (!confirm('Apakah Anda yakin ingin menghapus Webhook ini?')) return;
    try {
      const res = await fetch(`/api/webhooks/${id}`, { method: 'DELETE' });
      if (res.ok) {
        showToast('Webhook berhasil dihapus!', 'success');
        fetchWebhooks();
        fetchLogs();
      }
    } catch (err) {
      showToast('Gagal menghapus webhook', 'error');
    }
  };

  const handleTestWebhook = async (id: string) => {
    setTestingWhId(id);
    try {
      const res = await fetch(`/api/webhooks/${id}/test`, { method: 'POST' });
      const data = await res.json();
      setWhTestResults(prev => ({
        ...prev,
        [id]: data
      }));
      if (data.success) {
        showToast('Tes webhook terkirim sukses!', 'success');
      } else {
        showToast('Tes webhook gagal: ' + (data.error || 'Terjadi kesalahan'), 'error');
      }
      fetchLogs();
    } catch (err: any) {
      setWhTestResults(prev => ({
        ...prev,
        [id]: { success: false, error: err.message }
      }));
      showToast('Gagal memproses tes webhook', 'error');
    } finally {
      setTestingWhId(null);
    }
  };

  // API Tester State
  const [selectedEndpoint, setSelectedEndpoint] = useState<string>('/api/rooms');
  const [apiResponse, setApiResponse] = useState<string>('// Klik "Kirim Request" untuk melihat payload JSON real-time dari backend');
  const [apiTesting, setApiTesting] = useState(false);

  // Filters for Room Utilization
  const [filterProperty, setFilterProperty] = useState<string>('all');
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [searchRoom, setSearchRoom] = useState<string>('');

  // Status message
  const [statusMsg, setStatusMsg] = useState<{ text: string; type: 'success' | 'error' } | null>(null);

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

  const showToast = (text: string, type: 'success' | 'error' = 'success') => {
    setStatusMsg({ text, type });
    setTimeout(() => setStatusMsg(null), 4000);
  };

  // Fetch actual logs
  const fetchLogs = async (showLoading: any = false) => {
    if (showLoading === true || systemLogs.length === 0) {
      setLoadingLogs(true);
    }
    try {
      const res = await fetch('/api/logs');
      if (res.ok) {
        const data = await res.json();
        // reverse to show newest logs first
        setSystemLogs(data.reverse());
      }
    } catch (e) {
      console.error("Gagal memuat log sistem", e);
    } finally {
      setLoadingLogs(false);
    }
  };

  useEffect(() => {
    if (activeSubTab === 'backend-access') {
      fetchLogs();
      fetchApiKeys();
      fetchWebhooks();
    }
  }, [activeSubTab]);

  // Execute API test request
  const handleExecuteApi = async () => {
    setApiTesting(true);
    setApiResponse('// Mengirim request ke backend...');
    try {
      const res = await fetch(selectedEndpoint);
      if (res.ok) {
        const json = await res.json();
        setApiResponse(JSON.stringify(json, null, 2));
        showToast("Request API sukses dieksekusi!", "success");
      } else {
        setApiResponse(`// HTTP Error ${res.status}: ${res.statusText}`);
        showToast(`Request gagal dengan kode ${res.status}`, "error");
      }
    } catch (e: any) {
      setApiResponse(`// Error: ${e.message}`);
      showToast("Gagal menghubungi server", "error");
    } finally {
      setApiTesting(false);
    }
  };

  // Create customized System Log
  const handleCreateCustomLog = async () => {
    try {
      const res = await fetch('/api/logs', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          type: 'system',
          message: `[SUPERADMIN ACTION] Audit log manual ditambahkan oleh ${currentUser.fullName}`,
          user: currentUser.username
        })
      });

      if (res.ok) {
        showToast("Log audit berhasil dicatat ke backend!", "success");
        fetchLogs();
      }
    } catch (e) {
      showToast("Gagal mencatat log", "error");
    }
  };

  // Add Room
  const handleAddRoomSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const facilities = newRoomForm.facilitiesString.split(',').map(f => f.trim()).filter(Boolean);

    try {
      const res = await fetch('/api/rooms', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...newRoomForm,
          facilities
        })
      });

      if (res.ok) {
        showToast(`Kamar ${newRoomForm.roomNumber} berhasil ditambahkan!`, "success");
        setShowAddRoomModal(false);
        onRefreshAll();
        // Reset
        setNewRoomForm({
          propertyId: properties[0]?.id || '',
          roomNumber: '',
          type: 'Deluxe Suite',
          priceDay: 500000,
          status: 'available',
          position: 'Lantai 1',
          facing: 'Utara',
          view: 'Pemandangan Kota',
          facilitiesString: 'AC, Smart TV, Wi-Fi, Water Heater',
          imageUrl: ''
        });
      } else {
        const err = await res.json();
        showToast(err.error || "Gagal menambahkan kamar", "error");
      }
    } catch (e) {
      showToast("Koneksi gagal", "error");
    }
  };

  // Toggle Room Status Check-out
  const handleCheckOutRoom = async (room: Room) => {
    if (!window.confirm(`Apakah Anda yakin ingin menyelesaikan sewa/stay untuk Unit ${room.roomNumber}?`)) {
      return;
    }

    try {
      const res = await fetch(`/api/rooms/${room.id}/status`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          status: 'available',
          bookedDates: []
        })
      });

      if (res.ok) {
        showToast(`Unit ${room.roomNumber} sekarang tersedia kembali!`, "success");
        onRefreshAll();
        // Log to backend
        fetch('/api/logs', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            type: 'system',
            message: `Superadmin mengubah status Unit ${room.roomNumber} menjadi Tersedia (Check-Out)`,
            user: currentUser.username
          })
        });
      } else {
        showToast("Gagal memperbarui status unit", "error");
      }
    } catch (e) {
      showToast("Error koneksi", "error");
    }
  };

  // Fast Check-in Submit
  const handleFastCheckIn = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!showCheckInModal) return;

    const selectedProp = properties.find(p => p.id === showCheckInModal.propertyId);
    if (!selectedProp) return;

    try {
      const res = await fetch('/api/transactions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          buyerId: currentUser.id,
          buyerName: checkInForm.buyerName,
          buyerPhone: checkInForm.buyerPhone,
          propertyId: showCheckInModal.propertyId,
          type: 'stay',
          startDate: checkInForm.startDate,
          endDate: checkInForm.endDate,
          totalPrice: showCheckInModal.priceDay * 3, // fast compute
          paymentCycle: checkInForm.paymentCycle,
          amountPaid: checkInForm.paymentCycle === 'DP' ? checkInForm.amountPaid : showCheckInModal.priceDay * 3,
          notes: checkInForm.notes,
          roomId: showCheckInModal.id,
          roomNumber: showCheckInModal.roomNumber,
          reservationTime: checkInForm.startDate + " 14:00"
        })
      });

      if (res.ok) {
        showToast(`Check-In Unit ${showCheckInModal.roomNumber} berhasil diproses!`, "success");
        setShowCheckInModal(null);
        onRefreshAll();
      } else {
        const err = await res.json();
        showToast(err.error || "Gagal memproses check-in", "error");
      }
    } catch (e) {
      showToast("Gagal memproses transaksi", "error");
    }
  };

  // Download Report CSV
  const downloadCSVReport = () => {
    let csvContent = "data:text/csv;charset=utf-8,";
    csvContent += "ID Properti,Nama Properti,Tipe Properti,Nomor Kamar,Tipe Kamar,Harga Per Hari,Status Unit,Posisi,Hadap,Pemandangan\n";
    
    properties.forEach((p) => {
      const propRooms = rooms.filter(r => r.propertyId === p.id);
      if (propRooms.length > 0) {
        propRooms.forEach((r) => {
          csvContent += `"${p.id}","${p.name}","${p.type}","${r.roomNumber}","${r.type}","${r.priceDay}","${r.status}","${r.position || '-'}","${r.facing || '-'}","${r.view || '-'}"\n`;
        });
      } else {
        csvContent += `"${p.id}","${p.name}","${p.type}","No Rooms","N/A","0","N/A","N/A","N/A","N/A"\n`;
      }
    });

    const encodedUri = encodeURI(csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", `Laporan_Konsolidasi_SewaBeliPro_${new Date().toISOString().substring(0, 10)}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    showToast("Laporan Konsolidasi berhasil diunduh!", "success");
  };

  // Filter Rooms
  const filteredRooms = rooms.filter((r) => {
    const matchProp = filterProperty === 'all' || r.propertyId === filterProperty;
    const matchStatus = filterStatus === 'all' || r.status === filterStatus;
    const matchSearch = searchRoom === '' || 
      r.roomNumber.toLowerCase().includes(searchRoom.toLowerCase()) || 
      r.type.toLowerCase().includes(searchRoom.toLowerCase());
    return matchProp && matchStatus && matchSearch;
  });

  return (
    <div className="space-y-6" id="superadmin-console-panel">
      {/* Toast */}
      {statusMsg && (
        <div className={`fixed bottom-5 right-5 z-50 flex items-center space-x-2 px-4 py-3 rounded-xl shadow-lg border animate-bounce ${
          statusMsg.type === 'success' 
            ? 'bg-emerald-50 text-emerald-800 border-emerald-200' 
            : 'bg-rose-50 text-rose-800 border-rose-200'
        }`}>
          <Shield className="h-5 w-5 text-emerald-600 animate-pulse" />
          <span className="text-xs font-semibold">{statusMsg.text}</span>
        </div>
      )}

      {/* Main Banner */}
      <div className="bg-gradient-to-r from-blue-900 to-indigo-950 rounded-2xl p-6 md:p-8 text-white border border-blue-800 shadow-md relative overflow-hidden">
        <div className="absolute right-0 bottom-0 opacity-10 pointer-events-none translate-x-10 translate-y-10">
          <Shield className="h-72 w-72 text-white" />
        </div>
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div className="space-y-2">
            <span className="px-3 py-1 bg-blue-500/20 text-blue-300 rounded-full text-xs font-bold tracking-wider uppercase border border-blue-500/30 inline-block">
              Super Admin Console Active
            </span>
            <h2 className="font-sans font-black text-2xl md:text-3xl tracking-tight flex items-center gap-2">
              <span>Konsol Kendali & Konsolidasi SewaBeliPro</span>
            </h2>
            <p className="text-blue-100 text-xs md:text-sm max-w-2xl leading-relaxed">
              Selamat datang, <strong>{currentUser.fullName}</strong>. Akses penuh ke basis data, kontrol status unit hunian harian/bulanan, dan pengawasan log backend diaktifkan sepenuhnya.
            </p>
          </div>
          <div className="flex flex-wrap gap-2">
            <button
              onClick={onRefreshAll}
              className="px-4 py-2 bg-white/10 hover:bg-white/20 active:scale-95 transition-all text-white rounded-xl text-xs font-bold flex items-center gap-1.5 border border-white/15"
            >
              <RefreshCw className="h-3.5 w-3.5 animate-spin-hover" />
              <span>Sinkron Basis Data</span>
            </button>
            <button
              onClick={() => setShowAddRoomModal(true)}
              className="px-4 py-2 bg-blue-500 hover:bg-blue-600 active:scale-95 transition-all text-white rounded-xl text-xs font-extrabold flex items-center gap-1.5 shadow-lg shadow-blue-500/20"
            >
              <PlusCircle className="h-3.5 w-3.5" />
              <span>Tambah Kamar/Unit</span>
            </button>
          </div>
        </div>
      </div>

      {/* Sub Tabs Selection */}
      <div className="flex border-b border-gray-100 bg-white p-1 rounded-xl shadow-xs gap-1">
        <button
          onClick={() => setActiveSubTab('consolidation')}
          className={`flex-1 py-3 text-xs font-bold rounded-lg transition-all flex items-center justify-center gap-2 ${
            activeSubTab === 'consolidation'
              ? 'bg-blue-50 text-blue-700 shadow-xs'
              : 'text-gray-500 hover:text-gray-900 hover:bg-gray-50'
          }`}
        >
          <Building2 className="h-4 w-4" />
          <span>Laporan Konsolidasi Properti & Kamar</span>
        </button>

        <button
          onClick={() => setActiveSubTab('room-utilization')}
          className={`flex-1 py-3 text-xs font-bold rounded-lg transition-all flex items-center justify-center gap-2 ${
            activeSubTab === 'room-utilization'
              ? 'bg-blue-50 text-blue-700 shadow-xs'
              : 'text-gray-500 hover:text-gray-900 hover:bg-gray-50'
          }`}
        >
          <BedDouble className="h-4 w-4" />
          <span>Daftar Kamar & Pemanfaatan</span>
        </button>

        <button
          onClick={() => setActiveSubTab('backend-access')}
          className={`flex-1 py-3 text-xs font-bold rounded-lg transition-all flex items-center justify-center gap-2 ${
            activeSubTab === 'backend-access'
              ? 'bg-blue-50 text-blue-700 shadow-xs'
              : 'text-gray-500 hover:text-gray-900 hover:bg-gray-50'
          }`}
        >
          <Terminal className="h-4 w-4" />
          <span>Akses Backend & API logs</span>
        </button>
      </div>

      {/* RENDER TAB 1: CONSOLIDATION */}
      {activeSubTab === 'consolidation' && (
        <div className="space-y-6">
          <div className="bg-white p-5 rounded-xl border border-gray-100 shadow-xs flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div>
              <h3 className="font-sans font-bold text-gray-900 text-sm flex items-center gap-1.5">
                <FileSpreadsheet className="h-4 w-4 text-emerald-600" />
                Konsolidasi Portofolio Properti & Struktur Ruangan
              </h3>
              <p className="text-[11px] text-gray-400">Menghubungkan data properti utama dengan daftar unit kamar yang dikelola dalam satu bagan terpadu.</p>
            </div>
            <div className="flex gap-2">
              <button
                onClick={downloadCSVReport}
                className="px-3.5 py-2 bg-emerald-50 hover:bg-emerald-100/80 text-emerald-700 border border-emerald-200 rounded-lg text-xs font-bold flex items-center gap-1.5 transition-colors"
              >
                <Download className="h-3.5 w-3.5" />
                <span>Unduh CSV</span>
              </button>
              <button
                onClick={() => window.print()}
                className="px-3.5 py-2 bg-gray-50 hover:bg-gray-100 text-gray-700 border border-gray-200 rounded-lg text-xs font-bold flex items-center gap-1.5 transition-colors"
              >
                <Printer className="h-3.5 w-3.5" />
                <span>Cetak Laporan</span>
              </button>
            </div>
          </div>

          <div className="space-y-6">
            {properties.map((property) => {
              const propRooms = rooms.filter(r => r.propertyId === property.id);
              const occupiedCount = propRooms.filter(r => r.status === 'occupied').length;
              const availableCount = propRooms.filter(r => r.status === 'available').length;
              const occupancyRate = propRooms.length > 0 ? Math.round((occupiedCount / propRooms.length) * 100) : 0;

              // Potential maximum daily revenue vs current occupancy daily rate
              const maxPotentialDaily = propRooms.reduce((sum, r) => sum + r.priceDay, 0);
              const currentDailyRevenue = propRooms.filter(r => r.status === 'occupied').reduce((sum, r) => sum + r.priceDay, 0);

              return (
                <div key={property.id} className="bg-white rounded-xl border border-gray-100 overflow-hidden shadow-xs hover:border-gray-200 transition-all">
                  {/* Property Info Bar */}
                  <div className="bg-gray-50/50 p-4 border-b border-gray-100 flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div className="flex items-start gap-3">
                      <img
                        src={property.imageUrl}
                        alt=""
                        className="h-10 w-16 object-cover rounded-md border border-gray-200"
                        referrerPolicy="no-referrer"
                      />
                      <div>
                        <h4 className="font-extrabold text-sm text-gray-900">{property.name}</h4>
                        <p className="text-[10px] text-gray-400 flex items-center gap-1">
                          <Compass className="h-2.5 w-2.5 shrink-0" />
                          <span>{property.address}</span>
                          <span className="h-1.5 w-1.5 rounded-full bg-gray-300 mx-1"></span>
                          <span className="capitalize font-semibold text-blue-600">{property.type}</span>
                        </p>
                      </div>
                    </div>

                    {/* Stats Pill */}
                    <div className="flex flex-wrap items-center gap-2 md:gap-4">
                      <div className="bg-white px-2.5 py-1 rounded-lg border border-gray-100 text-center">
                        <span className="block text-[8px] font-bold text-gray-400 uppercase tracking-wider">Kapasitas</span>
                        <span className="text-xs font-extrabold text-gray-800">{propRooms.length} Kamar</span>
                      </div>
                      <div className="bg-white px-2.5 py-1 rounded-lg border border-gray-100 text-center">
                        <span className="block text-[8px] font-bold text-gray-400 uppercase tracking-wider">Okupansi</span>
                        <span className={`text-xs font-extrabold ${occupancyRate > 70 ? 'text-rose-600' : occupancyRate > 30 ? 'text-amber-600' : 'text-emerald-600'}`}>
                          {occupancyRate}% ({occupiedCount} Unit)
                        </span>
                      </div>
                      <div className="bg-emerald-50/50 px-2.5 py-1 rounded-lg border border-emerald-100/30 text-center">
                        <span className="block text-[8px] font-bold text-emerald-600 uppercase tracking-wider">Arus Harian Aktif</span>
                        <span className="text-xs font-black text-emerald-700">{formatRupiah(currentDailyRevenue)} /hari</span>
                      </div>
                    </div>
                  </div>

                  {/* Rooms Consolidated Table */}
                  <div className="overflow-x-auto">
                    <table className="w-full text-left border-collapse text-xs">
                      <thead>
                        <tr className="border-b border-gray-100 text-gray-400 font-bold uppercase bg-white">
                          <th className="py-2.5 px-4 text-[10px]">No. Unit</th>
                          <th className="py-2.5 px-4 text-[10px]">Tipe Kamar & Spesifikasi</th>
                          <th className="py-2.5 px-4 text-[10px]">Lokasi & Arah</th>
                          <th className="py-2.5 px-4 text-[10px]">Fasilitas Kamar</th>
                          <th className="py-2.5 px-4 text-[10px] text-right">Tarif Harian</th>
                          <th className="py-2.5 px-4 text-[10px] text-center">Status Hunian</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-gray-50 text-gray-700">
                        {propRooms.map((room) => {
                          const isOccupied = room.status === 'occupied';
                          return (
                            <tr key={room.id} className="hover:bg-gray-50/20">
                              <td className="py-3 px-4 font-mono font-bold text-gray-900 text-sm">
                                {room.roomNumber}
                              </td>
                              <td className="py-3 px-4">
                                <div className="font-semibold text-gray-800">{room.type}</div>
                                <div className="text-[9px] text-gray-400 flex items-center gap-1.5 mt-0.5">
                                  <Eye className="h-2.5 w-2.5 text-gray-400" />
                                  <span>View: {room.view || "Akses luar"}</span>
                                </div>
                              </td>
                              <td className="py-3 px-4">
                                <div className="text-gray-600">{room.position || "Lantai Utama"}</div>
                                <div className="text-[9px] text-gray-400 flex items-center gap-1 mt-0.5">
                                  <Compass className="h-2.5 w-2.5 text-gray-300" />
                                  <span>Hadap {room.facing || "Utara"}</span>
                                </div>
                              </td>
                              <td className="py-3 px-4">
                                <div className="flex flex-wrap gap-1 max-w-xs">
                                  {room.facilities?.map((f, idx) => (
                                    <span key={idx} className="px-1.5 py-0.5 bg-gray-100 text-[8px] font-medium text-gray-600 rounded">
                                      {f}
                                    </span>
                                  ))}
                                  {(!room.facilities || room.facilities.length === 0) && (
                                    <span className="text-gray-400 italic text-[10px]">Fasilitas standar</span>
                                  )}
                                </div>
                              </td>
                              <td className="py-3 px-4 text-right font-mono font-bold text-gray-900">
                                {formatRupiah(room.priceDay)}
                              </td>
                              <td className="py-3 px-4 text-center">
                                <span className={`px-2 py-0.5 rounded-full text-[9px] font-black uppercase ${
                                  isOccupied 
                                    ? 'bg-rose-50 text-rose-700 border border-rose-100' 
                                    : 'bg-emerald-50 text-emerald-700 border border-emerald-100'
                                }`}>
                                  {isOccupied ? 'Terisi / Booked' : 'Tersedia / Kosong'}
                                </span>
                              </td>
                            </tr>
                          );
                        })}

                        {propRooms.length === 0 && (
                          <tr>
                            <td colSpan={6} className="py-6 text-center text-gray-400 italic text-[11px]">
                              Belum ada unit kamar atau ruangan yang didaftarkan untuk properti ini.
                            </td>
                          </tr>
                        )}
                      </tbody>
                    </table>
                  </div>

                  {/* Potential vs Occupied Footer Metrics */}
                  <div className="bg-gray-50/20 px-4 py-2 text-[10px] text-gray-400 flex justify-between border-t border-gray-100">
                    <span>Estimasi Pendapatan Maksimal Jika Terisi Penuh: <strong>{formatRupiah(maxPotentialDaily)}/hari</strong></span>
                    <span>Deskripsi Properti: <strong className="text-gray-500 font-medium">{property.description.substring(0, 75)}...</strong></span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* RENDER TAB 2: ROOM UTILIZATION */}
      {activeSubTab === 'room-utilization' && (
        <div className="space-y-6">
          {/* Filtering Header bar */}
          <div className="bg-white p-5 rounded-xl border border-gray-100 shadow-xs space-y-4">
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-3 pb-3 border-b border-gray-100">
              <div>
                <h3 className="font-sans font-bold text-gray-900 text-sm">Pemantauan & Pencarian Status Unit Kamar</h3>
                <p className="text-xs text-gray-400">Pilih unit kamar yang kosong untuk melakukan booking langsung bagi tamu atau cek masa sewa.</p>
              </div>
              <span className="text-xs font-mono font-bold text-blue-600 bg-blue-50 px-3 py-1 rounded-lg">
                Ditemukan {filteredRooms.length} unit
              </span>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
              {/* Search */}
              <div className="relative">
                <input
                  type="text"
                  placeholder="Cari nomor kamar / tipe..."
                  value={searchRoom}
                  onChange={(e) => setSearchRoom(e.target.value)}
                  className="w-full pl-8 pr-3 py-2 border border-gray-200 rounded-lg text-xs bg-white focus:outline-hidden focus:border-blue-500"
                />
                <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
              </div>

              {/* Property Select */}
              <div>
                <select
                  value={filterProperty}
                  onChange={(e) => setFilterProperty(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs bg-white focus:outline-hidden focus:border-blue-500"
                >
                  <option value="all">Semua Properti</option>
                  {properties.map(p => (
                    <option key={p.id} value={p.id}>{p.name}</option>
                  ))}
                </select>
              </div>

              {/* Status Select */}
              <div>
                <select
                  value={filterStatus}
                  onChange={(e) => setFilterStatus(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs bg-white focus:outline-hidden focus:border-blue-500"
                >
                  <option value="all">Semua Status Hunian</option>
                  <option value="available">Tersedia / Kosong</option>
                  <option value="occupied">Terisi / Booked</option>
                </select>
              </div>

              <button
                onClick={() => {
                  setFilterProperty('all');
                  setFilterStatus('all');
                  setSearchRoom('');
                }}
                className="px-3 py-2 bg-gray-50 hover:bg-gray-100 text-gray-600 border border-gray-200 rounded-lg text-xs font-bold transition-all"
              >
                Reset Filter
              </button>
            </div>
          </div>

          {/* Rooms Grid */}
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            {filteredRooms.map((room) => {
              const property = properties.find(p => p.id === room.propertyId);
              const isOccupied = room.status === 'occupied';

              return (
                <div
                  key={room.id}
                  className={`bg-white rounded-2xl border transition-all overflow-hidden flex flex-col justify-between ${
                    isOccupied ? 'border-rose-100 hover:border-rose-300' : 'border-gray-100 hover:border-blue-300'
                  }`}
                >
                  {/* Image & Header */}
                  <div className="relative h-44 bg-gray-100 overflow-hidden">
                    {room.imageUrl ? (
                      <img
                        src={room.imageUrl}
                        alt=""
                        className="w-full h-full object-cover"
                        referrerPolicy="no-referrer"
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center text-gray-300 bg-slate-50">
                        <BedDouble className="h-12 w-12 text-gray-400" />
                      </div>
                    )}
                    <span
                      className={`absolute top-3 right-3 px-2.5 py-1 rounded-full text-[9px] font-black uppercase shadow-sm ${
                        isOccupied ? 'bg-rose-500 text-white' : 'bg-emerald-500 text-white'
                      }`}
                    >
                      {isOccupied ? 'Terisi / Booked' : 'Tersedia'}
                    </span>

                    {/* Property tag overlay */}
                    {property && (
                      <span className="absolute bottom-3 left-3 bg-black/60 backdrop-blur-xs text-white text-[9px] font-bold px-2 py-0.5 rounded-md">
                        {property.name}
                      </span>
                    )}
                  </div>

                  {/* Body Info */}
                  <div className="p-4 flex-grow flex flex-col justify-between space-y-3.5">
                    <div>
                      <div className="flex items-start justify-between">
                        <div>
                          <h4 className="font-extrabold text-sm text-gray-900">
                            Unit {room.roomNumber}
                          </h4>
                          <p className="text-[11px] text-gray-500 font-medium">
                            {room.type}
                          </p>
                        </div>
                        <span className="text-sm font-mono font-bold text-blue-600">
                          {formatRupiah(room.priceDay)}
                        </span>
                      </div>

                      {/* Amenities Icons */}
                      {room.facilities && room.facilities.length > 0 && (
                        <div className="mt-2.5 flex flex-wrap gap-1">
                          {room.facilities.map((fac, idx) => (
                            <span
                              key={idx}
                              className="px-1.5 py-0.5 rounded bg-gray-100 text-[8px] text-gray-600 font-bold uppercase"
                            >
                              {fac}
                            </span>
                          ))}
                        </div>
                      )}
                    </div>

                    {/* Grid Specifications */}
                    <div className="pt-3 border-t border-gray-100 grid grid-cols-2 gap-2 text-[10px] text-gray-500">
                      <div className="flex items-center gap-1.5">
                        <Layers className="h-3 w-3 text-gray-400 shrink-0" />
                        <span className="truncate">{room.position || "Lantai Utama"}</span>
                      </div>
                      <div className="flex items-center gap-1.5">
                        <Compass className="h-3 w-3 text-gray-400 shrink-0" />
                        <span className="truncate">Hadap {room.facing || "Utara"}</span>
                      </div>
                      <div className="flex items-center gap-1.5 col-span-2">
                        <Eye className="h-3 w-3 text-gray-400 shrink-0" />
                        <span className="truncate">View: {room.view || "Taman"}</span>
                      </div>
                    </div>
                  </div>

                  {/* Actions Bar footer */}
                  <div className="p-3 bg-gray-50/50 border-t border-gray-100 flex items-center justify-between gap-2">
                    {isOccupied ? (
                      <>
                        <div className="text-[9px] text-rose-600 font-mono font-bold">
                          {room.bookedDates && room.bookedDates.length > 0 
                            ? room.bookedDates[0] 
                            : "Masa sewa aktif"}
                        </div>
                        <button
                          onClick={() => handleCheckOutRoom(room)}
                          className="px-3 py-1.5 bg-rose-50 hover:bg-rose-100 text-rose-700 border border-rose-200 rounded-lg text-[10px] font-bold transition-all active:scale-95 shrink-0"
                        >
                          Check-Out Unit
                        </button>
                      </>
                    ) : (
                      <>
                        <span className="text-[10px] text-emerald-600 font-bold flex items-center gap-1">
                          <CheckCircle className="h-3.5 w-3.5" />
                          Siap Huni / Stay
                        </span>
                        <button
                          onClick={() => {
                            setCheckInForm(prev => ({
                              ...prev,
                              notes: `Check-in cepat superadmin untuk Kamar ${room.roomNumber}`
                            }));
                            setShowCheckInModal(room);
                          }}
                          className="px-3.5 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-[10px] font-extrabold transition-all active:scale-95 shadow-xs"
                        >
                          Check-In Tamu
                        </button>
                      </>
                    )}
                  </div>
                </div>
              );
            })}

            {filteredRooms.length === 0 && (
              <div className="col-span-full bg-white p-16 text-center rounded-2xl border border-gray-100">
                <BedDouble className="h-12 w-12 text-gray-300 mx-auto" />
                <h3 className="font-bold text-gray-800 mt-3 text-sm">Tidak Ada Kamar/Unit Sesuai Kriteria</h3>
                <p className="text-xs text-gray-400 mt-1 max-w-sm mx-auto">Silakan sesuaikan filter pencarian atau buat unit baru menggunakan tombol "Tambah Kamar/Unit".</p>
              </div>
            )}
          </div>
        </div>
      )}

      {/* RENDER TAB 3: BACKEND ACCESS & API LOGS */}
      {activeSubTab === 'backend-access' && (
        <div className="space-y-6">
          {/* Simulated Backend Server Health */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div className="bg-white p-5 rounded-xl border border-gray-100 shadow-xs">
              <div className="flex items-center justify-between mb-2">
                <span className="text-xs font-bold text-gray-400 uppercase tracking-wider">Status Server</span>
                <Server className="h-4 w-4 text-emerald-600" />
              </div>
              <div className="flex items-baseline space-x-1.5">
                <span className="h-2 w-2 rounded-full bg-emerald-500 animate-pulse"></span>
                <span className="text-lg font-black text-gray-800">ONLINE</span>
              </div>
              <span className="text-[10px] text-gray-400 mt-1 block">Uptime: 99.98% (Express Node.js)</span>
            </div>

            <div className="bg-white p-5 rounded-xl border border-gray-100 shadow-xs">
              <div className="flex items-center justify-between mb-2">
                <span className="text-xs font-bold text-gray-400 uppercase tracking-wider">Beban CPU</span>
                <Cpu className="h-4 w-4 text-blue-600" />
              </div>
              <div className="w-full bg-gray-100 h-2 rounded-full overflow-hidden mt-1">
                <div className="bg-blue-600 h-full rounded-full transition-all duration-1000" style={{ width: '24%' }}></div>
              </div>
              <span className="text-[10px] text-gray-400 mt-1.5 block">24% Load (Intel Xeon Core)</span>
            </div>

            <div className="bg-white p-5 rounded-xl border border-gray-100 shadow-xs">
              <div className="flex items-center justify-between mb-2">
                <span className="text-xs font-bold text-gray-400 uppercase tracking-wider">Storage & DB</span>
                <HardDrive className="h-4 w-4 text-purple-600" />
              </div>
              <div className="w-full bg-gray-100 h-2 rounded-full overflow-hidden mt-1">
                <div className="bg-purple-600 h-full rounded-full transition-all" style={{ width: '42%' }}></div>
              </div>
              <span className="text-[10px] text-gray-400 mt-1.5 block">42% Used (JSON DB Persistence)</span>
            </div>

            <div className="bg-white p-5 rounded-xl border border-gray-100 shadow-xs">
              <div className="flex items-center justify-between mb-2">
                <span className="text-xs font-bold text-gray-400 uppercase tracking-wider">Network Ingress</span>
                <Network className="h-4 w-4 text-amber-600" />
              </div>
              <div className="flex items-baseline space-x-1">
                <span className="text-lg font-black text-gray-800">Port 3000</span>
              </div>
              <span className="text-[10px] text-gray-400 mt-1 block">Reverse Proxy: Nginx Route</span>
            </div>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Left side: API Sandbox Tester */}
            <div className="bg-slate-950 p-6 rounded-xl text-slate-100 font-mono shadow-md flex flex-col justify-between border border-slate-850">
              <div className="space-y-4">
                <div className="flex items-center justify-between border-b border-slate-800 pb-3">
                  <div className="flex items-center gap-2">
                    <Terminal className="h-5 w-5 text-emerald-400" />
                    <span className="text-xs font-bold text-white uppercase tracking-wider">Backend API Client Sandbox</span>
                  </div>
                  <span className="text-[10px] text-emerald-400 bg-emerald-950/50 px-2 py-0.5 rounded-md">HTTP CLIENT</span>
                </div>

                <div className="space-y-2 text-xs">
                  <label className="block text-slate-400 font-bold">Select API Endpoint:</label>
                  <div className="flex gap-2">
                    <select
                      value={selectedEndpoint}
                      onChange={(e) => setSelectedEndpoint(e.target.value)}
                      className="flex-grow bg-slate-900 border border-slate-800 text-slate-100 px-3 py-2 rounded-lg text-xs font-mono focus:outline-hidden"
                    >
                      <option value="/api/rooms">GET /api/rooms</option>
                      <option value="/api/properties">GET /api/properties</option>
                      <option value="/api/users">GET /api/users</option>
                      <option value="/api/transactions">GET /api/transactions</option>
                      <option value="/api/logs">GET /api/logs</option>
                      <option value="/api/stats">GET /api/stats</option>
                    </select>
                    <button
                      onClick={handleExecuteApi}
                      disabled={apiTesting}
                      className="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 disabled:bg-slate-800 text-slate-950 font-black rounded-lg text-xs flex items-center gap-1.5 transition-all cursor-pointer"
                    >
                      {apiTesting ? <RefreshCw className="h-3.5 w-3.5 animate-spin" /> : <Play className="h-3.5 w-3.5 fill-slate-950" />}
                      <span>Kirim</span>
                    </button>
                  </div>
                </div>

                <div className="space-y-1.5">
                  <div className="flex items-center justify-between text-[11px] text-slate-400">
                    <span>Response JSON:</span>
                    <button
                      onClick={() => setApiResponse('// Konsol di-reset.')}
                      className="text-slate-500 hover:text-slate-300 transition-colors"
                    >
                      Clear
                    </button>
                  </div>
                  <div className="h-80 overflow-y-auto bg-slate-900 rounded-lg p-3 text-[10px] text-emerald-400 font-mono border border-slate-850 scrollbar-thin scrollbar-thumb-slate-800 scrollbar-track-transparent">
                    <pre className="whitespace-pre-wrap">{apiResponse}</pre>
                  </div>
                </div>
              </div>

              <div className="pt-4 border-t border-slate-850 flex items-center justify-between text-[10px] text-slate-500">
                <span>Method: GET</span>
                <span>Host: https://0.0.0.0:3000</span>
              </div>
            </div>

            {/* Right side: Real-time API Logs list */}
            <div className="bg-white p-6 rounded-xl border border-gray-100 shadow-xs flex flex-col justify-between">
              <div className="space-y-4">
                <div className="flex items-center justify-between border-b border-gray-100 pb-3">
                  <div className="flex items-center gap-2">
                    <Database className="h-5 w-5 text-blue-600 animate-pulse" />
                    <h4 className="font-sans font-bold text-gray-900 text-sm">System Audit Event Log (Real-time)</h4>
                  </div>
                  <div className="flex gap-1.5">
                    <button
                      onClick={handleCreateCustomLog}
                      className="px-2 py-1 bg-gray-50 hover:bg-gray-100 border border-gray-200 text-gray-600 rounded text-[10px] font-bold"
                    >
                      + Tambah Log Audit
                    </button>
                    <button
                      onClick={() => fetchLogs(false)}
                      className="p-1 text-gray-400 hover:text-gray-700"
                    >
                      <RefreshCw className={`h-3.5 w-3.5 ${loadingLogs ? 'animate-spin' : ''}`} />
                    </button>
                  </div>
                </div>

                <div className="space-y-3.5 overflow-y-auto h-[400px] pr-1.5 scrollbar-thin scrollbar-thumb-gray-200 scrollbar-track-transparent">
                  {systemLogs.map((log) => (
                    <div key={log.id} className="p-3 bg-gray-50 rounded-lg border border-gray-100 text-xs flex flex-col space-y-1.5 hover:bg-slate-50 transition-colors">
                      <div className="flex justify-between items-center text-[10px] text-gray-400 font-semibold font-mono">
                        <span className="uppercase">{log.type || 'app'}</span>
                        <span>{log.timestamp}</span>
                      </div>
                      <p className="text-gray-700 leading-snug">{log.message}</p>
                      
                      {/* IP, Device, and Location metadata */}
                      {(log as any).ip && (
                        <div className="flex flex-wrap items-center gap-1.5 mt-1">
                          <span className="text-[9px] text-cyan-600 bg-cyan-50 px-1 py-0.5 rounded font-mono border border-cyan-100 flex items-center gap-0.5">
                            🌐 {(log as any).ip}
                          </span>
                          {(log as any).device && (
                            <span className="text-[9px] text-indigo-600 bg-indigo-50 px-1 py-0.5 rounded border border-indigo-100 flex items-center gap-0.5">
                              💻 {(log as any).device}
                            </span>
                          )}
                          {(log as any).location && (
                            <span className="text-[9px] text-emerald-600 bg-emerald-50 px-1 py-0.5 rounded border border-emerald-100 flex items-center gap-0.5">
                              📍 {(log as any).location}
                            </span>
                          )}
                        </div>
                      )}

                      <div className="text-[9px] text-gray-400 flex items-center justify-between pt-1 border-t border-dashed border-gray-100">
                        <span>User: <strong>@{log.user || 'system'}</strong></span>
                        <span className="font-mono text-[8px]">ID: #{log.id.substring(0, 8)}</span>
                      </div>
                    </div>
                  ))}

                  {systemLogs.length === 0 && (
                    <div className="py-20 text-center text-gray-400 italic text-xs">
                      {loadingLogs ? 'Memuat log sistem...' : 'Belum ada log aktivitas tercatat.'}
                    </div>
                  )}
                </div>
              </div>

              <div className="pt-3 border-t border-gray-100 text-[10px] text-gray-400 text-center font-bold font-mono">
                PERSISTENCE: /database-blueprints.json
              </div>
            </div>
          </div>

          {/* API Keys and Webhooks Integration Settings (Incoming & Outgoing) */}
          <div className="bg-white p-6 rounded-xl border border-gray-100 shadow-xs mt-6 space-y-6">
            <div className="border-b border-gray-100 pb-4 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Globe className="h-5 w-5 text-indigo-600 animate-pulse" />
                <div>
                  <h4 className="font-sans font-bold text-gray-900 text-sm">Pengaturan API & Webhook Terintegrasi</h4>
                  <p className="text-[11px] text-gray-400 font-medium">Hubungkan dan sinkronisasikan aplikasi ini dengan sistem eksternal secara real-time</p>
                </div>
              </div>
              <span className="text-[10px] bg-indigo-50 text-indigo-700 px-2 py-0.5 rounded font-black uppercase tracking-wider border border-indigo-100">FULL-STACK GATEWAY</span>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
              {/* Column 1: API Keys (Incoming) */}
              <div className="space-y-4">
                <div className="flex items-center gap-2 text-xs font-bold text-gray-800 uppercase tracking-wider border-b border-gray-50 pb-2">
                  <Key className="h-4 w-4 text-emerald-600" />
                  <span>Kunci API Masuk (Incoming API Keys)</span>
                </div>
                <p className="text-xs text-gray-500 leading-relaxed">
                  Gunakan Kunci API berikut untuk mengizinkan aplikasi eksternal (seperti Aplikasi Android/iOS atau CRM) mengakses data properti, kamar, dan log sistem secara aman.
                </p>

                <div className="space-y-2 max-h-[220px] overflow-y-auto pr-1">
                  {apiKeys.map((key) => (
                    <div key={key.id} className="p-3 bg-gray-50 rounded-lg border border-gray-100 flex items-center justify-between gap-4">
                      <div className="space-y-1 min-w-0">
                        <div className="flex items-center gap-1.5 flex-wrap">
                          <span className="text-xs font-extrabold text-gray-800 truncate">{key.name}</span>
                          <span className={`text-[9px] px-1.5 py-0.5 rounded border font-semibold ${
                            key.permissions === 'read-only' 
                              ? 'bg-blue-50 text-blue-700 border-blue-100' 
                              : 'bg-emerald-50 text-emerald-700 border-emerald-100'
                          }`}>
                            {key.permissions === 'read-only' ? 'Read-Only' : 'All Perms (R/W)'}
                          </span>
                        </div>
                        <div className="flex items-center gap-1">
                          <code className="text-[10px] text-indigo-600 bg-white px-1.5 py-0.5 rounded border border-gray-100 font-mono truncate">{key.key}</code>
                          <button 
                            type="button"
                            onClick={() => {
                              navigator.clipboard.writeText(key.key);
                              showToast('Kunci API berhasil disalin ke clipboard!', 'success');
                            }}
                            className="p-1 hover:bg-gray-200 rounded text-gray-500 hover:text-gray-700 transition cursor-pointer"
                            title="Salin Kunci API"
                          >
                            <Copy className="h-3 w-3" />
                          </button>
                        </div>
                      </div>

                      <button
                        type="button"
                        onClick={() => handleDeleteApiKey(key.id)}
                        className="p-1.5 hover:bg-red-50 text-gray-400 hover:text-red-600 rounded transition cursor-pointer shrink-0"
                        title="Cabut Kunci API"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  ))}

                  {apiKeys.length === 0 && (
                    <div className="text-center py-8 text-gray-400 text-xs italic">
                      Belum ada Kunci API yang aktif.
                    </div>
                  )}
                </div>

                {/* Generate form */}
                <form onSubmit={handleCreateApiKey} className="bg-slate-50 p-4 rounded-xl border border-gray-100 space-y-3">
                  <span className="text-[10px] font-black text-indigo-700 tracking-wider uppercase block">Buat Kunci API Baru</span>
                  <div className="flex gap-2">
                    <input
                      type="text"
                      placeholder="Nama klien (misal: CRM Hub, Mobile App)"
                      value={newKeyName}
                      onChange={(e) => setNewKeyName(e.target.value)}
                      className="flex-grow bg-white border border-gray-200 text-xs px-3 py-2 rounded-lg text-gray-800 placeholder:text-gray-400 focus:outline-none focus:border-indigo-500 transition-all"
                    />
                    <select
                      value={newKeyPerms}
                      onChange={(e) => setNewKeyPerms(e.target.value)}
                      className="bg-white border border-gray-200 text-xs px-3 py-2 rounded-lg text-gray-800 focus:outline-none focus:border-indigo-500 transition-all font-semibold"
                    >
                      <option value="all">Full (R/W)</option>
                      <option value="read-only">Read-Only</option>
                    </select>
                    <button
                      type="submit"
                      className="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-lg text-xs transition-colors shrink-0 cursor-pointer"
                    >
                      Buat Kunci
                    </button>
                  </div>
                </form>
              </div>

              {/* Column 2: Webhooks (Outgoing) */}
              <div className="space-y-4">
                <div className="flex items-center gap-2 text-xs font-bold text-gray-800 uppercase tracking-wider border-b border-gray-50 pb-2">
                  <Webhook className="h-4 w-4 text-indigo-600" />
                  <span>Webhook Keluar (Outgoing Webhooks)</span>
                </div>
                <p className="text-xs text-gray-500 leading-relaxed">
                  Konfigurasikan target URL webhook eksternal agar sistem kami otomatis mengirimkan payload event JSON saat terjadi check-in, check-out, pembersihan, atau perbaikan unit.
                </p>

                <div className="space-y-2 max-h-[220px] overflow-y-auto pr-1">
                  {webhooks.map((wh) => (
                    <div key={wh.id} className="p-3 bg-gray-50 rounded-lg border border-gray-100 space-y-2">
                      <div className="flex items-start justify-between gap-2">
                        <div className="min-w-0">
                          <div className="flex items-center gap-2 flex-wrap">
                            <span className="text-xs font-extrabold text-gray-800 truncate">{wh.name}</span>
                            <span className={`text-[8px] px-1.5 py-0.2 rounded-full border font-bold uppercase ${
                              wh.status === 'active' 
                                ? 'bg-emerald-50 text-emerald-700 border-emerald-100 animate-pulse' 
                                : 'bg-gray-100 text-gray-500 border-gray-200'
                            }`}>
                              {wh.status === 'active' ? 'Aktif' : 'Non-Aktif'}
                            </span>
                          </div>
                          <p className="text-[10px] text-gray-400 font-mono truncate">{wh.url}</p>
                        </div>

                        <div className="flex items-center gap-1.5 shrink-0">
                          <button
                            type="button"
                            onClick={() => handleTestWebhook(wh.id)}
                            disabled={testingWhId !== null}
                            className="px-2 py-1 bg-white hover:bg-gray-100 border border-gray-200 hover:border-gray-300 text-[10px] text-gray-600 rounded font-bold transition flex items-center gap-1 cursor-pointer disabled:opacity-50"
                          >
                            <Activity className={`h-3 w-3 ${testingWhId === wh.id ? 'animate-spin text-indigo-600' : 'text-gray-500'}`} />
                            <span>{testingWhId === wh.id ? 'Menguji...' : 'Test'}</span>
                          </button>
                          
                          <button
                            type="button"
                            onClick={() => handleToggleWebhook(wh)}
                            className={`p-1.5 rounded text-xs font-black border transition cursor-pointer ${
                              wh.status === 'active'
                                ? 'bg-amber-50 text-amber-600 border-amber-100 hover:bg-amber-100'
                                : 'bg-emerald-50 text-emerald-600 border-emerald-100 hover:bg-emerald-100'
                            }`}
                            title={wh.status === 'active' ? 'Matikan Webhook' : 'Aktifkan Webhook'}
                          >
                            {wh.status === 'active' ? 'Pause' : 'Play'}
                          </button>

                          <button
                            type="button"
                            onClick={() => handleDeleteWebhook(wh.id)}
                            className="p-1.5 hover:bg-red-50 text-gray-400 hover:text-red-600 rounded border border-transparent hover:border-red-100 transition cursor-pointer"
                            title="Hapus Webhook"
                          >
                            <Trash2 className="h-3.5 w-3.5" />
                          </button>
                        </div>
                      </div>

                      {/* Display test output if any */}
                      {whTestResults[wh.id] && (
                        <div className={`text-[9px] p-1.5 rounded border font-mono ${
                          whTestResults[wh.id].success 
                            ? 'bg-emerald-50 text-emerald-700 border-emerald-100' 
                            : 'bg-red-50 text-red-700 border-red-100'
                        }`}>
                          {whTestResults[wh.id].success 
                            ? `✓ Tes Terkirim Sukses! Target merespon dengan status: ${whTestResults[wh.id].status || 200}`
                            : `✗ Tes Gagal: ${whTestResults[wh.id].error || 'Endpoint tidak merespon'}`
                          }
                        </div>
                      )}

                      <div className="flex flex-wrap items-center gap-1">
                        <span className="text-[8px] text-gray-400 font-bold uppercase mr-1">Events:</span>
                        {wh.events.map((ev: string) => (
                          <span key={ev} className="text-[8px] text-indigo-600 bg-indigo-50/50 px-1.5 py-0.2 rounded border border-indigo-100/30 font-mono">
                            {ev}
                          </span>
                        ))}
                      </div>
                    </div>
                  ))}

                  {webhooks.length === 0 && (
                    <div className="text-center py-8 text-gray-400 text-xs italic">
                      Belum ada Webhook keluar terdaftar.
                    </div>
                  )}
                </div>

                {/* Webhook form */}
                <form onSubmit={handleCreateWebhook} className="bg-slate-50 p-4 rounded-xl border border-gray-100 space-y-3">
                  <span className="text-[10px] font-black text-indigo-700 tracking-wider uppercase block">Daftarkan Webhook Baru</span>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
                    <input
                      type="text"
                      placeholder="Nama webhook (misal: Slack Bot)"
                      value={newWhName}
                      onChange={(e) => setNewWhName(e.target.value)}
                      className="bg-white border border-gray-200 text-xs px-3 py-2 rounded-lg text-gray-800 placeholder:text-gray-400 focus:outline-none focus:border-indigo-500 transition-all w-full"
                    />
                    <input
                      type="text"
                      placeholder="URL Target (https://...)"
                      value={newWhUrl}
                      onChange={(e) => setNewWhUrl(e.target.value)}
                      className="bg-white border border-gray-200 text-xs px-3 py-2 rounded-lg text-gray-800 placeholder:text-gray-400 focus:outline-none focus:border-indigo-500 transition-all w-full font-mono"
                    />
                  </div>
                  
                  <div className="flex items-center justify-between gap-4 flex-wrap">
                    <div className="flex flex-wrap gap-x-3 gap-y-1.5 text-[9px] text-gray-600 font-semibold">
                      <label className="flex items-center gap-1 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={newWhEvents.includes('check_in')}
                          onChange={(e) => {
                            if (e.target.checked) setNewWhEvents([...newWhEvents, 'check_in']);
                            else setNewWhEvents(newWhEvents.filter(ev => ev !== 'check_in'));
                          }}
                          className="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500 h-3 w-3"
                        />
                        <span>Check-In</span>
                      </label>
                      <label className="flex items-center gap-1 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={newWhEvents.includes('check_out')}
                          onChange={(e) => {
                            if (e.target.checked) setNewWhEvents([...newWhEvents, 'check_out']);
                            else setNewWhEvents(newWhEvents.filter(ev => ev !== 'check_out'));
                          }}
                          className="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500 h-3 w-3"
                        />
                        <span>Check-Out</span>
                      </label>
                      <label className="flex items-center gap-1 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={newWhEvents.includes('cleaning_started')}
                          onChange={(e) => {
                            if (e.target.checked) setNewWhEvents([...newWhEvents, 'cleaning_started']);
                            else setNewWhEvents(newWhEvents.filter(ev => ev !== 'cleaning_started'));
                          }}
                          className="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500 h-3 w-3"
                        />
                        <span>Mulai Bersih</span>
                      </label>
                      <label className="flex items-center gap-1 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={newWhEvents.includes('cleaning_completed')}
                          onChange={(e) => {
                            if (e.target.checked) setNewWhEvents([...newWhEvents, 'cleaning_completed']);
                            else setNewWhEvents(newWhEvents.filter(ev => ev !== 'cleaning_completed'));
                          }}
                          className="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500 h-3 w-3"
                        />
                        <span>Selesai Bersih</span>
                      </label>
                      <label className="flex items-center gap-1 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={newWhEvents.includes('maintenance_started')}
                          onChange={(e) => {
                            if (e.target.checked) setNewWhEvents([...newWhEvents, 'maintenance_started']);
                            else setNewWhEvents(newWhEvents.filter(ev => ev !== 'maintenance_started'));
                          }}
                          className="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500 h-3 w-3"
                        />
                        <span>Mulai Perbaikan</span>
                      </label>
                      <label className="flex items-center gap-1 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={newWhEvents.includes('maintenance_completed')}
                          onChange={(e) => {
                            if (e.target.checked) setNewWhEvents([...newWhEvents, 'maintenance_completed']);
                            else setNewWhEvents(newWhEvents.filter(ev => ev !== 'maintenance_completed'));
                          }}
                          className="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500 h-3 w-3"
                        />
                        <span>Selesai Perbaikan</span>
                      </label>
                    </div>

                    <button
                      type="submit"
                      className="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-lg text-xs transition-colors shrink-0 cursor-pointer"
                    >
                      Daftarkan Webhook
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* MODAL MODAL FOR ACTIONS */}

      {/* MODAL 1: TAMBAH KAMAR */}
      {showAddRoomModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-xs p-4">
          <div className="bg-white rounded-2xl border border-gray-100 shadow-2xl max-w-lg w-full overflow-hidden animate-in fade-in zoom-in-95 duration-200">
            <div className="bg-gradient-to-r from-blue-700 to-indigo-800 p-5 text-white flex justify-between items-center">
              <h3 className="font-sans font-extrabold text-base flex items-center gap-1.5">
                <PlusCircle className="h-5 w-5 text-blue-300" />
                <span>Pendaftaran Unit Kamar Baru</span>
              </h3>
              <button
                onClick={() => setShowAddRoomModal(false)}
                className="text-white/80 hover:text-white transition-colors"
              >
                <XCircle className="h-5 w-5" />
              </button>
            </div>

            <form onSubmit={handleAddRoomSubmit} className="p-6 space-y-4">
              <div className="grid grid-cols-2 gap-4 text-xs">
                {/* Properti */}
                <div className="col-span-2 space-y-1">
                  <label className="block text-xs font-semibold text-gray-500">Pilih Properti Induk *</label>
                  <select
                    value={newRoomForm.propertyId}
                    onChange={(e) => setNewRoomForm(prev => ({ ...prev, propertyId: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs bg-white focus:outline-hidden"
                    required
                  >
                    {properties.map(p => (
                      <option key={p.id} value={p.id}>{p.name} ({p.type})</option>
                    ))}
                  </select>
                </div>

                {/* Nomor Kamar */}
                <div className="space-y-1">
                  <label className="block text-xs font-semibold text-gray-500">Nomor Kamar/Unit *</label>
                  <input
                    type="text"
                    placeholder="Contoh: 101, Villa-01, 2503"
                    value={newRoomForm.roomNumber}
                    onChange={(e) => setNewRoomForm(prev => ({ ...prev, roomNumber: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs"
                    required
                  />
                </div>

                {/* Tipe Kamar */}
                <div className="space-y-1">
                  <label className="block text-xs font-semibold text-gray-500">Tipe / Kategori Kamar *</label>
                  <input
                    type="text"
                    placeholder="Contoh: Deluxe Double, Executive Suite"
                    value={newRoomForm.type}
                    onChange={(e) => setNewRoomForm(prev => ({ ...prev, type: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs"
                    required
                  />
                </div>

                {/* Harga Harian */}
                <div className="space-y-1">
                  <label className="block text-xs font-semibold text-gray-500">Tarif / Harga Per Hari (IDR) *</label>
                  <input
                    type="number"
                    value={newRoomForm.priceDay}
                    onChange={(e) => setNewRoomForm(prev => ({ ...prev, priceDay: Number(e.target.value) }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs font-mono font-semibold"
                    required
                  />
                </div>

                {/* Posisi */}
                <div className="space-y-1">
                  <label className="block text-xs font-semibold text-gray-500">Posisi Unit</label>
                  <input
                    type="text"
                    placeholder="Contoh: Lantai 2, Sayap Barat"
                    value={newRoomForm.position}
                    onChange={(e) => setNewRoomForm(prev => ({ ...prev, position: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs"
                  />
                </div>

                {/* Hadap */}
                <div className="space-y-1">
                  <label className="block text-xs font-semibold text-gray-500">Hadap Angin</label>
                  <input
                    type="text"
                    placeholder="Contoh: Timur (Sunrise), Selatan"
                    value={newRoomForm.facing}
                    onChange={(e) => setNewRoomForm(prev => ({ ...prev, facing: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs"
                  />
                </div>

                {/* View */}
                <div className="space-y-1">
                  <label className="block text-xs font-semibold text-gray-500">View / Pemandangan</label>
                  <input
                    type="text"
                    placeholder="Contoh: Kolam Renang, City Skyline"
                    value={newRoomForm.view}
                    onChange={(e) => setNewRoomForm(prev => ({ ...prev, view: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs"
                  />
                </div>

                {/* Image URL */}
                <div className="col-span-2 space-y-1">
                  <label className="block text-xs font-semibold text-gray-500">Foto Kamar (URL Unsplash)</label>
                  <input
                    type="url"
                    placeholder="https://images.unsplash.com/..."
                    value={newRoomForm.imageUrl}
                    onChange={(e) => setNewRoomForm(prev => ({ ...prev, imageUrl: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs"
                  />
                </div>

                {/* Facilities */}
                <div className="col-span-2 space-y-1">
                  <label className="block text-xs font-semibold text-gray-500">Fasilitas Kamar (Pisahkan dengan koma)</label>
                  <input
                    type="text"
                    placeholder="Contoh: AC, Smart TV, Wi-Fi, Water Heater"
                    value={newRoomForm.facilitiesString}
                    onChange={(e) => setNewRoomForm(prev => ({ ...prev, facilitiesString: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs"
                  />
                </div>
              </div>

              <div className="pt-4 border-t border-gray-100 flex justify-end gap-2.5">
                <button
                  type="button"
                  onClick={() => setShowAddRoomModal(false)}
                  className="px-4 py-2 bg-gray-50 hover:bg-gray-100 text-gray-600 rounded-xl text-xs font-bold transition-all border border-gray-200"
                >
                  Batal
                </button>
                <button
                  type="submit"
                  className="px-5 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-xl text-xs font-extrabold transition-all"
                >
                  Simpan Kamar
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* MODAL 2: CHECK-IN FAST */}
      {showCheckInModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-xs p-4">
          <div className="bg-white rounded-2xl border border-gray-100 shadow-2xl max-w-md w-full overflow-hidden animate-in fade-in zoom-in-95 duration-200">
            <div className="bg-gradient-to-r from-blue-700 to-indigo-800 p-5 text-white flex justify-between items-center">
              <div>
                <h3 className="font-sans font-extrabold text-base flex items-center gap-1.5">
                  <Calendar className="h-5 w-5 text-blue-300" />
                  <span>Proses Check-In Tamu Cepat</span>
                </h3>
                <p className="text-[10px] text-blue-200">Kamar {showCheckInModal.roomNumber} - {showCheckInModal.type}</p>
              </div>
              <button
                onClick={() => setShowCheckInModal(null)}
                className="text-white/80 hover:text-white transition-colors"
              >
                <XCircle className="h-5 w-5" />
              </button>
            </div>

            <form onSubmit={handleFastCheckIn} className="p-6 space-y-4">
              <div className="space-y-3.5 text-xs">
                {/* Guest Name */}
                <div className="space-y-1">
                  <label className="block text-xs font-semibold text-gray-500">Nama Lengkap Tamu *</label>
                  <input
                    type="text"
                    value={checkInForm.buyerName}
                    onChange={(e) => setCheckInForm(prev => ({ ...prev, buyerName: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs"
                    required
                  />
                </div>

                {/* Phone */}
                <div className="space-y-1">
                  <label className="block text-xs font-semibold text-gray-500">No. WhatsApp Tamu *</label>
                  <input
                    type="text"
                    value={checkInForm.buyerPhone}
                    onChange={(e) => setCheckInForm(prev => ({ ...prev, buyerPhone: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs font-mono"
                    required
                  />
                </div>

                {/* Dates */}
                <div className="grid grid-cols-2 gap-3">
                  <div className="space-y-1">
                    <label className="block text-xs font-semibold text-gray-500">Tanggal Check-In *</label>
                    <input
                      type="date"
                      value={checkInForm.startDate}
                      onChange={(e) => setCheckInForm(prev => ({ ...prev, startDate: e.target.value }))}
                      className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs"
                      required
                    />
                  </div>
                  <div className="space-y-1">
                    <label className="block text-xs font-semibold text-gray-500">Tanggal Check-Out *</label>
                    <input
                      type="date"
                      value={checkInForm.endDate}
                      onChange={(e) => setCheckInForm(prev => ({ ...prev, endDate: e.target.value }))}
                      className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs"
                      required
                    />
                  </div>
                </div>

                {/* Payment Cycle */}
                <div className="space-y-1">
                  <label className="block text-xs font-semibold text-gray-500">Metode Pembayaran *</label>
                  <select
                    value={checkInForm.paymentCycle}
                    onChange={(e) => setCheckInForm(prev => ({ ...prev, paymentCycle: e.target.value as any }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs bg-white"
                  >
                    <option value="lunas">Lunas Seketika (Simulasi)</option>
                    <option value="DP">Uang Muka / Down Payment (DP)</option>
                  </select>
                </div>

                {checkInForm.paymentCycle === 'DP' && (
                  <div className="space-y-1">
                    <label className="block text-xs font-semibold text-gray-500">Jumlah DP yang Dibayarkan (IDR) *</label>
                    <input
                      type="number"
                      value={checkInForm.amountPaid}
                      onChange={(e) => setCheckInForm(prev => ({ ...prev, amountPaid: Number(e.target.value) }))}
                      className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs font-mono font-bold text-blue-600"
                      required
                    />
                  </div>
                )}

                {/* Notes */}
                <div className="space-y-1">
                  <label className="block text-xs font-semibold text-gray-500">Catatan Pemesanan</label>
                  <textarea
                    value={checkInForm.notes}
                    onChange={(e) => setCheckInForm(prev => ({ ...prev, notes: e.target.value }))}
                    rows={2}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs resize-none"
                  />
                </div>
              </div>

              <div className="pt-4 border-t border-gray-100 flex justify-end gap-2.5">
                <button
                  type="button"
                  onClick={() => setShowCheckInModal(null)}
                  className="px-4 py-2 bg-gray-50 hover:bg-gray-100 text-gray-600 rounded-xl text-xs font-bold transition-all border border-gray-200"
                >
                  Batal
                </button>
                <button
                  type="submit"
                  className="px-5 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-xl text-xs font-extrabold transition-all"
                >
                  Proses Check-In
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
