import React, { useState } from 'react';
import { Property, PropertyType, User } from '../types';
import { Plus, Edit2, Trash2, X, MapPin, Phone, Mail, Building, Tag, Check, RefreshCw, Search, ArrowUpDown, ChevronUp, ChevronDown } from 'lucide-react';

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

export default function PropertyCrudPanel({ properties, currentUser, onRefresh }: PropertyCrudPanelProps) {
  const [editingProperty, setEditingProperty] = useState<Property | null>(null);
  const [showAddForm, setShowAddForm] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Form states
  const [name, setName] = useState('');
  const [type, setType] = useState<PropertyType>('hotel');
  const [address, setAddress] = useState('');
  const [description, setDescription] = useState('');
  const [priceDay, setPriceDay] = useState('');
  const [priceMonth, setPriceMonth] = useState('');
  const [priceBuy, setPriceBuy] = useState('');
  const [imageUrl, setImageUrl] = useState('');
  const [contactPhone, setContactPhone] = useState('');
  const [contactEmail, setContactEmail] = useState('');
  const [status, setStatus] = useState<'available' | 'rented' | 'sold'>('available');

  const resetForm = () => {
    setName('');
    setType('hotel');
    setAddress('');
    setDescription('');
    setPriceDay('');
    setPriceMonth('');
    setPriceBuy('');
    setImageUrl('');
    setContactPhone('');
    setContactEmail('');
    setStatus('available');
    setError(null);
  };

  const openEdit = (property: Property) => {
    setEditingProperty(property);
    setName(property.name);
    setType(property.type);
    setAddress(property.address);
    setDescription(property.description);
    setPriceDay(property.priceDay ? String(property.priceDay) : '');
    setPriceMonth(property.priceMonth ? String(property.priceMonth) : '');
    setPriceBuy(property.priceBuy ? String(property.priceBuy) : '');
    setImageUrl(property.imageUrl);
    setContactPhone(property.contactPhone || '');
    setContactEmail(property.contactEmail || '');
    setStatus(property.status);
    setShowAddForm(false);
  };

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!name || !address || !description) {
      setError('Harap isi field wajib: Nama, Alamat, Deskripsi');
      return;
    }

    setLoading(true);
    setError(null);
    try {
      const res = await fetch('/api/properties', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ownerId: currentUser.id,
          ownerName: currentUser.fullName,
          name,
          type,
          address,
          description,
          priceDay: priceDay ? Number(priceDay) : undefined,
          priceMonth: priceMonth ? Number(priceMonth) : undefined,
          priceBuy: priceBuy ? Number(priceBuy) : undefined,
          imageUrl,
          contactPhone,
          contactEmail,
        }),
      });

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

  const handleUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!editingProperty) return;
    if (!name || !address || !description) {
      setError('Harap isi field wajib: Nama, Alamat, Deskripsi');
      return;
    }

    setLoading(true);
    setError(null);
    try {
      const res = await fetch(`/api/properties/${editingProperty.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name,
          type,
          address,
          description,
          priceDay: priceDay ? Number(priceDay) : undefined,
          priceMonth: priceMonth ? Number(priceMonth) : undefined,
          priceBuy: priceBuy ? Number(priceBuy) : undefined,
          imageUrl,
          contactPhone,
          contactEmail,
          status,
        }),
      });

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

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

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

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

  // Filter by search query
  if (searchQuery.trim() !== '') {
    const q = searchQuery.toLowerCase();
    displayedProperties = displayedProperties.filter(p => 
      p.name.toLowerCase().includes(q) ||
      p.address.toLowerCase().includes(q) ||
      p.description.toLowerCase().includes(q) ||
      (p.contactPhone && p.contactPhone.toLowerCase().includes(q)) ||
      (p.contactEmail && p.contactEmail.toLowerCase().includes(q)) ||
      p.type.toLowerCase().includes(q)
    );
  }

  // Sort properties
  displayedProperties = [...displayedProperties].sort((a, b) => {
    let comparison = 0;
    if (sortField === 'name') {
      comparison = a.name.localeCompare(b.name);
    } else if (sortField === 'type') {
      comparison = a.type.localeCompare(b.type);
    } else if (sortField === 'status') {
      comparison = a.status.localeCompare(b.status);
    } else if (sortField === 'priceDay') {
      const priceA = a.priceDay || a.priceMonth || a.priceBuy || 0;
      const priceB = b.priceDay || b.priceMonth || b.priceBuy || 0;
      comparison = priceA - priceB;
    }
    return sortOrder === 'asc' ? comparison : -comparison;
  });

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

  const formatRupiah = (num?: number) => {
    if (num === undefined) return '-';
    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 Listing Properti (CRUD)</h3>
          <p className="text-xs text-gray-400">Total {displayedProperties.length} properti terdaftar</p>
        </div>
        {!showAddForm && !editingProperty && (
          <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 Properti Baru</span>
          </button>
        )}
      </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 || editingProperty) && (
        <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 ? 'Pendaftaran Properti Baru' : `Edit Properti: ${editingProperty?.name}`}
            </h4>
            <button
              type="button"
              onClick={() => { setShowAddForm(false); setEditingProperty(null); resetForm(); }}
              className="text-gray-400 hover:text-gray-600 cursor-pointer"
            >
              <X className="h-4 w-4" />
            </button>
          </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">Nama Properti <span className="text-red-500">*</span></label>
              <input
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="e.g. Grand City Resort & Villa"
                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 Properti <span className="text-red-500">*</span></label>
              <select
                value={type}
                onChange={(e) => setType(e.target.value as PropertyType)}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500"
              >
                <option value="hotel">Hotel (Stay Harian)</option>
                <option value="villa">Villa (Stay Harian)</option>
                <option value="apartment">Apartemen (Sewa Bulanan / Jual)</option>
                <option value="house">Rumah (Jual)</option>
                <option value="kos">Kos-Kosan (Sewa Bulanan)</option>
              </select>
              {/* Quick Preset Pills for Property Type */}
              <div className="flex flex-wrap gap-1 mt-1">
                {(['hotel', 'villa', 'apartment', 'house', 'kos'] as PropertyType[]).map((t) => (
                  <button
                    key={t}
                    type="button"
                    onClick={() => setType(t)}
                    className={`text-[9px] px-2 py-0.5 rounded-full border transition-all cursor-pointer ${
                      type === t 
                        ? 'bg-blue-600 border-blue-600 text-white font-semibold' 
                        : 'bg-gray-50 border-gray-200 text-gray-600 hover:border-gray-300'
                    }`}
                  >
                    {t === 'hotel' ? '🏨 Hotel' : t === 'villa' ? '🏡 Villa' : t === 'apartment' ? '🏢 Apartemen' : t === 'house' ? '🏠 Rumah' : '🛏️ Kos'}
                  </button>
                ))}
              </div>
            </div>

            <div className="md:col-span-2 space-y-1.5">
              <div className="flex justify-between items-center">
                <label className="block text-xs font-semibold text-gray-600">Alamat Lengkap <span className="text-red-500">*</span></label>
                <span className="text-[10px] text-gray-400 font-medium">Klik kota untuk auto-isi</span>
              </div>
              <input
                type="text"
                value={address}
                onChange={(e) => setAddress(e.target.value)}
                placeholder="Alamat properti..."
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500"
                required
              />
              {/* Quick Location presets */}
              <div className="flex flex-wrap gap-1 mt-1 items-center">
                <span className="text-[9px] text-gray-400 font-black uppercase mr-1">Preset Kota:</span>
                {['Jakarta Pusat', 'Jakarta Selatan', 'Bandung', 'Bali', 'Yogyakarta', 'Surabaya', 'Medan'].map((city) => (
                  <button
                    key={city}
                    type="button"
                    onClick={() => {
                      if (address.toLowerCase().includes(city.toLowerCase())) return;
                      if (!address.trim()) {
                        setAddress(city);
                      } else {
                        const trimmed = address.trim();
                        setAddress(trimmed.endsWith(',') ? `${trimmed} ${city}` : `${trimmed}, ${city}`);
                      }
                    }}
                    className="text-[9px] px-2 py-0.5 rounded bg-gray-100 hover:bg-gray-200 text-gray-700 border border-gray-200/50 transition-all cursor-pointer"
                  >
                    📍 {city}
                  </button>
                ))}
              </div>
            </div>

            <div className="md:col-span-2 space-y-1.5">
              <div className="flex justify-between items-center">
                <label className="block text-xs font-semibold text-gray-600">Deskripsi Singkat & Fasilitas <span className="text-red-500">*</span></label>
                <span className="text-[10px] text-gray-400 font-medium">Klik fasilitas untuk tambah cepat</span>
              </div>
              <textarea
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                placeholder="Deskripsikan layanan, letak strategis, kenyamanan, atau fasilitas properti ini..."
                rows={3}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500"
                required
              />
              {/* Quick Facility Tag Presets */}
              <div className="flex flex-wrap gap-1 mt-1 items-center">
                <span className="text-[9px] text-gray-400 font-black uppercase mr-1">Preset Fasilitas:</span>
                {['WiFi Gratis', 'AC', 'Kolam Renang', 'Kamar Mandi Dalam', 'Parkir Mobil', 'Dapur Bersama', 'Keamanan 24 Jam', 'TV', 'Kulkas', 'Sofa'].map((fac) => (
                  <button
                    key={fac}
                    type="button"
                    onClick={() => {
                      if (description.toLowerCase().includes(fac.toLowerCase())) return;
                      if (!description.trim()) {
                        setDescription(`Fasilitas: ${fac}`);
                      } else {
                        const trimmed = description.trim();
                        if (trimmed.endsWith('.') || trimmed.endsWith(',')) {
                          setDescription(`${trimmed} ${fac}`);
                        } else {
                          setDescription(`${trimmed}, ${fac}`);
                        }
                      }
                    }}
                    className="text-[9px] px-2 py-0.5 rounded-full bg-blue-50 hover:bg-blue-100 text-blue-700 border border-blue-100/30 transition-all cursor-pointer font-medium"
                  >
                    ✨ {fac}
                  </button>
                ))}
              </div>
            </div>

            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-gray-600">Tarif per Hari (IDR) <span className="text-gray-400 font-normal">(Hotel/Villa)</span></label>
              <input
                type="number"
                value={priceDay}
                onChange={(e) => setPriceDay(e.target.value)}
                placeholder="Kosongkan jika tidak disewakan harian"
                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">Tarif per Bulan (IDR) <span className="text-gray-400 font-normal">(Apartemen/Kos)</span></label>
              <input
                type="number"
                value={priceMonth}
                onChange={(e) => setPriceMonth(e.target.value)}
                placeholder="Kosongkan jika tidak disewakan bulanan"
                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">Harga Jual Unit (IDR) <span className="text-gray-400 font-normal">(Rumah/Apartemen Jual)</span></label>
              <input
                type="number"
                value={priceBuy}
                onChange={(e) => setPriceBuy(e.target.value)}
                placeholder="Kosongkan jika tidak dijual permanen"
                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 Properti <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"
              >
                <option value="available">Tersedia / Aktif</option>
                <option value="rented">Disewa / Terisi</option>
                <option value="sold">Terjual</option>
              </select>
            </div>

            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-gray-600">Link Foto Utama Properti</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 className="space-y-1.5">
              <label className="block text-xs font-semibold text-gray-600">Telepon Kontak Pengelola</label>
              <input
                type="text"
                value={contactPhone}
                onChange={(e) => setContactPhone(e.target.value)}
                placeholder="0812-xxxx-xxxx"
                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">Email Kontak Pengelola</label>
              <input
                type="email"
                value={contactEmail}
                onChange={(e) => setContactEmail(e.target.value)}
                placeholder="pengelola@properti.com"
                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); setEditingProperty(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 Properti' : 'Simpan Perubahan'}</span>
            </button>
          </div>
        </form>
      )}

      {/* SEARCH & FILTERS FOR PROPERTIES */}
      <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 properti berdasarkan nama, alamat, tipe, deskripsi..."
            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="name-asc">Nama Properti (A-Z)</option>
            <option value="name-desc">Nama Properti (Z-A)</option>
            <option value="type-asc">Tipe Properti (A-Z)</option>
            <option value="type-desc">Tipe Properti (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>
          </select>
        </div>
      </div>

      {/* PROPERTIES TABLE */}
      <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('name')}>
                  <div className="flex items-center space-x-1">
                    <span>Info Properti</span>
                    {sortField === 'name' ? (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('type')}>
                  <div className="flex items-center space-x-1">
                    <span>Tipe & Status</span>
                    {sortField === 'type' || 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 cursor-pointer hover:bg-gray-100 transition-colors select-none" onClick={() => handleToggleSort('priceDay')}>
                  <div className="flex items-center space-x-1">
                    <span>Skema Harga</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">Kontak</th>
                <th className="py-3 px-4 text-center">Aksi</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50 text-gray-700">
              {displayedProperties.map((prop) => (
                <tr key={prop.id} className="hover:bg-gray-50/20">
                  <td className="py-3 px-4">
                    <div className="flex items-center space-x-3">
                      <img src={prop.imageUrl} alt="" className="h-10 w-16 object-cover rounded-md bg-gray-100 shrink-0 border border-gray-100" referrerPolicy="no-referrer" />
                      <div>
                        <span className="font-bold text-gray-900 block">{prop.name}</span>
                        <span className="text-[10px] text-gray-400 flex items-center mt-0.5">
                          <MapPin className="h-3 w-3 mr-0.5 inline shrink-0" />
                          <span className="truncate max-w-[200px]">{prop.address}</span>
                        </span>
                      </div>
                    </div>
                  </td>
                  <td className="py-3 px-4">
                    <div className="space-y-1">
                      <span className="font-semibold text-gray-800 capitalize bg-slate-100 px-2 py-0.5 rounded-md text-[10px] inline-block">
                        {prop.type}
                      </span>
                      <div>
                        <span className={`px-2 py-0.5 rounded-full text-[9px] font-black uppercase ${
                          prop.status === 'available' ? 'bg-green-100 text-green-800' :
                          prop.status === 'rented' ? 'bg-amber-100 text-amber-800' :
                          'bg-red-100 text-red-800'
                        }`}>
                          {prop.status === 'available' ? 'Tersedia' : prop.status === 'rented' ? 'Disewa' : 'Terjual'}
                        </span>
                      </div>
                    </div>
                  </td>
                  <td className="py-3 px-4 space-y-0.5">
                    {prop.priceDay && <div className="text-gray-900 font-semibold">{formatRupiah(prop.priceDay)} <span className="text-[10px] text-gray-400">/hari</span></div>}
                    {prop.priceMonth && <div className="text-gray-600 font-medium">{formatRupiah(prop.priceMonth)} <span className="text-[10px] text-gray-400">/bulan</span></div>}
                    {prop.priceBuy && <div className="text-blue-600 font-bold">{formatRupiah(prop.priceBuy)} <span className="text-[10px] text-gray-400">(Beli)</span></div>}
                    {!prop.priceDay && !prop.priceMonth && !prop.priceBuy && <span className="text-gray-400 italic">Hubungi pengelola</span>}
                  </td>
                  <td className="py-3 px-4 space-y-1">
                    <div className="flex items-center text-[10px] text-gray-500">
                      <Phone className="h-3 w-3 mr-1 inline text-gray-400 shrink-0" />
                      <span>{prop.contactPhone || '-'}</span>
                    </div>
                    <div className="flex items-center text-[10px] text-gray-500">
                      <Mail className="h-3 w-3 mr-1 inline text-gray-400 shrink-0" />
                      <span className="truncate max-w-[140px]">{prop.contactEmail || '-'}</span>
                    </div>
                  </td>
                  <td className="py-3 px-4 text-center">
                    <div className="flex items-center justify-center space-x-2">
                      <button
                        onClick={() => openEdit(prop)}
                        title="Edit Properti"
                        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(prop.id)}
                        title="Hapus Properti"
                        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>
              ))}
              {displayedProperties.length === 0 && (
                <tr>
                  <td colSpan={5} className="py-12 text-center text-gray-400 italic">Belum ada properti terdaftar. Buat baru untuk memulai.</td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
