"use client";

import React, { useState } from "react";
import Link from "next/link";
import { Property } from "@/data/portalData";
import { resolveImageUrl, recordPropertyView } from "@/services/propertyService";
import { useAuth } from "@/context/AuthContext";
import { 
  Bed, 
  Bath, 
  Maximize2, 
  MapPin, 
  Heart, 
  Eye, 
  ShieldCheck, 
  Sparkles, 
  ArrowUpRight,
  Share2,
  Check
} from "lucide-react";

interface PropertyCardProps {
  property: Property | any;
  onOpenTourModal?: (property: Property) => void;
}

export default function PropertyCard({ property, onOpenTourModal }: PropertyCardProps) {
  const { isPropertySaved, toggleSaveProperty } = useAuth();
  const [copied, setCopied] = useState(false);
  const isFavorite = isPropertySaved(property.id);

  const handleCopyLink = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    const url = typeof window !== "undefined"
      ? `${window.location.origin}/properties/${property.slug || property.id}`
      : `https://dreamhomes.lk/properties/${property.slug || property.id}`;

    if (navigator.clipboard) {
      navigator.clipboard.writeText(url);
    } else {
      const input = document.createElement("input");
      input.value = url;
      document.body.appendChild(input);
      input.select();
      document.execCommand("copy");
      document.body.removeChild(input);
    }
    setCopied(true);
    setTimeout(() => setCopied(false), 2500);
  };

  // 1. Safe Category extraction
  const categoryName = typeof property.category === "object" && property.category !== null
    ? property.category.name || "Residence"
    : property.category || "Luxury Villa";

  // 2. Safe Location extraction
  const locationName = typeof property.location === "object" && property.location !== null
    ? property.location.name || property.address || "Sri Lanka"
    : property.location || property.address || "Colombo, Sri Lanka";

  // 3. Safe Hero Image resolution (backend storage path vs CDN)
  const heroImageSrc = property.heroImage
    ? resolveImageUrl(property.heroImage)
    : property.primary_image?.image_path
    ? resolveImageUrl(property.primary_image.image_path)
    : property.primaryImage?.image_path
    ? resolveImageUrl(property.primaryImage.image_path)
    : property.images?.[0]?.image_path
    ? resolveImageUrl(property.images[0].image_path)
    : "https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=1000&q=80";

  // 4. Safe Price formatting
  const rawPriceLKR = Number(property.priceLKR ?? (property.price && property.price > 100000 ? (property.price / 1000000).toFixed(1) : property.price) ?? 0);
  const rawPriceUSD = Number(property.priceUSD ?? (rawPriceLKR ? Math.round((rawPriceLKR * 1000000) / 300) : 0));

  const formatPriceLKR = (lkr: number) => {
    if (!lkr) return "Price on Request";
    if (lkr >= 1) return `LKR ${lkr.toLocaleString()} Million`;
    return `LKR ${(lkr * 1000000).toLocaleString()}`;
  };

  const formatPriceUSD = (usd: number) => {
    if (!usd) return "";
    return `$${usd.toLocaleString()} USD`;
  };

  // 5. Safe Agent details
  const agentName = property.agent?.name || "DreamHomes Advisor";
  const agentAvatar = resolveImageUrl(
    property.agent?.image || property.agent?.avatar || "https://images.unsplash.com/photo-1560250097-0b93528c311a?auto=format&fit=crop&w=256&q=80"
  );
  const agentDivision = property.agent?.division || property.agent?.role || "Prime Portfolio";
  const agentSlug = property.agent?.slug || agentName.toLowerCase().replace(/\s+/g, "-");

  // 6. View Count (from database backend property_views count)
  const totalViews = Number(property.views_count ?? property.viewsCount ?? 0);

  // Safe Bedrooms / Bathrooms / Area
  const bedrooms = Number(property.bedrooms ?? 0);
  const bathrooms = Number(property.bathrooms ?? 0);
  const areaSqft = Number(property.sqft ?? property.area_sqft ?? 0);
  const propertySlug = property.slug || String(property.id);

  const handleCardClick = () => {
    // Proactively register view count
    if (property.id || property.slug) {
      recordPropertyView(propertySlug);
    }
  };

  return (
    <div className="group bg-[#0e0e10] rounded-3xl overflow-hidden border border-[#FFE259]/25 shadow-xl hover:border-[#FFE259]/60 hover:shadow-2xl transition-all duration-300 flex flex-col hover:-translate-y-1 text-white">
      
      {/* Property Image & Badges */}
      <div className="relative aspect-[16/10] overflow-hidden bg-zinc-900">
        <img
          src={heroImageSrc}
          alt={property.title}
          className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-700 ease-out opacity-90 group-hover:opacity-100"
          loading="lazy"
          onError={(e) => {
            // Fallback if local storage image is missing
            (e.target as HTMLImageElement).src = "https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=1000&q=80";
          }}
        />

        {/* Gradient Overlay for Contrast */}
        <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-black/30" />

        {/* Top Badges */}
        <div className="absolute top-4 left-4 right-4 flex items-center justify-between gap-2">
          <div className="flex flex-wrap gap-1.5 items-center">
            {property.status?.toLowerCase() === "sold" ? (
              <span className="px-3 py-1 rounded-full text-xs font-black bg-rose-600 text-white shadow-md border border-rose-400 flex items-center gap-1 uppercase tracking-wider">
                Sold
              </span>
            ) : property.status?.toLowerCase() === "rented" ? (
              <span className="px-3 py-1 rounded-full text-xs font-black bg-cyan-600 text-white shadow-md border border-cyan-400 flex items-center gap-1 uppercase tracking-wider">
                Rented
              </span>
            ) : (
              <span className="px-3 py-1 rounded-full text-xs font-extrabold bg-[#FFE259] text-black shadow-md border border-[#FFE259]/80">
                {categoryName}
              </span>
            )}
            {property.hasVirtualTour && (
              <span className="px-2.5 py-1 rounded-full text-[11px] font-bold bg-[#0A0A0A]/80 backdrop-blur-md text-[#FFE259] border border-[#FFE259]/30 flex items-center gap-1 shadow-sm">
                <Eye className="w-3 h-3 text-[#FFE259]" /> 360° VR
              </span>
            )}
            {(property.verified !== false) && (
              <span className="px-2.5 py-1 rounded-full text-[11px] font-bold bg-[#0A0A0A]/80 backdrop-blur-md text-[#FFE259] border border-[#FFE259]/40 flex items-center gap-1 shadow-sm">
                <ShieldCheck className="w-3 h-3 text-[#FFE259]" /> Verified
              </span>
            )}
          </div>

          <div className="flex items-center gap-1.5">
            {/* 1-Click Copy Share Link Button */}
            <button
              onClick={handleCopyLink}
              className={`w-8 h-8 rounded-full flex items-center justify-center transition-all cursor-pointer border border-white/10 ${
                copied
                  ? "bg-[#059669] text-white scale-110 shadow-md"
                  : "bg-black/60 backdrop-blur-md text-slate-300 hover:bg-black/80 hover:text-[#FFE259]"
              }`}
              title={copied ? "Link Copied to Clipboard!" : "Copy Property Link to share"}
              aria-label={copied ? "Link Copied" : "Copy Property Link"}
            >
              {copied ? (
                <Check className="w-3.5 h-3.5 text-white" />
              ) : (
                <Share2 className="w-3.5 h-3.5" />
              )}
            </button>

            {/* Heart Favorite Button */}
            <button
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                toggleSaveProperty(property.id, property.title);
              }}
              className={`w-8 h-8 rounded-full flex items-center justify-center transition-all cursor-pointer ${
                isFavorite
                  ? "bg-rose-500 text-white scale-110"
                  : "bg-black/60 backdrop-blur-md text-slate-300 hover:bg-black/80 hover:text-rose-400 border border-white/10"
              }`}
              title={isFavorite ? "Remove from Saved Properties" : "Save Property to Wishlist"}
              aria-label={isFavorite ? "Remove from Saved Properties" : "Save Property"}
            >
              <Heart className={`w-3.5 h-3.5 ${isFavorite ? "fill-current" : ""}`} />
            </button>
          </div>
        </div>

        {/* Bottom Price Tag on Image */}
        <div className="absolute bottom-4 left-4 right-4 flex items-end justify-between">
          <div>
            <span className="text-[#FFE259] text-xl md:text-2xl font-extrabold block leading-none font-display-lg drop-shadow-md">
              {formatPriceLKR(rawPriceLKR)}
            </span>
            
          </div>
          <span className="text-xs px-2.5 py-0.5 rounded-full bg-[#0A0A0A]/80 backdrop-blur-md text-[#FFE259] border border-[#FFE259]/30 font-medium">
            {property.status || "For Sale"}
          </span>
        </div>
      </div>

      {/* Property Details */}
      <div className="p-6 flex-grow flex flex-col justify-between">
        <div>
          {/* Location & Views Count */}
          <div className="flex items-center justify-between text-xs font-semibold text-slate-400 mb-2">
            <div className="flex items-center gap-1.5 line-clamp-1">
              <MapPin className="w-3.5 h-3.5 text-[#FFE259] shrink-0" />
              <span className="text-slate-300">{property.location || locationName}</span>
            </div>
            <div className="flex items-center gap-1 text-[11px] text-slate-400 bg-[#18181b] px-2 py-0.5 rounded-full border border-zinc-800 shrink-0 font-medium">
              <Eye className="w-3 h-3 text-[#FFE259]" />
              <span>{totalViews.toLocaleString()} Views</span>
            </div>
          </div>

          {/* Title */}
          <Link href={`/properties/${propertySlug}`} onClick={handleCardClick}>
            <h3 className="text-lg font-bold text-white group-hover:text-[#FFE259] transition-colors leading-snug mb-2 font-headline-md line-clamp-1">
              {property.title}
            </h3>
          </Link>

          <p className="text-xs text-slate-400 line-clamp-2 mb-4 leading-relaxed">
            {property.description || "Exclusive residence featuring world-class architecture and luxury fittings in prime location."}
          </p>

          {/* Key Specs Bar */}
          <div className="grid grid-cols-3 gap-2 py-3 px-3.5 bg-[#18181b] rounded-2xl border border-zinc-800 text-slate-300 text-xs font-semibold mb-4">
            <div className="flex items-center gap-1.5">
              <Bed className="w-4 h-4 text-[#FFE259] shrink-0" />
              <span>{bedrooms} Beds</span>
            </div>
            <div className="flex items-center gap-1.5">
              <Bath className="w-4 h-4 text-[#FFE259] shrink-0" />
              <span>{bathrooms} Baths</span>
            </div>
            <div className="flex items-center gap-1.5">
              <Maximize2 className="w-4 h-4 text-[#FFE259] shrink-0" />
              <span>{areaSqft.toLocaleString()} SqFt</span>
            </div>
          </div>
        </div>

        {/* Agent Badge & Action Buttons */}
        <div>
          <div className="pt-3 pb-1 border-t border-zinc-800 flex items-center justify-between">
            <Link
              href={`/agents/${agentSlug}`}
              className="flex items-center gap-2 group/agent hover:text-[#FFE259] transition-colors"
            >
              <img
                src={agentAvatar}
                alt={agentName}
                className="w-6 h-6 rounded-full object-cover border border-[#FFE259]/40"
                onError={(e) => {
                  (e.target as HTMLImageElement).src = "https://images.unsplash.com/photo-1560250097-0b93528c311a?auto=format&fit=crop&w=256&q=80";
                }}
              />
              <span className="text-[11px] font-bold text-slate-300 group-hover/agent:text-[#FFE259] truncate max-w-[140px]">
                {agentName}
              </span>
            </Link>
            <span className="text-[10px] text-slate-400 font-medium truncate max-w-[110px]">
              {agentDivision}
            </span>
          </div>

          <div className="flex items-center gap-2 pt-2">
            <Link
              href={`/properties/${propertySlug}`}
              onClick={handleCardClick}
              className="flex-1 bg-[#059669] hover:bg-[#047857] text-white text-xs font-bold py-2.5 rounded-full text-center transition-colors duration-200 flex items-center justify-center gap-1.5 shadow-md shadow-[#059669]/20"
            >
              <span>Explore Residence</span>
              <ArrowUpRight className="w-3.5 h-3.5" />
            </Link>
            
            {onOpenTourModal && (
              <button
                onClick={() => onOpenTourModal(property)}
                className="px-4 py-2.5 rounded-full bg-[#18181b] border border-[#FFE259]/30 hover:border-[#FFE259] text-slate-300 hover:text-white text-xs font-bold transition-colors cursor-pointer"
              >
                Tour
              </button>
            )}
          </div>
        </div>
      </div>

    </div>
  );
}
