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

import { MapPin, Building, Key, Coins, CalendarDays, Eye, Trash2 } from 'lucide-react';
import { Property, User, Room } from '../types';

interface PropertyCardProps {
  key?: string | number;
  property: Property;
  currentUser: User | null;
  onSelect: (property: Property) => void;
  onDelete?: (id: string) => void | Promise<void>;
  rooms?: Room[];
}

export default function PropertyCard({
  property,
  currentUser,
  onSelect,
  onDelete,
  rooms = [],
}: PropertyCardProps) {
  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) : null));
  const getBadgeColors = (type: string) => {
    switch (type) {
      case 'hotel':
        return 'bg-blue-50 text-blue-700 border-blue-100';
      case 'villa':
        return 'bg-emerald-50 text-emerald-700 border-emerald-100';
      case 'apartment':
        return 'bg-indigo-50 text-indigo-700 border-indigo-100';
      case 'house':
        return 'bg-amber-50 text-amber-700 border-amber-100';
      case 'kos':
        return 'bg-purple-50 text-purple-700 border-purple-100';
      default:
        return 'bg-gray-50 text-gray-700 border-gray-100';
    }
  };

  const getStatusColors = (status: string) => {
    switch (status) {
      case 'available':
        return 'bg-green-500 text-white';
      case 'rented':
        return 'bg-orange-500 text-white';
      case 'sold':
        return 'bg-red-500 text-white';
      default:
        return 'bg-gray-500 text-white';
    }
  };

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

  const isOwner = currentUser && currentUser.id === property.ownerId;

  return (
    <div className="bg-white rounded-xl border border-gray-100 overflow-hidden shadow-xs hover:shadow-md transition-all duration-300 group flex flex-col h-full">
      {/* Property Image Container */}
      <div className="relative aspect-video overflow-hidden bg-gray-100">
        <img
          src={property.imageUrl}
          alt={property.name}
          className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
          referrerPolicy="no-referrer"
        />
        {/* Type Badge */}
        <span className={`absolute top-3 left-3 px-2.5 py-1 text-xs font-semibold rounded-full border shadow-sm uppercase tracking-wider ${getBadgeColors(property.type)}`}>
          {property.type}
        </span>
        {/* Status Badge */}
        <span className={`absolute top-3 right-3 px-2.5 py-1 text-xs font-bold rounded-md shadow-sm ${getStatusColors(property.status)}`}>
          {property.status === 'available' ? 'Tersedia' : property.status === 'rented' ? 'Disewa' : 'Terjual'}
        </span>
      </div>

      {/* Property Content */}
      <div className="p-5 flex flex-col flex-grow">
        <div className="flex-grow">
          {/* Owner Info */}
          <span className="text-[10px] font-bold tracking-widest text-gray-400 uppercase">
            Oleh: {property.ownerName}
          </span>
          <h3 className="font-sans font-semibold text-lg text-gray-900 mt-1 line-clamp-1 group-hover:text-blue-600 transition-colors">
            {property.name}
          </h3>

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

          {/* Detailed Info / Price options */}
          <div className="mt-4 pt-4 border-t border-gray-50 grid grid-cols-1 gap-2">
            {effectivePriceDay && (
              <div className="flex items-center justify-between text-xs text-gray-600">
                <span className="flex items-center text-gray-400">
                  <CalendarDays className="h-3.5 w-3.5 mr-1" /> Menginap (Harian)
                </span>
                <span className="font-bold text-gray-900">
                  {roomsWithPriceDay.length > 0 && !property.priceDay ? (
                    <span className="text-[9px] text-blue-600 font-semibold mr-1 bg-blue-50 px-1 py-0.5 rounded-md">Mulai</span>
                  ) : ''}
                  {formatRupiah(effectivePriceDay)}
                  <span className="text-[10px] font-normal text-gray-400">/hari</span>
                </span>
              </div>
            )}
            {property.priceMonth && (
              <div className="flex items-center justify-between text-xs text-gray-600">
                <span className="flex items-center text-gray-400">
                  <Key className="h-3.5 w-3.5 mr-1" /> Sewa (Bulanan)
                </span>
                <span className="font-bold text-gray-900">{formatRupiah(property.priceMonth)}<span className="text-[10px] font-normal text-gray-400">/bulan</span></span>
              </div>
            )}
            {property.priceBuy && (
              <div className="flex items-center justify-between text-xs text-gray-600">
                <span className="flex items-center text-gray-400">
                  <Coins className="h-3.5 w-3.5 mr-1" /> Beli (Milik Sendiri)
                </span>
                <span className="font-bold text-blue-600">{formatRupiah(property.priceBuy)}</span>
              </div>
            )}
          </div>
        </div>

        {/* Card Actions */}
        <div className="mt-5 pt-4 border-t border-gray-100 flex items-center justify-between gap-2">
          <button
            onClick={() => onSelect(property)}
            className="flex-grow bg-gray-50 hover:bg-blue-50 hover:text-blue-600 text-gray-700 py-2 px-3 rounded-lg text-xs font-semibold flex items-center justify-center space-x-1 transition-colors cursor-pointer"
          >
            <Eye className="h-3.5 w-3.5" />
            <span>Detail Properti</span>
          </button>

          {isOwner && onDelete && (
            <button
              onClick={() => onDelete(property.id)}
              className="bg-red-50 hover:bg-red-100 text-red-600 p-2 rounded-lg text-xs font-semibold flex items-center justify-center transition-colors cursor-pointer border border-red-100"
              title="Hapus Listing"
            >
              <Trash2 className="h-4 w-4" />
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
