import React, { useState } from 'react';
import { Room, Property, User } from '../types';
import { Plus, Edit2, Trash2, X, RefreshCw, BedDouble, Check, Tag, Info, Sparkles, Search, ArrowUpDown, ChevronUp, ChevronDown } from 'lucide-react';

interface RoomCrudPanelProps {
  rooms: Room[];
  properties: Property[];
  currentUser: User;
  onRefresh: () => void;
}

export default function RoomCrudPanel({ rooms, properties, currentUser, onRefresh }: RoomCrudPanelProps) {
  const [editingRoom, setEditingRoom] = useState<Room | null>(null);
  const [showAddForm, setShowAddForm] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Form states
  const [propertyId, setPropertyId] = useState('');
  const [roomNumber, setRoomNumber] = useState('');
  const [type, setType] = useState('');
  const [priceDay, setPriceDay] = useState('');
  const [status, setStatus] = useState<'available' | 'occupied'>('available');
  const [position, setPosition] = useState('');
  const [facing, setFacing] = useState('');
  const [view, setView] = useState('');
  const [imageUrl, setImageUrl] = useState('');
  const [facilitiesString, setFacilitiesString] = useState(''); // comma separated

  // Quick select and auto-fill states
  const [isCustomType, setIsCustomType] = useState(false);
  const [alertInfo, setAlertInfo] = useState<string | null>(null);

  const PRESET_ROOM_TYPES = [
    'Standard Cozy',
    'Superior Suite',
    'Deluxe Room',
    'Executive Room',
    'Family Suite',
    'VIP Penthouse',
    'Studio Room',
    'Kos Standar',
    'Kos VIP'
  ];

  // Find last created room of a type and load its facilities and price
  const handleSelectRoomType = (selectedType: string) => {
    setType(selectedType);
    if (!selectedType) return;
    
    // Find last created room with this type (newer ID first)
    const matched = [...rooms]
      .filter((r) => r.type && r.type.toLowerCase().trim() === selectedType.toLowerCase().trim())
      .sort((a, b) => b.id.localeCompare(a.id))[0];
      
    if (matched) {
      if (matched.facilities) {
        setFacilitiesString(matched.facilities.join(', '));
      } else {
        setFacilitiesString('');
      }
      setPriceDay(String(matched.priceDay));
      
      // Also auto-fill other non-empty fields to assist the user
      if (matched.position && !position) setPosition(matched.position);
      if (matched.facing && !facing) setFacing(matched.facing);
      if (matched.view && !view) setView(matched.view);
      if (matched.imageUrl && !imageUrl) setImageUrl(matched.imageUrl);
      
      setAlertInfo(`✨ Otomatis memuat fasilitas & tarif default dari unit terakhir (${matched.roomNumber}) untuk kelas "${selectedType}"`);
      setTimeout(() => setAlertInfo(null), 6000);
    }
  };

  // Get unique room classes and their last created room details
  const getRoomClassTemplates = () => {
    const classMap: Record<string, { lastRoom: Room; count: number }> = {};
    // Sort ascending by ID so later rooms overwrite earlier ones
    const sortedRooms = [...rooms].sort((a, b) => a.id.localeCompare(b.id));
    
    sortedRooms.forEach(room => {
      const typeKey = room.type ? room.type.trim() : '';
      if (typeKey) {
        if (!classMap[typeKey]) {
          classMap[typeKey] = { lastRoom: room, count: 0 };
        }
        classMap[typeKey].lastRoom = room;
        classMap[typeKey].count += 1;
      }
    });
    
    return Object.entries(classMap).map(([typeName, data]) => ({
      typeName,
      lastRoom: data.lastRoom,
      count: data.count
    }));
  };

  // Filter properties by owner role
  let myProperties = properties;
  if (currentUser.role === 'admin') {
    myProperties = properties.filter((p) => p.id === currentUser.propertyId);
  } else if (currentUser.role === 'owner') {
    myProperties = properties.filter((p) => p.ownerId === currentUser.id);
  }

  // Search and Sort states
  const [searchQuery, setSearchQuery] = useState('');
  const [sortField, setSortField] = useState<'roomNumber' | 'type' | 'priceDay' | 'status' | 'propertyId'>('roomNumber');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc');

  const myPropertyIds = myProperties.map((p) => p.id);
  let myRooms = rooms.filter((r) => myPropertyIds.includes(r.propertyId));

  // Search filter
  if (searchQuery.trim() !== '') {
    const q = searchQuery.toLowerCase();
    myRooms = myRooms.filter(r => 
      r.roomNumber.toLowerCase().includes(q) ||
      (r.type && r.type.toLowerCase().includes(q)) ||
      (r.position && r.position.toLowerCase().includes(q)) ||
      (r.facilities && r.facilities.some(f => f.toLowerCase().includes(q))) ||
      getPropertyName(r.propertyId).toLowerCase().includes(q)
    );
  }

  // Sorting logic
  myRooms = [...myRooms].sort((a, b) => {
    let comparison = 0;
    if (sortField === 'roomNumber') {
      comparison = a.roomNumber.localeCompare(b.roomNumber, undefined, { numeric: true, sensitivity: 'base' });
    } else if (sortField === 'type') {
      comparison = (a.type || '').localeCompare(b.type || '');
    } else if (sortField === 'priceDay') {
      comparison = a.priceDay - b.priceDay;
    } else if (sortField === 'status') {
      comparison = a.status.localeCompare(b.status);
    } else if (sortField === 'propertyId') {
      comparison = getPropertyName(a.propertyId).localeCompare(getPropertyName(b.propertyId));
    }
    return sortOrder === 'asc' ? comparison : -comparison;
  });

  const handleToggleSort = (field: 'roomNumber' | 'type' | 'priceDay' | 'status' | 'propertyId') => {
    if (sortField === field) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortOrder('asc');
    }
  };

  const resetForm = () => {
    setPropertyId(myProperties[0]?.id || '');
    setRoomNumber('');
    setType('');
    setPriceDay('');
    setStatus('available');
    setPosition('');
    setFacing('');
    setView('');
    setImageUrl('');
    setFacilitiesString('');
    setError(null);
  };

  const openEdit = (room: Room) => {
    setEditingRoom(room);
    setPropertyId(room.propertyId);
    setRoomNumber(room.roomNumber);
    setType(room.type);
    setPriceDay(String(room.priceDay));
    setStatus(room.status);
    setPosition(room.position || '');
    setFacing(room.facing || '');
    setView(room.view || '');
    setImageUrl(room.imageUrl || '');
    setFacilitiesString(room.facilities ? room.facilities.join(', ') : '');
    setShowAddForm(false);
  };

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    const activePropertyId = propertyId || myProperties[0]?.id;
    if (!activePropertyId || !roomNumber || !type || !priceDay) {
      setError('Harap lengkapi field wajib: Properti, Nomor Kamar, Tipe, dan Tarif Harian');
      return;
    }

    setLoading(true);
    setError(null);
    try {
      const facilities = facilitiesString.split(',')
        .map(f => f.trim())
        .filter(f => f.length > 0);

      const res = await fetch('/api/rooms', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          propertyId: activePropertyId,
          roomNumber,
          type,
          priceDay: Number(priceDay),
          status,
          position,
          facilities,
          facing,
          view,
          imageUrl,
        }),
      });

      if (res.ok) {
        resetForm();
        setShowAddForm(false);
        onRefresh();
      } else {
        const data = await res.json();
        setError(data.error || 'Gagal menambahkan kamar');
      }
    } catch (err) {
      setError('Koneksi ke server gagal');
    } finally {
      setLoading(false);
    }
  };

  const handleUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!editingRoom) return;
    if (!propertyId || !roomNumber || !type || !priceDay) {
      setError('Harap lengkapi field wajib: Properti, Nomor Kamar, Tipe, dan Tarif Harian');
      return;
    }

    setLoading(true);
    setError(null);
    try {
      const facilities = facilitiesString.split(',')
        .map(f => f.trim())
        .filter(f => f.length > 0);

      const res = await fetch(`/api/rooms/${editingRoom.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          propertyId,
          roomNumber,
          type,
          priceDay: Number(priceDay),
          status,
          position,
          facilities,
          facing,
          view,
          imageUrl,
        }),
      });

      if (res.ok) {
        setEditingRoom(null);
        resetForm();
        onRefresh();
      } else {
        const data = await res.json();
        setError(data.error || 'Gagal memperbarui kamar');
      }
    } catch (err) {
      setError('Koneksi ke server gagal');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!window.confirm('Apakah Anda yakin ingin menghapus kamar / ruangan ini?')) return;
    setLoading(true);
    try {
      const res = await fetch(`/api/rooms/${id}`, { method: 'DELETE' });
      if (res.ok) {
        onRefresh();
      } else {
        const data = await res.json();
        alert(data.error || 'Gagal menghapus kamar');
      }
    } catch (err) {
      alert('Koneksi ke server gagal');
    } finally {
      setLoading(false);
    }
  };

  const getPropertyName = (id: string) => {
    return properties.find(p => p.id === id)?.name || 'Properti Tidak Diketahui';
  };

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

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center bg-white p-4 rounded-xl border border-gray-100 shadow-xs">
        <div>
          <h3 className="font-sans font-bold text-base text-gray-900">Kelola Unit Kamar / Ruangan (CRUD)</h3>
          <p className="text-xs text-gray-400">Total {myRooms.length} kamar / unit aktif terdaftar</p>
        </div>
        {!showAddForm && !editingRoom && myProperties.length > 0 && (
          <button
            onClick={() => { resetForm(); setShowAddForm(true); }}
            className="bg-blue-600 hover:bg-blue-700 text-white px-3 py-1.5 rounded-lg text-xs font-bold flex items-center space-x-1 cursor-pointer transition-colors"
          >
            <Plus className="h-4 w-4" />
            <span>Tambah Kamar Baru</span>
          </button>
        )}
      </div>

      {myProperties.length === 0 && (
        <div className="bg-amber-50 p-4 rounded-xl border border-amber-100 text-xs text-amber-800 flex items-start space-x-2">
          <Info className="h-4 w-4 text-amber-600 shrink-0 mt-0.5" />
          <div>
            <p className="font-bold">Properti Tidak Ditemukan</p>
            <p className="mt-0.5">Daftarkan properti (hotel, villa, apartemen) terlebih dahulu di tab <strong>Manajemen Properti</strong> sebelum Anda bisa menambahkan kamar atau ruangan.</p>
          </div>
        </div>
      )}

      {error && (
        <div className="bg-red-50 text-red-800 p-3.5 rounded-lg border border-red-100 text-xs font-semibold">
          {error}
        </div>
      )}

      {/* CREATE OR EDIT FORM */}
      {(showAddForm || editingRoom) && (
        <form onSubmit={showAddForm ? handleCreate : handleUpdate} className="bg-white p-6 rounded-xl border border-gray-100 shadow-xs space-y-4">
          <div className="flex justify-between items-center pb-2 border-b border-gray-100">
            <h4 className="font-bold text-sm text-gray-900">
              {showAddForm ? 'Tambah Unit Kamar Baru' : `Edit Unit Kamar: Room ${editingRoom?.roomNumber}`}
            </h4>
            <button
              type="button"
              onClick={() => { setShowAddForm(false); setEditingRoom(null); resetForm(); }}
              className="text-gray-400 hover:text-gray-600 cursor-pointer"
            >
              <X className="h-4 w-4" />
            </button>
          </div>

          {alertInfo && (
            <div className="bg-blue-50 text-blue-800 border border-blue-100 px-3 py-2 rounded-lg text-xs font-semibold flex items-center space-x-2 animate-pulse">
              <Sparkles className="h-4 w-4 text-blue-500 shrink-0" />
              <span>{alertInfo}</span>
            </div>
          )}

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-gray-600">Pilih Properti <span className="text-red-500">*</span></label>
              <select
                value={propertyId}
                onChange={(e) => setPropertyId(e.target.value)}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500 bg-white"
                required
              >
                {myProperties.map(p => (
                  <option key={p.id} value={p.id}>{p.name} ({p.type})</option>
                ))}
              </select>
            </div>

            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-gray-600">Nomor / Nama Kamar <span className="text-red-500">*</span></label>
              <input
                type="text"
                value={roomNumber}
                onChange={(e) => setRoomNumber(e.target.value)}
                placeholder="e.g. 101, Villa-02, VIP-1"
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500"
                required
              />
            </div>

            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-gray-600">Tipe / Kelas Kamar <span className="text-red-500">*</span></label>
              <div className="flex gap-2">
                <select
                  value={
                    Array.from(new Set(rooms.map(r => r.type?.trim()).filter(Boolean))).includes(type) 
                      ? type 
                      : (type ? "custom" : "")
                  }
                  onChange={(e) => {
                    if (e.target.value === "custom") {
                      setType("");
                      setIsCustomType(true);
                    } else {
                      setIsCustomType(false);
                      handleSelectRoomType(e.target.value);
                    }
                  }}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500 bg-white font-medium"
                >
                  <option value="">-- Pilih Tipe / Kelas Kamar --</option>
                  
                  {/* Unique types from existing database rooms */}
                  {Array.from(new Set(rooms.map(r => r.type?.trim()).filter(Boolean))).length > 0 && (
                    <optgroup label="Tipe Terdaftar (Otomatis Acuan)">
                      {Array.from(new Set(rooms.map(r => r.type?.trim()).filter(Boolean))).map((t) => (
                        <option key={t} value={t}>{t}</option>
                      ))}
                    </optgroup>
                  )}
                  
                  {/* Common preset templates */}
                  <optgroup label="Preset Rekomendasi">
                    {PRESET_ROOM_TYPES.filter(pt => 
                      !Array.from(new Set(rooms.map(r => r.type?.trim()).filter(Boolean)))
                        .some(et => et.toLowerCase() === pt.toLowerCase())
                    ).map((pt) => (
                      <option key={pt} value={pt}>{pt}</option>
                    ))}
                  </optgroup>
                  
                  <option value="custom">✍️ Ketik Tipe / Kelas Kustom...</option>
                </select>
                
                {isCustomType && (
                  <button
                    type="button"
                    onClick={() => {
                      setIsCustomType(false);
                      setType("");
                    }}
                    className="px-2.5 py-1.5 bg-gray-100 hover:bg-gray-200 text-gray-600 rounded-lg text-[10px] font-bold"
                    title="Kembali ke Dropdown"
                  >
                    Batal
                  </button>
                )}
              </div>

              {/* Show text input field if they chose custom or it doesn't match any standard types */}
              {(isCustomType || (type && !Array.from(new Set(rooms.map(r => r.type?.trim()).filter(Boolean))).includes(type) && !PRESET_ROOM_TYPES.includes(type))) && (
                <div className="mt-1.5 relative animate-in fade-in slide-in-from-top-1 duration-200">
                  <input
                    type="text"
                    value={type}
                    onChange={(e) => setType(e.target.value)}
                    placeholder="Ketik tipe kamar kustom baru..."
                    className="w-full px-3 py-2 border border-blue-300 bg-blue-50/5 rounded-lg text-xs focus:outline-hidden focus:border-blue-500 font-semibold"
                    required
                  />
                  <span className="absolute right-3 top-2 text-[8px] bg-blue-100 text-blue-800 font-extrabold px-1.5 py-0.5 rounded uppercase tracking-wider">
                    Kustom
                  </span>
                </div>
              )}
            </div>

            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-gray-600">Tarif Harian (IDR) <span className="text-red-500">*</span></label>
              <input
                type="number"
                value={priceDay}
                onChange={(e) => setPriceDay(e.target.value)}
                placeholder="e.g. 350000"
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500"
                required
              />
            </div>

            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-gray-600">Posisi / Lokasi Kamar</label>
              <input
                type="text"
                value={position}
                onChange={(e) => setPosition(e.target.value)}
                placeholder="e.g. Lantai 2, Sayap Barat"
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500"
              />
            </div>

            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-gray-600">Hadap Kamar (Arah)</label>
              <input
                type="text"
                value={facing}
                onChange={(e) => setFacing(e.target.value)}
                placeholder="e.g. Timur (Sunrise), Selatan (Pegunungan)"
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500"
              />
            </div>

            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-gray-600">Pemandangan Kamar (View)</label>
              <input
                type="text"
                value={view}
                onChange={(e) => setView(e.target.value)}
                placeholder="e.g. Kolam Renang Utama, Taman Hijau, City Skylines"
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500"
              />
            </div>

            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-gray-600">Status Kamar <span className="text-red-500">*</span></label>
              <select
                value={status}
                onChange={(e) => setStatus(e.target.value as any)}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500 bg-white"
              >
                <option value="available">Tersedia / Kosong (Hijau)</option>
                <option value="occupied">Terisi / Terpakai (Merah)</option>
              </select>
            </div>

            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-gray-600">Fasilitas <span className="text-gray-400 font-normal">(pisahkan dengan koma)</span></label>
              <input
                type="text"
                value={facilitiesString}
                onChange={(e) => setFacilitiesString(e.target.value)}
                placeholder="AC, Smart TV, Wifi, Bathtub, King Bed"
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500"
              />
            </div>

            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-gray-600">Link Foto Interior Kamar</label>
              <input
                type="text"
                value={imageUrl}
                onChange={(e) => setImageUrl(e.target.value)}
                placeholder="https://..."
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500"
              />
            </div>
          </div>

          <div className="flex justify-end space-x-3 pt-3 border-t border-gray-100">
            <button
              type="button"
              onClick={() => { setShowAddForm(false); setEditingRoom(null); resetForm(); }}
              className="px-4 py-2 border border-gray-300 rounded-lg text-xs font-semibold text-gray-600 hover:bg-gray-50 cursor-pointer"
            >
              Batalkan
            </button>
            <button
              type="submit"
              disabled={loading}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg text-xs font-bold shadow-sm hover:bg-blue-700 disabled:opacity-50 cursor-pointer flex items-center space-x-1"
            >
              {loading && <RefreshCw className="h-3 w-3 animate-spin" />}
              <span>{showAddForm ? 'Tambahkan Kamar' : 'Simpan Perubahan'}</span>
            </button>
          </div>
        </form>
      )}

      {/* SEARCH & FILTERS FOR ROOMS */}
      <div className="bg-white p-4 rounded-xl border border-gray-100 shadow-xs flex flex-col sm:flex-row gap-3 items-center">
        <div className="relative flex-1 w-full">
          <Search className="absolute left-3 top-2.5 h-4 w-4 text-gray-400" />
          <input
            type="text"
            placeholder="Cari unit berdasarkan nomor, tipe/kelas, properti, fasilitas, lokasi..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full bg-gray-50 border border-gray-200 rounded-lg pl-9 pr-4 py-2 text-xs focus:outline-hidden focus:ring-2 focus:ring-blue-100 focus:bg-white focus:border-blue-500 transition-all text-gray-800 font-medium"
          />
        </div>
        <div className="flex items-center space-x-2 shrink-0 w-full sm:w-auto justify-end">
          <span className="text-[10px] font-black text-gray-400 uppercase tracking-wider">Urutkan:</span>
          <select
            value={`${sortField}-${sortOrder}`}
            onChange={(e) => {
              const [field, order] = e.target.value.split('-');
              setSortField(field as any);
              setSortOrder(order as any);
            }}
            className="bg-gray-50 border border-gray-200 rounded-lg text-xs py-2 px-3 focus:outline-hidden focus:ring-2 focus:ring-blue-100 focus:bg-white focus:border-blue-500 transition-all text-gray-700 font-bold cursor-pointer"
          >
            <option value="roomNumber-asc">Nomor Kamar (1-9)</option>
            <option value="roomNumber-desc">Nomor Kamar (9-1)</option>
            <option value="type-asc">Tipe / Kelas (A-Z)</option>
            <option value="type-desc">Tipe / Kelas (Z-A)</option>
            <option value="priceDay-asc">Tarif Terendah</option>
            <option value="priceDay-desc">Tarif Tertinggi</option>
            <option value="status-asc">Status (A-Z)</option>
            <option value="status-desc">Status (Z-A)</option>
            <option value="propertyId-asc">Properti (A-Z)</option>
            <option value="propertyId-desc">Properti (Z-A)</option>
          </select>
        </div>
      </div>

      {/* ROOMS TABLE LIST */}
      <div className="bg-white rounded-xl border border-gray-100 shadow-xs overflow-hidden">
        <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-gray-50/50">
                <th className="py-3 px-4 cursor-pointer hover:bg-gray-100 transition-colors select-none" onClick={() => handleToggleSort('propertyId')}>
                  <div className="flex items-center space-x-1">
                    <span>Properti</span>
                    {sortField === 'propertyId' ? (sortOrder === 'asc' ? <ChevronUp className="h-3 w-3 text-blue-600" /> : <ChevronDown className="h-3 w-3 text-blue-600" />) : <ArrowUpDown className="h-3 w-3 text-gray-300" />}
                  </div>
                </th>
                <th className="py-3 px-4 cursor-pointer hover:bg-gray-100 transition-colors select-none" onClick={() => handleToggleSort('roomNumber')}>
                  <div className="flex items-center space-x-1">
                    <span>Nomor & Kelas</span>
                    {sortField === 'roomNumber' || sortField === 'type' ? (sortOrder === 'asc' ? <ChevronUp className="h-3 w-3 text-blue-600" /> : <ChevronDown className="h-3 w-3 text-blue-600" />) : <ArrowUpDown className="h-3 w-3 text-gray-300" />}
                  </div>
                </th>
                <th className="py-3 px-4 cursor-pointer hover:bg-gray-100 transition-colors select-none" onClick={() => handleToggleSort('priceDay')}>
                  <div className="flex items-center space-x-1">
                    <span>Tarif & Lokasi</span>
                    {sortField === 'priceDay' ? (sortOrder === 'asc' ? <ChevronUp className="h-3 w-3 text-blue-600" /> : <ChevronDown className="h-3 w-3 text-blue-600" />) : <ArrowUpDown className="h-3 w-3 text-gray-300" />}
                  </div>
                </th>
                <th className="py-3 px-4">Fasilitas</th>
                <th className="py-3 px-4 cursor-pointer hover:bg-gray-100 transition-colors select-none" onClick={() => handleToggleSort('status')}>
                  <div className="flex items-center space-x-1">
                    <span>Status</span>
                    {sortField === 'status' ? (sortOrder === 'asc' ? <ChevronUp className="h-3 w-3 text-blue-600" /> : <ChevronDown className="h-3 w-3 text-blue-600" />) : <ArrowUpDown className="h-3 w-3 text-gray-300" />}
                  </div>
                </th>
                <th className="py-3 px-4 text-center">Aksi</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50 text-gray-700">
              {myRooms.map((room) => (
                <tr key={room.id} className="hover:bg-gray-50/20">
                  <td className="py-3 px-4">
                    <span className="font-bold text-gray-900 block truncate max-w-[150px]">
                      {getPropertyName(room.propertyId)}
                    </span>
                  </td>
                  <td className="py-3 px-4">
                    <div className="flex items-center space-x-2">
                      <div className="bg-blue-50 text-blue-600 p-1.5 rounded-lg shrink-0">
                        <BedDouble className="h-4 w-4" />
                      </div>
                      <div>
                        <span className="font-bold text-gray-900 block">Unit {room.roomNumber}</span>
                        <span className="text-[10px] text-gray-500">{room.type}</span>
                      </div>
                    </div>
                  </td>
                  <td className="py-3 px-4 space-y-0.5">
                    <div className="font-extrabold text-slate-800">{formatRupiah(room.priceDay)}/hari</div>
                    {room.position && <div className="text-[10px] text-gray-400 font-medium">{room.position}</div>}
                  </td>
                  <td className="py-3 px-4">
                    {room.facilities && room.facilities.length > 0 ? (
                      <div className="flex flex-wrap gap-1 max-w-[200px]">
                        {room.facilities.map((fac, i) => (
                          <span key={i} className="bg-gray-100 text-gray-600 text-[9px] px-1.5 py-0.5 rounded-sm">
                            {fac}
                          </span>
                        ))}
                      </div>
                    ) : (
                      <span className="text-gray-400 italic">Standar</span>
                    )}
                  </td>
                  <td className="py-3 px-4">
                    <span className={`px-2 py-0.5 rounded-full text-[9px] font-black uppercase ${
                      room.status === 'available' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                    }`}>
                      {room.status === 'available' ? 'Kosong / Hijau' : 'Terpakai / Merah'}
                    </span>
                  </td>
                  <td className="py-3 px-4 text-center">
                    <div className="flex items-center justify-center space-x-2">
                      <button
                        onClick={() => openEdit(room)}
                        title="Edit Kamar"
                        className="p-1.5 bg-gray-50 text-gray-600 rounded-lg border border-gray-200 hover:bg-blue-50 hover:text-blue-600 transition-colors cursor-pointer"
                      >
                        <Edit2 className="h-3.5 w-3.5" />
                      </button>
                      <button
                        onClick={() => handleDelete(room.id)}
                        title="Hapus Kamar"
                        className="p-1.5 bg-gray-50 text-gray-600 rounded-lg border border-gray-200 hover:bg-red-50 hover:text-red-600 transition-colors cursor-pointer"
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
              {myRooms.length === 0 && (
                <tr>
                  <td colSpan={6} className="py-12 text-center text-gray-400 italic">Belum ada kamar terdaftar untuk properti yang Anda kelola.</td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* ROOM CLASS REFERENCE TEMPLATES TABLE */}
      {getRoomClassTemplates().length > 0 && (
        <div className="bg-white rounded-xl border border-gray-100 shadow-xs overflow-hidden animate-in fade-in duration-300">
          <div className="p-4 border-b border-gray-100 bg-gray-50/50 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-2">
            <div>
              <h4 className="font-sans font-bold text-sm text-gray-900 flex items-center gap-2">
                <span className="bg-indigo-50 text-indigo-600 p-1.5 rounded-lg">📊</span>
                <span>Tabel Acuan Default Fasilitas & Tarif Kelas Kamar (Sistem Otomatis)</span>
              </h4>
              <p className="text-[10px] text-gray-400">
                Fasilitas otomatis secara default akan mengikuti unit terakhir yang Anda buat sesuai dengan kelas/tipe kamar di bawah ini.
              </p>
            </div>
          </div>
          
          <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-gray-50/25">
                  <th className="py-2.5 px-4">Tipe / Kelas Kamar</th>
                  <th className="py-2.5 px-4">Unit Acuan Terakhir</th>
                  <th className="py-2.5 px-4">Tarif Default</th>
                  <th className="py-2.5 px-4">Fasilitas Otomatis (Terakhir)</th>
                  <th className="py-2.5 px-4 text-center">Aksi Cepat</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50 text-gray-700">
                {getRoomClassTemplates().map(({ typeName, lastRoom, count }) => (
                  <tr key={typeName} className="hover:bg-gray-50/20 transition-colors">
                    <td className="py-3 px-4 font-bold text-gray-900">
                      <div className="flex items-center space-x-1.5">
                        <Tag className="h-3.5 w-3.5 text-indigo-500" />
                        <span>{typeName}</span>
                        <span className="bg-indigo-50 text-indigo-700 text-[8px] font-extrabold px-1.5 py-0.5 rounded-full">
                          {count} Unit
                        </span>
                      </div>
                    </td>
                    <td className="py-3 px-4">
                      <span className="text-gray-600 font-semibold">
                        Unit {lastRoom.roomNumber} <span className="text-[10px] text-gray-400 font-normal">({getPropertyName(lastRoom.propertyId)})</span>
                      </span>
                    </td>
                    <td className="py-3 px-4 font-extrabold text-slate-800">
                      {formatRupiah(lastRoom.priceDay)}/hari
                    </td>
                    <td className="py-3 px-4">
                      {lastRoom.facilities && lastRoom.facilities.length > 0 ? (
                        <div className="flex flex-wrap gap-1 max-w-[320px]">
                          {lastRoom.facilities.map((fac, i) => (
                            <span key={i} className="bg-emerald-50 text-emerald-700 border border-emerald-100/30 text-[9px] px-1.5 py-0.5 rounded-sm font-medium">
                              {fac}
                            </span>
                          ))}
                        </div>
                      ) : (
                        <span className="text-gray-400 italic">Standar</span>
                      )}
                    </td>
                    <td className="py-3 px-4 text-center">
                      <button
                        type="button"
                        onClick={() => {
                          resetForm();
                          setShowAddForm(true);
                          setEditingRoom(null);
                          // Populate details
                          setPropertyId(lastRoom.propertyId);
                          handleSelectRoomType(typeName);
                          // Scroll smoothly to form
                          window.scrollTo({ top: 0, behavior: 'smooth' });
                        }}
                        className="inline-flex items-center space-x-1 bg-indigo-50 hover:bg-indigo-600 text-indigo-600 hover:text-white border border-indigo-100/50 px-2.5 py-1 rounded-lg text-[10px] font-extrabold transition-all cursor-pointer shadow-2xs active:scale-95"
                      >
                        <Plus className="h-3 w-3" />
                        <span>Buat Unit Serupa</span>
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
