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

import React, { useState } from 'react';
import { 
  X, CalendarDays, Key, Coins, MapPin, Sparkles, ShieldCheck, 
  User, Phone, Mail, MessageSquare, Map, Eye, Compass, Layers, 
  Wifi, CheckCircle, AlertTriangle, BedDouble, Home, Calendar,
  ChevronDown, ChevronUp, SlidersHorizontal, Info
} from 'lucide-react';
import { Property, User as UserType, Room } from '../types';

interface PropertyDetailsModalProps {
  property: Property;
  currentUser: UserType | null;
  onClose: () => void;
  onAction: (transactionData: {
    propertyId: string;
    type: 'stay' | 'rent' | 'buy';
    startDate?: string;
    endDate?: string;
    totalPrice: number;
    couponCode?: string;
    paymentMethod?: string;
    reservationTime?: string;
    confirmationNotes?: string;
    paymentCycle?: 'DP' | 'lunas';
    amountPaid?: number;
    roomId?: string;
    roomNumber?: string;
  }) => void;
  onOpenAuth: () => void;
  promos?: any[];
  rooms?: Room[];
}

export default function PropertyDetailsModal({
  property,
  currentUser,
  onClose,
  onAction,
  onOpenAuth,
  promos = [],
  rooms = []
}: PropertyDetailsModalProps) {
  // Get filtered rooms for this property
  const propertyRooms = rooms.filter((r) => r.propertyId === property.id);
  const roomsWithPriceDay = propertyRooms.filter((r) => r.priceDay);
  const effectivePriceDay = property.priceDay || 
    (roomsWithPriceDay.length > 0 ? Math.min(...roomsWithPriceDay.map(r => r.priceDay)) : 
      (property.priceMonth ? Math.round(property.priceMonth / 30) : 0));

  const [selectedTab, setSelectedTab] = useState<'stay' | 'rent' | 'buy'>(
    effectivePriceDay ? 'stay' : property.priceMonth ? 'rent' : 'buy'
  );
  const [activeLeftTab, setActiveLeftTab] = useState<'info' | 'map'>('info');

  const [selectedRoomId, setSelectedRoomId] = useState<string>(
    propertyRooms.length > 0 ? propertyRooms[0].id : ''
  );
  const selectedRoom = propertyRooms.find((r) => r.id === selectedRoomId);

  // Clear error on tab change
  React.useEffect(() => {
    setError(null);
  }, [selectedTab]);

  // States for booking
  const [stayStart, setStayStart] = useState('');
  const [stayEnd, setStayEnd] = useState('');
  const [rentDuration, setRentDuration] = useState(1);
  const [error, setError] = useState<string | null>(null);

  // Advanced Operations states
  const [couponCode, setCouponCode] = useState('');
  const [appliedDiscount, setAppliedDiscount] = useState(0);
  const [couponStatus, setCouponStatus] = useState<'none' | 'applied' | 'invalid'>('none');
  const [paymentMethod, setPaymentMethod] = useState('Bank Transfer - Mandiri');
  const [paymentCycle, setPaymentCycle] = useState<'lunas' | 'DP'>('lunas');
  const [amountPaid, setAmountPaid] = useState('500000');
  const [reservationTime, setReservationTime] = useState('');
  const [confirmationNotes, setConfirmationNotes] = useState('');

  // Handle coupon validation client-side
  const handleApplyCoupon = () => {
    const code = couponCode.trim().toUpperCase();
    if (!code) {
      setAppliedDiscount(0);
      setCouponStatus('none');
      return;
    }

    // Check custom database promos first
    const matchedPromo = promos.find((p: any) => p.code.toUpperCase() === code);
    if (matchedPromo) {
      if (matchedPromo.used >= matchedPromo.maxUse) {
        setAppliedDiscount(0);
        setCouponStatus('invalid');
        return;
      }
      setAppliedDiscount(matchedPromo.discount);
      setCouponStatus('applied');
    } else if (code === 'HEMAT50') {
      setAppliedDiscount(50000);
      setCouponStatus('applied');
    } else if (code === 'WEEKENDSERU') {
      setAppliedDiscount(100000);
      setCouponStatus('applied');
    } else {
      setAppliedDiscount(0);
      setCouponStatus('invalid');
    }
  };

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

  // Calculation for stay duration
  const getStayDays = () => {
    if (!stayStart || !stayEnd) return 0;
    const start = new Date(stayStart);
    const end = new Date(stayEnd);
    const diff = end.getTime() - start.getTime();
    if (diff <= 0) return 0;
    return Math.ceil(diff / (1000 * 3600 * 24));
  };

  const calculateStayTotal = () => {
    const days = getStayDays();
    const rate = selectedRoom ? selectedRoom.priceDay : effectivePriceDay;
    return days * rate;
  };

  const calculateRentTotal = () => {
    return rentDuration * (property.priceMonth || 0);
  };

  const handleBooking = (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    if (currentUser && currentUser.role !== 'superadmin' && !currentUser.permissions.includes('order_transaction')) {
      setError('Akses Ditolak: Peran Anda tidak memiliki izin "order_transaction" untuk melakukan transaksi!');
      return;
    }

    const basePrice = selectedTab === 'stay' 
      ? calculateStayTotal() 
      : selectedTab === 'rent' 
        ? calculateRentTotal() 
        : (property.priceBuy || 0);

    const commonParams = {
      propertyId: property.id,
      couponCode: couponStatus === 'applied' ? couponCode : undefined,
      paymentMethod,
      reservationTime: reservationTime || stayStart || new Date().toISOString().replace('T', ' ').substring(0, 16),
      confirmationNotes: confirmationNotes || undefined,
      paymentCycle,
      amountPaid: paymentCycle === 'DP' ? Number(amountPaid) : undefined,
      roomId: selectedRoomId || undefined,
      roomNumber: selectedRoom ? selectedRoom.roomNumber : undefined
    };

    if (selectedTab === 'stay') {
      const days = getStayDays();
      if (days <= 0) {
        setError('Tanggal menginap harus valid dan minimal 1 malam!');
        return;
      }
      onAction({
        ...commonParams,
        type: 'stay',
        startDate: stayStart,
        endDate: stayEnd,
        totalPrice: basePrice,
      });
    } else if (selectedTab === 'rent') {
      const today = new Date().toISOString().split('T')[0];
      const endDate = new Date();
      endDate.setMonth(endDate.getMonth() + rentDuration);
      onAction({
        ...commonParams,
        type: 'rent',
        startDate: today,
        endDate: endDate.toISOString().split('T')[0],
        totalPrice: basePrice,
      });
    } else if (selectedTab === 'buy') {
      onAction({
        ...commonParams,
        type: 'buy',
        totalPrice: basePrice,
      });
    }
  };

  const currentBasePrice = selectedTab === 'stay' 
    ? calculateStayTotal() 
    : selectedTab === 'rent' 
      ? calculateRentTotal() 
      : (property.priceBuy || 0);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-xs overflow-y-auto">
      <form onSubmit={handleBooking} className="bg-white rounded-2xl w-full max-w-4xl max-h-[90vh] overflow-y-auto shadow-2xl border border-gray-100 flex flex-col md:flex-row relative">
        {/* Close button */}
        <button
          type="button"
          onClick={onClose}
          className="absolute top-4 right-4 z-10 bg-black/50 hover:bg-black/70 text-white p-1.5 rounded-full transition-colors cursor-pointer"
        >
          <X className="h-5 w-5" />
        </button>

        {/* Column 1: Media & Details */}
        <div className="w-full md:w-1/2 p-5 flex flex-col border-b md:border-b-0 md:border-r border-gray-100 bg-slate-50/50">
          <div className="relative aspect-video rounded-2xl overflow-hidden bg-gray-150 shadow-xs mb-3">
            <img
              src={property.imageUrl}
              alt={property.name}
              className="w-full h-full object-cover"
              referrerPolicy="no-referrer"
            />
            <span className="absolute top-3 left-3 bg-white/95 backdrop-blur-md text-blue-700 text-[10px] font-extrabold uppercase tracking-widest px-2.5 py-1 rounded-full shadow-xs">
              {property.type}
            </span>
          </div>

          <div className="px-1">
            <h2 className="font-sans font-extrabold text-xl text-gray-950 mt-1 leading-snug">
              {property.name}
            </h2>

            <div className="flex items-start text-gray-500 text-xs mt-2">
              <MapPin className="h-3.5 w-3.5 mr-1 text-gray-400 shrink-0 mt-0.5" />
              <span className="line-clamp-2 leading-relaxed">{property.address}</span>
            </div>

            {/* Modern Left Sub-Tabs */}
            <div className="flex bg-slate-200/60 p-1 rounded-xl mt-4 space-x-1 border border-slate-200/40">
              <button
                type="button"
                onClick={() => setActiveLeftTab('info')}
                className={`flex-1 py-2 text-xs font-bold rounded-lg transition-all flex items-center justify-center gap-1.5 cursor-pointer ${
                  activeLeftTab === 'info'
                    ? 'bg-white text-blue-700 shadow-sm ring-1 ring-black/5'
                    : 'text-gray-500 hover:text-gray-800'
                }`}
              >
                <Info className="h-3.5 w-3.5" />
                <span>Detail & Legalitas</span>
              </button>
              <button
                type="button"
                onClick={() => setActiveLeftTab('map')}
                className={`flex-1 py-2 text-xs font-bold rounded-lg transition-all flex items-center justify-center gap-1.5 cursor-pointer ${
                  activeLeftTab === 'map'
                    ? 'bg-white text-blue-700 shadow-sm ring-1 ring-black/5'
                    : 'text-gray-500 hover:text-gray-800'
                }`}
              >
                <Map className="h-3.5 w-3.5" />
                <span>Kontak & Peta</span>
              </button>
            </div>

            {/* Sub-Tab Content with Stable height for elegance */}
            <div className="mt-4 min-h-[200px] flex flex-col justify-between">
              {activeLeftTab === 'info' ? (
                <div className="space-y-3.5">
                  <div>
                    <h4 className="text-[10px] font-bold text-gray-400 uppercase tracking-wider">
                      Deskripsi Properti
                    </h4>
                    <p className="text-gray-600 text-xs mt-1.5 leading-relaxed max-h-[100px] overflow-y-auto pr-1">
                      {property.description}
                    </p>
                  </div>

                  {/* Verification elements */}
                  <div className="p-3 bg-gradient-to-br from-blue-50/60 to-indigo-50/40 border border-blue-100/50 rounded-xl flex items-start space-x-2.5 shadow-2xs">
                    <ShieldCheck className="h-4.5 w-4.5 text-blue-600 shrink-0 mt-0.5" />
                    <div>
                      <p className="text-[11px] font-bold text-blue-950">Legalitas & Keamanan Terjamin</p>
                      <p className="text-[10px] text-gray-500 mt-0.5 leading-relaxed">
                        Properti ini telah diverifikasi keabsahan dokumen hukumnya (SHM/Sertifikat Resmi) oleh tim internal.
                      </p>
                    </div>
                  </div>
                </div>
              ) : (
                <div className="space-y-3">
                  <div>
                    <h4 className="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-2">
                      Hubungi Agen & Pengelola Resmi
                    </h4>
                    
                    {/* Contacts Grid */}
                    <div className="grid grid-cols-2 gap-2">
                      <a
                        href={`tel:${property.contactPhone || '081299998888'}`}
                        className="flex items-center space-x-2 p-2 bg-white hover:bg-blue-50/40 rounded-xl border border-gray-150 hover:border-blue-200 transition-all text-left group"
                      >
                        <div className="p-1.5 bg-blue-50 text-blue-600 rounded-lg group-hover:bg-blue-100 transition-colors shrink-0">
                          <Phone className="h-3.5 w-3.5" />
                        </div>
                        <div className="overflow-hidden">
                          <p className="text-[8px] font-extrabold text-gray-400 uppercase">Telepon</p>
                          <p className="text-[10px] font-bold text-gray-850 truncate">{property.contactPhone || '0812-9999-8888'}</p>
                        </div>
                      </a>

                      <a
                        href={`https://wa.me/62${(property.contactPhone || '081299998888').replace(/[^0-9]/g, '').replace(/^0/, '')}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex items-center space-x-2 p-2 bg-white hover:bg-emerald-50/40 rounded-xl border border-gray-150 hover:border-emerald-200 transition-all text-left group"
                      >
                        <div className="p-1.5 bg-emerald-50 text-emerald-600 rounded-lg group-hover:bg-emerald-100 transition-colors shrink-0">
                          <MessageSquare className="h-3.5 w-3.5" />
                        </div>
                        <div>
                          <p className="text-[8px] font-extrabold text-gray-400 uppercase">WhatsApp</p>
                          <p className="text-[10px] font-bold text-gray-850">Hubungi Host</p>
                        </div>
                      </a>
                    </div>

                    {property.contactEmail && (
                      <a
                        href={`mailto:${property.contactEmail}`}
                        className="flex items-center space-x-2 p-2 bg-white hover:bg-purple-50/40 rounded-xl border border-gray-150 hover:border-purple-200 transition-all text-left group mt-1.5 w-full"
                      >
                        <div className="p-1.5 bg-purple-50 text-purple-600 rounded-lg group-hover:bg-purple-100 transition-colors shrink-0">
                          <Mail className="h-3.5 w-3.5" />
                        </div>
                        <div className="overflow-hidden">
                          <p className="text-[8px] font-extrabold text-gray-400 uppercase">Email Resmi</p>
                          <p className="text-[10px] font-bold text-gray-850 truncate">{property.contactEmail}</p>
                        </div>
                      </a>
                    )}
                  </div>

                  {/* Embedded Map (Highly Compact) */}
                  <div className="rounded-xl overflow-hidden border border-gray-150 bg-gray-100 relative h-24 shadow-2xs group">
                    <iframe
                      title={`Peta Lokasi ${property.name}`}
                      src={property.mapEmbedUrl || `https://maps.google.com/maps?q=${encodeURIComponent(property.address)}&t=&z=15&ie=UTF8&iwloc=&output=embed`}
                      width="100%"
                      height="100%"
                      style={{ border: 0 }}
                      allowFullScreen={false}
                      loading="lazy"
                      referrerPolicy="no-referrer-when-downgrade"
                      className="w-full h-full relative z-10"
                    />
                    <div className="absolute inset-0 flex items-center justify-center bg-gray-50 text-gray-400 text-[10px] gap-1 z-0">
                      <Map className="h-3.5 w-3.5 animate-pulse text-blue-500" />
                      <span>Memuat Peta...</span>
                    </div>
                  </div>
                </div>
              )}
            </div>

            {/* --- TRANSPARANSI & PENJELASAN SKEMA TARIF --- */}
            <div className="mt-4 p-3 bg-blue-50/40 rounded-xl border border-blue-100/50 space-y-1.5 shadow-2xs">
              <span className="text-[10px] font-bold text-blue-900 uppercase tracking-wider flex items-center gap-1">
                <Info className="h-3 w-3 text-blue-500 shrink-0" />
                Skema & Transparansi Tarif
              </span>
              <p className="text-[10px] text-gray-600 leading-relaxed">
                ℹ️ <strong>Keterangan Harga:</strong> Harga yang tertera di halaman depan (thumbnail) adalah tarif <strong>{property.priceMonth ? 'Sewa Bulanan (kontrak jangka panjang)' : 'Menginap Harian'}</strong>. 
                {property.priceMonth && (
                  <span>
                    {" "}Tarif sewa harian (Menginap) dihitung per malam ({formatRupiah(effectivePriceDay)}/hari) untuk fleksibilitas tinggi, sedangkan tarif bulanan ({formatRupiah(property.priceMonth)}/bulan) memberikan penghematan maksimal hingga 40% jika Anda tinggal dalam waktu lama.
                  </span>
                )}
              </p>
            </div>

            {/* --- ADVANCED OPERATIONS (Moved to Left Column to utilize space elegantly) --- */}
            {property.status === 'available' && (
              <div className="mt-5 pt-4 border-t border-slate-200 space-y-3">
                <div className="flex items-center gap-1.5 text-xs font-bold text-gray-800">
                  <SlidersHorizontal className="h-3.5 w-3.5 text-blue-600 animate-pulse" />
                  <span>Metode Pembayaran, Kupon, & Janji Temu</span>
                </div>

                <div className="grid grid-cols-2 gap-2.5">
                  <div>
                    <label className="block text-[10px] font-semibold text-gray-500 mb-1">Metode Pembayaran</label>
                    <select
                      value={paymentMethod}
                      onChange={(e) => setPaymentMethod(e.target.value)}
                      className="w-full p-2 border border-gray-200 rounded-xl text-xs bg-white focus:outline-hidden focus:ring-1 focus:ring-blue-500"
                    >
                      <option value="Bank Transfer - Mandiri">Mandiri Virtual Account</option>
                      <option value="Bank Transfer - BCA">BCA Virtual Account</option>
                      <option value="Credit Card">Kartu Kredit (Visa/Mastercard)</option>
                      <option value="E-Wallet (OVO/Gopay)">E-Wallet (OVO / Gopay)</option>
                      <option value="Tunai / Cash">Tunai / Cash di Kasir</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-[10px] font-semibold text-gray-500 mb-1">Skema Siklus Bayar</label>
                    <select
                      value={paymentCycle}
                      onChange={(e) => setPaymentCycle(e.target.value as 'lunas' | 'DP')}
                      className="w-full p-2 border border-gray-200 rounded-xl text-xs bg-white focus:outline-hidden focus:ring-1 focus:ring-blue-500"
                    >
                      <option value="lunas">Lunas (Full Payment)</option>
                      {selectedTab !== 'buy' && <option value="DP">Uang Muka (DP)</option>}
                    </select>
                  </div>
                </div>

                {/* DP Amount Input */}
                {paymentCycle === 'DP' && selectedTab !== 'buy' && (
                  <div className="p-2.5 bg-amber-50 rounded-xl border border-amber-100 space-y-1 animate-fade-in duration-200">
                    <label className="block text-[10px] font-bold text-amber-950">Nominal Uang Muka / DP (Rp)</label>
                    <input
                      type="number"
                      value={amountPaid}
                      onChange={(e) => setAmountPaid(e.target.value)}
                      placeholder="500000"
                      className="w-full p-2 border border-amber-200 rounded-lg text-xs bg-white focus:outline-hidden"
                    />
                    <span className="text-[9px] text-amber-700 block">Sisa tagihan otomatis ditangguhkan ke Laporan Tagihan.</span>
                  </div>
                )}

                {/* Janji Temu / Waktu Reservasi */}
                <div>
                  <label className="block text-[10px] font-semibold text-gray-500 mb-1">
                    {selectedTab === 'buy' ? 'Rencana Kunjungan / Survey Lokasi' : 'Waktu Janji / Jadwal Check-In'}
                  </label>
                  <input
                    type="datetime-local"
                    value={reservationTime}
                    onChange={(e) => setReservationTime(e.target.value)}
                    className="w-full p-2 border border-gray-200 rounded-xl text-xs bg-white focus:outline-hidden"
                    required={selectedTab === 'buy'}
                  />
                </div>

                {/* Promo & Kupon */}
                <div>
                  <label className="block text-[10px] font-semibold text-gray-500 mb-1">Kupon / Promo Code</label>
                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={couponCode}
                      onChange={(e) => {
                        setCouponCode(e.target.value);
                        setCouponStatus('none');
                        setAppliedDiscount(0);
                      }}
                      placeholder="Contoh: HEMAT50, WEEKENDSERU"
                      className="flex-1 p-2 border border-gray-200 rounded-xl text-xs uppercase bg-white focus:outline-hidden"
                    />
                    <button
                      type="button"
                      onClick={handleApplyCoupon}
                      className="px-3 py-1.5 bg-gray-800 hover:bg-black text-white rounded-xl text-xs font-bold transition-all cursor-pointer"
                    >
                      Gunakan
                    </button>
                  </div>
                  
                  {couponStatus === 'applied' && (
                    <p className="text-[10px] text-emerald-600 font-bold mt-1">
                      ✓ Berhasil! Potongan {formatRupiah(appliedDiscount)} telah dipasang.
                    </p>
                  )}
                  {couponStatus === 'invalid' && (
                    <p className="text-[10px] text-red-500 font-semibold mt-1">
                      ⚠ Kupon tidak valid. Coba gunakan: HEMAT50 atau WEEKENDSERU
                    </p>
                  )}
                </div>

                {/* Keterangan Konfirmasi */}
                <div>
                  <label className="block text-[10px] font-semibold text-gray-500 mb-1">Catatan Tambahan / Bukti Bayar</label>
                  <textarea
                    value={confirmationNotes}
                    onChange={(e) => setConfirmationNotes(e.target.value)}
                    placeholder="Contoh: Transfer atas nama, nomor rekening, atau pesan..."
                    rows={1}
                    className="w-full p-2 border border-gray-200 rounded-xl text-xs bg-white focus:outline-hidden resize-none"
                  />
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Column 2: Booking Form */}
        <div className="w-full md:w-1/2 p-5 flex flex-col justify-between">
          <div>
            <span className="text-xs font-semibold text-gray-400 uppercase tracking-widest">
              Opsi Transaksi Properti
            </span>
            <h3 className="text-lg font-bold text-gray-900 mt-1">
              {property.status === 'available' ? 'Lakukan Pemesanan' : 'Detail Kepemilikan'}
            </h3>

            {property.status === 'available' ? (
              <>
                {/* Modern Segmented Control / Card Tabs */}
                <div className={`grid gap-2 p-1.5 bg-slate-100 rounded-2xl mt-4 ${
                  [effectivePriceDay, property.priceMonth, property.priceBuy].filter(Boolean).length === 3 
                    ? 'grid-cols-3' 
                    : [effectivePriceDay, property.priceMonth, property.priceBuy].filter(Boolean).length === 2 
                      ? 'grid-cols-2' 
                      : 'grid-cols-1'
                }`}>
                  {effectivePriceDay && (
                    <button
                      type="button"
                      onClick={() => setSelectedTab('stay')}
                      className={`flex flex-col sm:flex-row items-center justify-center gap-1.5 py-2.5 px-3 rounded-xl text-xs font-bold transition-all duration-200 cursor-pointer ${
                        selectedTab === 'stay'
                          ? 'bg-white text-blue-600 shadow-sm ring-1 ring-black/5'
                          : 'text-gray-500 hover:text-gray-800 hover:bg-white/40'
                      }`}
                    >
                      <CalendarDays className={`h-4 w-4 ${selectedTab === 'stay' ? 'text-blue-600' : 'text-gray-400'}`} />
                      <span>Menginap</span>
                    </button>
                  )}
                  {property.priceMonth && (
                    <button
                      type="button"
                      onClick={() => setSelectedTab('rent')}
                      className={`flex flex-col sm:flex-row items-center justify-center gap-1.5 py-2.5 px-3 rounded-xl text-xs font-bold transition-all duration-200 cursor-pointer ${
                        selectedTab === 'rent'
                          ? 'bg-white text-blue-600 shadow-sm ring-1 ring-black/5'
                          : 'text-gray-500 hover:text-gray-800 hover:bg-white/40'
                      }`}
                    >
                      <Key className={`h-4 w-4 ${selectedTab === 'rent' ? 'text-blue-600' : 'text-gray-400'}`} />
                      <span>Sewa</span>
                    </button>
                  )}
                  {property.priceBuy && (
                    <button
                      type="button"
                      onClick={() => setSelectedTab('buy')}
                      className={`flex flex-col sm:flex-row items-center justify-center gap-1.5 py-2.5 px-3 rounded-xl text-xs font-bold transition-all duration-200 cursor-pointer ${
                        selectedTab === 'buy'
                          ? 'bg-white text-blue-600 shadow-sm ring-1 ring-black/5'
                          : 'text-gray-500 hover:text-gray-800 hover:bg-white/40'
                      }`}
                    >
                      <Coins className={`h-4 w-4 ${selectedTab === 'buy' ? 'text-blue-600' : 'text-gray-400'}`} />
                      <span>Beli</span>
                    </button>
                  )}
                </div>

                {/* PILIH UNIT / KAMAR */}
                {propertyRooms.length > 0 && (
                  <div className="mt-5 space-y-2.5">
                    <div className="flex items-center justify-between">
                      <span className="text-xs font-bold text-gray-700 uppercase tracking-wider flex items-center gap-1.5">
                        <BedDouble className="h-3.5 w-3.5 text-blue-600" />
                        Pilih Kamar / Unit Ruangan ({propertyRooms.length})
                      </span>
                      <span className="text-[10px] text-gray-400 font-mono bg-gray-100 px-2 py-0.5 rounded-full">
                        Semua Unit Terlihat
                      </span>
                    </div>

                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 max-h-[190px] overflow-y-auto pr-1">
                      {propertyRooms.map((room) => {
                        const isSelected = selectedRoomId === room.id;
                        const isOccupied = room.status === 'occupied';

                        return (
                          <div
                            key={room.id}
                            onClick={() => setSelectedRoomId(room.id)}
                            className={`w-full rounded-2xl border p-3 cursor-pointer transition-all duration-200 ${
                              isSelected
                                ? 'border-blue-600 bg-blue-50/20 shadow-sm ring-1 ring-blue-600/10'
                                : 'border-gray-150 hover:border-gray-300 hover:shadow-xs bg-white'
                            }`}
                          >
                            {/* Room Image & Status Badge */}
                            <div className="relative h-24 w-full rounded-xl overflow-hidden bg-gray-50 mb-2 shadow-inner">
                              {room.imageUrl ? (
                                <img
                                  src={room.imageUrl}
                                  alt={room.roomNumber}
                                  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">
                                  <Home className="h-8 w-8 text-gray-400" />
                                </div>
                              )}
                              <span
                                className={`absolute top-2 right-2 px-2 py-0.5 rounded-full text-[9px] font-bold shadow-xs ${
                                  isOccupied
                                    ? 'bg-rose-500 text-white'
                                    : 'bg-emerald-500 text-white animate-pulse'
                                }`}
                              >
                                {isOccupied ? 'Terisi' : 'Tersedia'}
                              </span>
                            </div>

                            {/* Room Number & Type */}
                            <div className="flex items-start justify-between">
                              <div className="overflow-hidden">
                                <h4 className="text-xs font-extrabold text-gray-900 flex items-center gap-1">
                                  <span className={`w-1.5 h-1.5 rounded-full ${isSelected ? 'bg-blue-600' : 'bg-gray-400'}`}></span>
                                  Unit {room.roomNumber}
                                </h4>
                                <p className="text-[10px] text-gray-500 truncate max-w-[130px]" title={room.type}>
                                  {room.type}
                                </p>
                              </div>
                              <span className="text-xs font-mono font-bold text-blue-700 bg-blue-50 px-1.5 py-0.5 rounded-md">
                                {formatRupiah(room.priceDay)}
                              </span>
                            </div>

                            {/* Position, Facing & View Info */}
                            <div className="mt-2 pt-2 border-t border-gray-100 grid grid-cols-2 gap-1 text-[9px] text-gray-500">
                              <div className="flex items-center gap-1">
                                <Layers className="h-2.5 w-2.5 text-gray-400 shrink-0" />
                                <span className="truncate" title={room.position}>{room.position || "Lantai utama"}</span>
                              </div>
                              <div className="flex items-center gap-1">
                                <Compass className="h-2.5 w-2.5 text-gray-400 shrink-0" />
                                <span className="truncate" title={room.facing}>Hadap: {room.facing || "Utara"}</span>
                              </div>
                              <div className="flex items-center gap-1 col-span-2">
                                <Eye className="h-2.5 w-2.5 text-gray-400 shrink-0" />
                                <span className="truncate" title={room.view}>View: {room.view || "Pemandangan luar"}</span>
                              </div>
                            </div>

                            {/* Room Amenities Icons */}
                            {room.facilities && room.facilities.length > 0 && (
                              <div className="mt-2 flex flex-wrap gap-1">
                                {room.facilities.slice(0, 3).map((fac, idx) => (
                                  <span
                                    key={idx}
                                    className="px-1 py-0.5 rounded bg-gray-50 border border-gray-100 text-[8px] text-gray-600 font-medium"
                                  >
                                    {fac}
                                  </span>
                                ))}
                                {room.facilities.length > 3 && (
                                  <span className="px-1 py-0.5 rounded bg-gray-50 text-[8px] text-gray-400 font-medium">
                                    +{room.facilities.length - 3}
                                  </span>
                                )}
                              </div>
                            )}
                          </div>
                        );
                      })}
                    </div>

                    {/* Booked Dates / Waktu Terisi Warning */}
                    {selectedRoom && selectedRoom.status === 'occupied' && (
                      <div className="p-3 bg-rose-50 border border-rose-100 rounded-xl text-xs text-rose-800 flex items-start space-x-2">
                        <AlertTriangle className="h-4 w-4 text-rose-600 shrink-0 mt-0.5" />
                        <div>
                          <p className="font-bold">Unit {selectedRoom.roomNumber} Sedang Terisi</p>
                          <p className="text-[10px] text-rose-600 mt-0.5">
                            Kamar ini telah dibooking untuk masa sewa berikut:
                          </p>
                          <ul className="list-disc list-inside font-mono text-[9px] mt-1 space-y-0.5">
                            {selectedRoom.bookedDates && selectedRoom.bookedDates.length > 0 ? (
                              selectedRoom.bookedDates.map((dateStr, idx) => (
                                <li key={idx} className="font-bold">{dateStr}</li>
                              ))
                            ) : (
                              <li className="italic">Tanggal Terisi: 25 Juni s/d 30 Juni 2026</li>
                            )}
                          </ul>
                          <p className="text-[10px] text-rose-600 mt-1.5">
                            Silakan ganti tanggal pemesanan Anda atau pilih unit kamar lain yang kosong di atas.
                          </p>
                        </div>
                      </div>
                    )}
                  </div>
                )}

                {/* Form based on Tab */}
                <div className="mt-5 space-y-4">
                  {selectedTab === 'stay' && (
                    <div className="space-y-3">
                      <div className="p-3 bg-gradient-to-r from-blue-50 to-indigo-50/50 border border-blue-100/60 rounded-xl text-xs flex justify-between items-center shadow-xs">
                        <span className="text-blue-900 font-medium flex items-center gap-1">
                          <Sparkles className="h-3.5 w-3.5 text-blue-500 animate-pulse animate-duration-1000" />
                          Harga Sewa Harian {selectedRoom ? `(Unit ${selectedRoom.roomNumber})` : '(Default Properti)'}:
                        </span>
                        <span className="font-extrabold text-blue-700 text-sm">
                          {formatRupiah(selectedRoom ? selectedRoom.priceDay : effectivePriceDay)} / hari
                        </span>
                      </div>

                      {/* Price Equality Explanation Block */}
                      {selectedRoom ? (
                        selectedRoom.priceDay !== effectivePriceDay ? (
                          <div className="p-2.5 bg-amber-50/70 border border-amber-100 rounded-xl text-[10px] text-amber-850 flex items-start gap-1.5 leading-relaxed shadow-3xs">
                            <Info className="h-3.5 w-3.5 text-amber-500 shrink-0 mt-0.5" />
                            <div>
                              <span className="font-bold block mb-0.5">Penyesuaian Tarif Unit Premium</span>
                              <span>Harga Unit {selectedRoom.roomNumber} ({formatRupiah(selectedRoom.priceDay)}/hari) berbeda dari tarif dasar standar properti ({formatRupiah(effectivePriceDay)}/hari) karena merupakan tipe kamar <strong>{selectedRoom.type}</strong> yang hadap <strong>{selectedRoom.facing || 'Luar'}</strong> dengan pemandangan <strong>{selectedRoom.view || 'Indah'}</strong> serta fasilitas eksklusif.</span>
                            </div>
                          </div>
                        ) : (
                          <div className="p-2.5 bg-emerald-50/60 border border-emerald-100 rounded-xl text-[10px] text-emerald-800 flex items-center gap-1.5 shadow-3xs">
                            <CheckCircle className="h-3.5 w-3.5 text-emerald-500 shrink-0" />
                            <span>Tarif Unit {selectedRoom.roomNumber} sama dengan tarif standar dasar properti ({formatRupiah(effectivePriceDay)}/hari).</span>
                          </div>
                        )
                      ) : null}
                      <div className="grid grid-cols-2 gap-3">
                        <div>
                          <label className="block text-xs font-semibold text-gray-600 mb-1">Check-in</label>
                          <input
                            type="date"
                            required
                            min={new Date().toISOString().split('T')[0]}
                            value={stayStart}
                            onChange={(e) => setStayStart(e.target.value)}
                            className="w-full p-2.5 border border-gray-200 rounded-lg text-sm bg-white focus:outline-hidden focus:border-blue-500"
                          />
                        </div>
                        <div>
                          <label className="block text-xs font-semibold text-gray-600 mb-1">Check-out</label>
                          <input
                            type="date"
                            required
                            min={stayStart || new Date().toISOString().split('T')[0]}
                            value={stayEnd}
                            onChange={(e) => setStayEnd(e.target.value)}
                            className="w-full p-2.5 border border-gray-200 rounded-lg text-sm bg-white focus:outline-hidden focus:border-blue-500"
                          />
                        </div>
                      </div>

                      {stayStart && stayEnd && getStayDays() > 0 && (
                        <div className="bg-gradient-to-br from-blue-50 to-indigo-50/50 border border-blue-100 p-4 rounded-xl flex justify-between items-center text-sm shadow-xs">
                          <div>
                            <p className="font-bold text-blue-900">Total {getStayDays()} Malam</p>
                            <p className="text-xs text-blue-600">Simulasi konfirmasi instan</p>
                          </div>
                          <span className="font-bold text-lg text-blue-900">
                            {formatRupiah(calculateStayTotal())}
                          </span>
                        </div>
                      )}
                    </div>
                  )}

                  {selectedTab === 'rent' && (
                    <div className="space-y-3">
                      <div className="p-3 bg-gradient-to-r from-blue-50 to-indigo-50/50 border border-blue-100/60 rounded-xl text-xs flex justify-between items-center shadow-xs">
                        <span className="text-blue-900 font-medium flex items-center gap-1">
                          <Sparkles className="h-3.5 w-3.5 text-blue-500" />
                          Harga Sewa Bulanan:
                        </span>
                        <span className="font-extrabold text-blue-700 text-sm">{formatRupiah(property.priceMonth || 0)} / bulan</span>
                      </div>
                      <div>
                        <label className="block text-xs font-semibold text-gray-600 mb-1">Durasi Sewa (Bulan)</label>
                        <select
                          value={rentDuration}
                          onChange={(e) => setRentDuration(Number(e.target.value))}
                          className="w-full p-2.5 border border-gray-200 rounded-lg text-sm bg-white focus:outline-hidden focus:border-blue-500"
                        >
                          <option value={1}>1 Bulan</option>
                          <option value={3}>3 Bulan</option>
                          <option value={6}>6 Bulan</option>
                          <option value={12}>12 Bulan (1 Tahun)</option>
                          <option value={24}>24 Bulan (2 Tahun)</option>
                        </select>
                      </div>

                      <div className="bg-gradient-to-br from-blue-50 to-indigo-50/50 border border-blue-100 p-4 rounded-xl flex justify-between items-center text-sm shadow-xs">
                        <div>
                          <p className="font-bold text-blue-900">Total Pembayaran Sewa</p>
                          <p className="text-xs text-blue-600">Terbuka kontrak hukum digital</p>
                        </div>
                        <span className="font-bold text-lg text-blue-900">
                          {formatRupiah(calculateRentTotal())}
                        </span>
                      </div>
                    </div>
                  )}

                  {selectedTab === 'buy' && (
                    <div className="space-y-3">
                      <div className="p-4 bg-gray-50 rounded-xl border border-gray-100 text-center">
                        <span className="text-xs text-gray-500 block uppercase font-bold tracking-wider">Harga Pembelian Unit</span>
                        <span className="font-sans font-extrabold text-2xl text-blue-600 mt-1 block">
                          {formatRupiah(property.priceBuy || 0)}
                        </span>
                        <p className="text-[11px] text-gray-400 mt-2">Biaya sudah termasuk Notaris, Akta Jual Beli (AJB), dan Pajak Pertambahan Nilai (PPN 11%).</p>
                      </div>

                      <div className="p-3 bg-emerald-50 rounded-lg text-xs text-emerald-800 flex items-center space-x-2">
                        <Sparkles className="h-4 w-4 shrink-0 text-emerald-600" />
                        <span>Kredit Pemilikan Rumah (KPR) tersedia dengan DP 10% (simulasi default adalah Cash Bertahap).</span>
                      </div>
                    </div>
                  )}

                  {/* Elegant Premium Invoice Breakdown (ALWAYS visible) */}
                  <div className="bg-slate-50 rounded-2xl p-4 border border-slate-150 space-y-2.5 shadow-inner">
                      <div className="text-xs font-bold text-gray-800 border-b border-gray-150 pb-2 flex items-center gap-1.5">
                        <Sparkles className="h-3.5 w-3.5 text-blue-600 animate-pulse" />
                        Rincian Tagihan Pemesanan
                      </div>
                      
                      <div className="flex justify-between text-xs text-gray-500">
                        <span>
                          Harga Dasar {selectedTab === 'stay' ? (selectedRoom ? `(Unit ${selectedRoom.roomNumber})` : '(Default)') : ''}:
                        </span>
                        <span className="font-semibold text-gray-800">
                          {formatRupiah(
                            selectedTab === 'stay'
                              ? (selectedRoom ? selectedRoom.priceDay : effectivePriceDay)
                              : selectedTab === 'rent'
                                ? (property.priceMonth || 0)
                                : (property.priceBuy || 0)
                          )}
                          {selectedTab === 'stay' ? ' / hari' : selectedTab === 'rent' ? ' / bulan' : ''}
                        </span>
                      </div>

                      {selectedTab === 'stay' && (
                        <div className="flex justify-between text-xs text-gray-500">
                          <span>Durasi Menginap:</span>
                          <span className="font-semibold text-gray-800">
                            {getStayDays() > 0 ? `${getStayDays()} Malam` : 'Belum memilih tanggal'}
                          </span>
                        </div>
                      )}

                      {selectedTab === 'rent' && (
                        <div className="flex justify-between text-xs text-gray-500">
                          <span>Durasi Sewa:</span>
                          <span className="font-semibold text-gray-800">{rentDuration} Bulan</span>
                        </div>
                      )}

                      {appliedDiscount > 0 && (
                        <div className="flex justify-between text-xs text-emerald-600 font-bold bg-emerald-50 px-2 py-1.5 rounded-lg border border-emerald-100">
                          <span>Kupon Terpasang ({couponCode.toUpperCase()}):</span>
                          <span>-{formatRupiah(appliedDiscount)}</span>
                        </div>
                      )}

                      <div className="border-t border-dashed border-gray-200 my-2 pt-2 flex justify-between items-center text-xs font-bold text-gray-800">
                        <span>Total Tagihan:</span>
                        <span className="text-base text-blue-700 font-extrabold">
                          {formatRupiah(Math.max(0, currentBasePrice - appliedDiscount))}
                        </span>
                      </div>

                      {paymentCycle === 'DP' && selectedTab !== 'buy' && (
                        <div className="bg-amber-50 rounded-xl p-3 border border-amber-100 text-[11px] space-y-1.5">
                          <div className="flex justify-between text-amber-900 font-bold">
                            <span>Siklus Bayar:</span>
                            <span className="uppercase text-[9px] bg-amber-200 px-1.5 py-0.5 rounded-md font-extrabold">Uang Muka (DP)</span>
                          </div>
                          <div className="flex justify-between text-amber-900 font-extrabold">
                            <span>Nominal Uang Muka:</span>
                            <span>{formatRupiah(Number(amountPaid) || 0)}</span>
                          </div>
                          <div className="flex justify-between text-amber-700 font-semibold border-t border-amber-100 pt-1">
                            <span>Sisa Tagihan (Ditunda):</span>
                            <span>{formatRupiah(Math.max(0, (currentBasePrice - appliedDiscount) - (Number(amountPaid) || 0)))}</span>
                          </div>
                        </div>
                      )}
                    </div>
                  </div>

                  {currentUser && currentUser.role !== 'superadmin' && !currentUser.permissions.includes('order_transaction') && (
                    <div className="p-3 bg-amber-50 border border-amber-200 text-amber-800 rounded-xl text-xs font-semibold flex items-start space-x-2">
                      <AlertTriangle className="h-4 w-4 text-amber-500 shrink-0 mt-0.5" />
                      <div>
                        <p className="font-bold">Izin Transaksi Dinonaktifkan</p>
                        <p className="text-[10px] text-amber-700 font-normal mt-0.5">Peran akun Anda ({currentUser.roleName}) tidak memiliki hak "order_transaction" untuk bertransaksi.</p>
                      </div>
                    </div>
                  )}

                  {error && (
                    <div className="p-3 bg-red-50 border border-red-100 text-red-700 rounded-lg text-xs font-semibold" id="details-modal-error">
                      {error}
                    </div>
                  )}

                  {!currentUser && (
                    <div className="p-3.5 bg-gradient-to-br from-blue-50 to-indigo-50/60 border border-blue-100/80 rounded-xl text-xs space-y-1 my-3 shadow-xs">
                      <div className="flex items-center space-x-1.5 text-blue-900 font-bold">
                        <Sparkles className="h-4 w-4 text-blue-500 animate-pulse" />
                        <span>Booking Instan & Daftar Akun Otomatis</span>
                      </div>
                      <p className="text-gray-600 text-[11px] leading-relaxed">
                        Sistem kami mendukung pemesanan instan! Dengan menekan tombol di bawah, Anda akan dipandu untuk mendaftarkan akun baru, dan pemesanan unit ini akan otomatis diproses dan disimpan di akun Anda setelah pendaftaran selesai.
                      </p>
                    </div>
                  )}

                  {/* Submit Action */}
                  <div className="pt-4">
                    {currentUser ? (
                      <button
                        type="submit"
                        disabled={currentUser.role !== 'superadmin' && !currentUser.permissions.includes('order_transaction')}
                        className={`w-full font-bold py-3 px-4 rounded-xl shadow-sm transition-colors cursor-pointer text-sm ${
                          currentUser.role !== 'superadmin' && !currentUser.permissions.includes('order_transaction')
                            ? 'bg-gray-200 text-gray-400 cursor-not-allowed border border-gray-300'
                            : 'bg-blue-600 hover:bg-blue-700 text-white'
                        }`}
                      >
                        {currentUser.role !== 'superadmin' && !currentUser.permissions.includes('order_transaction')
                          ? 'Izin Transaksi Tidak Tersedia'
                          : selectedTab === 'stay' ? 'Pesan Kamar Sekarang' : selectedTab === 'rent' ? 'Sewa Properti Ini' : 'Ajukan Pembelian Properti'}
                      </button>
                    ) : (
                      <button
                        type="submit"
                        className="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-4 rounded-xl shadow-sm transition-colors cursor-pointer text-sm"
                      >
                        {selectedTab === 'stay' ? 'Pesan Kamar & Daftar Akun' : selectedTab === 'rent' ? 'Sewa Properti & Daftar Akun' : 'Beli Properti & Daftar Akun'}
                      </button>
                    )}
                  </div>
              </>
            ) : (
              <div className="mt-8 p-6 bg-red-50 text-center rounded-xl border border-red-100">
                <Coins className="h-10 w-10 text-red-500 mx-auto" />
                <h4 className="font-bold text-red-900 mt-2">Properti Tidak Tersedia</h4>
                <p className="text-xs text-red-600 mt-1">
                  Properti ini telah berhasil disewa/dibeli oleh pengguna lain. Status: <span className="uppercase font-extrabold">{property.status}</span>
                </p>
              </div>
            )}
          </div>

          <div className="mt-6 pt-4 border-t border-gray-100 flex items-center space-x-3 text-xs text-gray-400">
            <User className="h-4 w-4 text-gray-300" />
            <span>Listing dikelola oleh: <strong>{property.ownerName}</strong></span>
          </div>
        </div>
      </form>
    </div>
  );
}
