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

import { Property } from '../types';
import { Star, MapPin, Zap, Shield, CheckCircle, Wifi, Compass, ArrowRight, Heart, Bell, Navigation } from 'lucide-react';

interface PropertyCardProps {
  key?: any;
  property: Property;
  isSelected: boolean;
  onSelect: (id: string | null) => void;
  onBookNow: (property: Property) => void;
  isFavorite?: boolean;
  onToggleFavorite?: (id: string) => void;
  onShowNearby?: (property: Property) => void;
  isAlertActive?: boolean;
  onToggleAlert?: (id: string) => void;
}

export default function PropertyCard({
  property,
  isSelected,
  onSelect,
  onBookNow,
  isFavorite = false,
  onToggleFavorite,
  onShowNearby,
  isAlertActive = false,
  onToggleAlert,
}: PropertyCardProps) {
  const isCharging = property.type === 'charging' || property.type === 'both';
  const isParking = property.type === 'parking' || property.type === 'both';

  // Get matching badge colors
  const getTypeBadge = () => {
    switch (property.type) {
      case 'charging':
        return (
          <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold bg-emerald-950/70 text-emerald-300 border border-emerald-900/60 shadow-sm">
            <Zap className="w-3 h-3 fill-emerald-400 stroke-emerald-300" />
            <span>EV Charging</span>
          </span>
        );
      case 'parking':
        return (
          <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold bg-indigo-950/70 text-indigo-300 border border-indigo-900/60 shadow-sm">
            <span className="text-[10px] bg-indigo-500 text-slate-950 rounded w-3.5 h-3.5 flex items-center justify-center font-black">P</span>
            <span>Smart Parking</span>
          </span>
        );
      case 'both':
        return (
          <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold bg-teal-950/70 text-teal-300 border border-teal-900/60 shadow-sm">
            <div className="flex items-center gap-0.5">
              <span className="text-[9px] bg-teal-500 text-slate-950 rounded w-3.5 h-3.5 flex items-center justify-center font-black">P</span>
              <Zap className="w-2.5 h-2.5 fill-teal-400 stroke-teal-300" />
            </div>
            <span>Charge & Park</span>
          </span>
        );
    }
  };

  const occupancyRate = ((property.totalSlots - property.availableSlots) / property.totalSlots) * 100;
  
  // Decide slots status color text
  const getSlotsStatusColor = () => {
    if (property.availableSlots === 0) return 'text-rose-400 bg-rose-950/40 border border-rose-900/30';
    if (property.availableSlots <= 3) return 'text-amber-400 bg-amber-950/40 border border-amber-900/30';
    return 'text-emerald-400 bg-emerald-950/40 border border-emerald-900/30';
  };

  return (
    <div
      id={`property-card-${property.id}`}
      onClick={() => onSelect(property.id)}
      className={`group flex flex-col rounded-2xl overflow-hidden bg-slate-900 border cursor-pointer transition-all duration-300 shadow-xl hover:shadow-2xl hover:border-slate-700
        ${isSelected 
          ? 'ring-2 ring-amber-500 border-transparent shadow-black bg-slate-900/90' 
          : 'border-slate-800/80 text-slate-200'}`}
    >
      {/* Property Photo Block - Height: aspect 4:3 style */}
      <div className="relative h-48 w-full overflow-hidden bg-slate-950 shrink-0">
        <img
          src={property.photo}
          alt={property.title}
          referrerPolicy="no-referrer"
          className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105 opacity-85"
        />
        
        {/* Type Badge Overlay */}
        <div className="absolute top-3 left-3 z-10">
          {getTypeBadge()}
        </div>

        {/* Rating overlay */}
        <div className="absolute top-3 right-3 z-10 flex items-center gap-1 px-2 py-0.5 rounded-lg bg-slate-950/95 backdrop-blur-xs text-amber-400 font-extrabold text-xs shadow-sm border border-slate-800 select-none">
          <Star className="w-3.5 h-3.5 fill-amber-400 stroke-amber-400" />
          <span>{property.rating}</span>
          {property.reviews && property.reviews.length > 0 && (
            <span className="text-slate-500 text-[9px] font-semibold pl-0.5">({property.reviews.length})</span>
          )}
        </div>

        {/* Favorite Heart Trigger */}
        {onToggleFavorite && (
          <button
            type="button"
            onClick={(e) => {
              e.stopPropagation();
              onToggleFavorite(property.id);
            }}
            className="absolute top-11 right-3 z-20 p-1.5 rounded-lg bg-slate-950/95 backdrop-blur-xs text-rose-500 hover:text-rose-400 font-extrabold text-xs shadow-sm border border-slate-800 select-none transition-transform duration-150 hover:scale-110 active:scale-95"
            title={isFavorite ? "Remove from Favorites" : "Add to Favorites"}
          >
            <Heart className={`w-3.5 h-3.5 transition-colors ${isFavorite ? 'fill-rose-500 text-rose-500' : 'text-slate-400 hover:text-slate-200'}`} />
          </button>
        )}

        {/* Price/Hour Overlay tag */}
        <div className="absolute bottom-3 right-3 z-10 bg-slate-950/90 text-white font-bold text-sm px-3 py-1 rounded-lg backdrop-blur-xs border border-slate-800 shadow-sm">
          <span className="font-sans text-xs text-amber-450">₹</span>
          <span className="text-base font-black text-amber-450">{property.fare}</span>
          <span className="text-[10px] text-slate-400 font-normal"> /hr</span>
        </div>
      </div>

      {/* Content Block */}
      <div className="flex-1 p-5 flex flex-col gap-4 bg-slate-900">
        <div>
          <h3 className="font-sans font-extrabold text-white text-lg leading-snug tracking-tight group-hover:text-amber-400 transition-colors duration-150">
            {property.title}
          </h3>
          
          <div className="flex items-start justify-between gap-2 mt-1">
            <div className="flex items-start gap-1 text-slate-400 text-xs text-balance flex-1">
              <MapPin className="w-3.5 h-3.5 shrink-0 text-slate-500 mt-0.5" />
              <span>{property.location.address}, {property.location.city}</span>
            </div>
            
            <a
              href={`https://www.google.com/maps/dir/?api=1&destination=${property.location.lat},${property.location.lng}`}
              target="_blank"
              rel="noopener noreferrer"
              onClick={(e) => e.stopPropagation()}
              className="flex items-center gap-1.5 py-1 px-2.5 rounded-lg bg-slate-950 border border-slate-800 hover:border-amber-550 hover:bg-slate-850 text-slate-300 hover:text-amber-400 text-[10px] font-extrabold shadow-sm select-none transition-all duration-150 active:scale-95 shrink-0 self-start"
              title="Navigate using Google Maps external route directions"
            >
              <Navigation className="w-3 h-3 text-amber-400 fill-amber-400/10" />
              <span>Navigate</span>
            </a>
          </div>
        </div>

        {/* Description Snippet */}
        <p className="text-slate-400 text-xs leading-relaxed line-clamp-2 font-medium">
          {property.description}
        </p>

        {/* If selected, render actual feedback review logs to build functional depth */}
        {isSelected && property.reviews && property.reviews.length > 0 && (
          <div className="space-y-2 border-t border-slate-800/60 pt-3 mt-1 text-left">
            <h5 className="text-[10px] text-amber-500 font-extrabold uppercase tracking-wider flex items-center gap-1">
              <Star className="w-3.5 h-3.5 fill-amber-500 text-amber-500" />
              <span>COMMUNITY REVIEWS ({property.reviews.length})</span>
            </h5>
            <div className="space-y-2 max-h-36 overflow-y-auto pr-1">
              {property.reviews.map((rev) => (
                <div key={rev.id} className="bg-slate-950/80 p-2.5 rounded-xl border border-slate-850 space-y-1">
                  <div className="flex items-center justify-between text-[9px] font-mono">
                    <span className="text-slate-350 font-bold">{rev.userName}</span>
                    <span className="text-slate-550">{new Date(rev.createdAt).toLocaleDateString('en-IN', { dateStyle: 'short' })}</span>
                  </div>
                  <div className="flex gap-0.5">
                    {Array.from({ length: 5 }).map((_, i) => (
                      <Star key={i} className={`w-2.5 h-2.5 ${i < rev.rating ? 'text-amber-400 fill-amber-400' : 'text-slate-900 border-none'}`} />
                    ))}
                  </div>
                  <p className="text-slate-400 text-[10.5px] leading-relaxed italic">
                    "{rev.comment}"
                  </p>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Charger Types if EV station */}
        {property.chargerTypes && property.chargerTypes.length > 0 && (
          <div className="flex flex-wrap gap-1 px-2.5 py-1.5 bg-emerald-950/25 rounded-xl border border-emerald-900/30 mt-1">
            <span className="text-[10px] text-emerald-405 font-bold uppercase tracking-wider block mr-1 self-center">Plugs:</span>
            {property.chargerTypes.map((plug, idx) => (
              <span key={idx} className="bg-slate-950 px-1.5 py-0.5 rounded text-[10px] font-bold text-emerald-300 border border-emerald-900/30">
                {plug}
              </span>
            ))}
          </div>
        )}

        {/* Amenities Icons */}
        <div className="flex flex-wrap gap-1.5 mt-1">
          {property.amenities.slice(0, 3).map((amenity, idx) => (
            <span
              key={idx}
              className="inline-flex items-center gap-1 bg-slate-950 hover:bg-slate-850 px-2 py-0.5 rounded-md text-[10px] text-slate-350 font-medium transition-colors border border-slate-850"
            >
              {amenity.includes('Guard') || amenity.includes('CCTV') || amenity.includes('Security') ? (
                <Shield className="w-3 h-3 text-slate-500" />
              ) : amenity.includes('Wi-Fi') ? (
                <Wifi className="w-3 h-3 text-slate-500" />
              ) : (
                <CheckCircle className="w-3 h-3 text-emerald-500" />
              )}
              {amenity}
            </span>
          ))}
          {property.amenities.length > 3 && (
            <span className="text-[9px] text-slate-500 font-medium self-center ml-1">
              +{property.amenities.length - 3} more
            </span>
          )}
        </div>

        {/* Slot capacity meter */}
        <div className="space-y-1.5 mt-2">
          <div className="flex justify-between text-xs font-semibold">
            <span className="text-slate-400">Available Space</span>
            <span className={`px-2 py-0.5 rounded-full text-[10px] font-extrabold border ${getSlotsStatusColor()}`}>
              {property.availableSlots === 0 
                ? 'Full Place' 
                : `${property.availableSlots} of ${property.totalSlots} Slots Free`}
            </span>
          </div>
          
          <div className="w-full bg-slate-950 border border-slate-800/80 h-2 rounded-full overflow-hidden">
            <div
              className={`h-full rounded-full transition-all duration-500 
                ${property.availableSlots === 0 
                  ? 'bg-rose-500' 
                  : property.availableSlots <= 3 
                    ? 'bg-amber-500' 
                    : 'bg-emerald-500'}`}
              style={{ width: `${Math.min(100, Math.max(5, 100 - occupancyRate))}%` }}
            />
          </div>
        </div>

        {/* Footer Actions */}
        <div className="flex items-center gap-1.5 pt-3 border-t border-slate-800/60 mt-2 shrink-0">
          <button
            type="button"
            onClick={(e) => {
              e.stopPropagation();
              onSelect(property.id);
            }}
            className="flex-1 flex items-center justify-center gap-1 py-2 px-1 text-[10px] sm:text-xs font-bold rounded-xl bg-slate-950 hover:bg-slate-850 text-slate-300 border border-slate-800 transition-all duration-150"
            title="Mark Location on Map"
          >
            <Compass className="w-3 w-3 text-slate-400" />
            <span>Map Pin</span>
          </button>

          {onShowNearby && (
            <button
              type="button"
              onClick={(e) => {
                e.stopPropagation();
                onShowNearby(property);
              }}
              className="flex-1.2 flex items-center justify-center gap-1 py-2 px-1 text-[10px] sm:text-xs font-bold rounded-xl bg-amber-950/40 hover:bg-amber-900/40 text-amber-350 border border-amber-900/30 transition-all duration-150"
              title="Show properties nearby using Geolocation"
            >
              <MapPin className="w-3 h-3 text-amber-400" />
              <span>Show Nearby</span>
            </button>
          )}

          {property.availableSlots === 0 ? (
            <button
              type="button"
              onClick={(e) => {
                e.stopPropagation();
                if (onToggleAlert) onToggleAlert(property.id);
              }}
              className={`flex-1.3 group/btn flex items-center justify-center gap-1 py-2 px-1 text-[10px] sm:text-xs font-bold rounded-xl shadow-sm transition-all duration-150 border
                ${isAlertActive 
                  ? 'bg-rose-500/15 hover:bg-rose-500/20 text-rose-400 border-rose-500/30' 
                  : 'bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 border-amber-500/30'
                }`}
              title={isAlertActive ? "Remove notification alert" : "Get notified when a spot becomes available!"}
            >
              <Bell className={`w-3.5 h-3.5 transition-transform duration-300 ${isAlertActive ? 'fill-rose-400 stroke-rose-400 animate-bounce' : 'text-amber-400 group-hover/btn:rotate-12'}`} />
              <span>{isAlertActive ? 'Alert Active' : 'Alert Me'}</span>
            </button>
          ) : (
            <button
              type="button"
              disabled={property.availableSlots === 0}
              onClick={(e) => {
                e.stopPropagation(); // Avoid triggering card selection on click
                onBookNow(property);
              }}
              className={`flex-1.3 group/btn flex items-center justify-center gap-1 py-2 px-1 text-[10px] sm:text-xs font-bold rounded-xl shadow-sm transition-all duration-150
                ${property.availableSlots === 0
                  ? 'bg-slate-950 text-slate-600 border border-slate-850 cursor-not-allowed shadow-none font-medium'
                  : 'bg-amber-500 hover:bg-amber-400 text-slate-950 border border-amber-500 hover:border-amber-400 font-extrabold shadow-amber-500/10'}`}
            >
              <span>Book Now</span>
              <ArrowRight className="w-3 h-3 transform transition-transform group-hover/btn:translate-x-0.5 shrink-0" />
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
