"use client";

import React, { useState, useEffect } from "react";
import { Property } from "@/data/portalData";
import { resolveImageUrl } from "@/services/propertyService";
import {
  X,
  Copy,
  Check,
  Share2,
  Send,
  Mail,
  ExternalLink,
  MessageCircle,
  Sparkles,
  Bed,
  Bath,
  Maximize2,
  MapPin,
  ShieldCheck
} from "lucide-react";

interface PropertyShareModalProps {
  isOpen: boolean;
  onClose: () => void;
  property: Property | any;
}

export default function PropertyShareModal({
  isOpen,
  onClose,
  property,
}: PropertyShareModalProps) {
  const [copied, setCopied] = useState(false);
  const [currentUrl, setCurrentUrl] = useState("");

  useEffect(() => {
    if (typeof window !== "undefined") {
      const slug = property?.slug || property?.id || "";
      const base = window.location.origin;
      setCurrentUrl(`${base}/properties/${slug}`);
    }
  }, [property]);

  if (!isOpen || !property) return null;

  const propertySlug = property.slug || String(property.id);
  const shareUrl = currentUrl || `https://dreamhomes.lk/properties/${propertySlug}`;

  const heroImage = property.heroImage
    ? resolveImageUrl(property.heroImage)
    : property.primary_image?.image_path
    ? resolveImageUrl(property.primary_image.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=1200&q=85";

  const priceText = property.priceDisplayLKR || (property.priceLKR ? `LKR ${property.priceLKR} Million` : "Price on Request");
  const locationText = property.location || property.address || "Sri Lanka";
  const bedrooms = property.bedrooms || 0;
  const bathrooms = property.bathrooms || 0;
  const sqft = property.sqft || property.area_sqft || 0;

  const shareTitle = `${property.title} - ${priceText} | DreamHomes`;
  const shareText = `Check out this luxury property on DreamHomes Sri Lanka:\n\n🏡 *${property.title}*\n💰 *Price:* ${priceText}\n📍 *Location:* ${locationText}\n📐 *Specs:* ${bedrooms} Beds • ${bathrooms} Baths • ${Number(sqft).toLocaleString()} SqFt\n\n🔗 View full photos & 360° virtual tour:\n${shareUrl}`;

  // Direct Social Share URLs
  const whatsappUrl = `https://api.whatsapp.com/send?text=${encodeURIComponent(shareText)}`;
  const facebookUrl = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(shareUrl)}`;
  const twitterUrl = `https://twitter.com/intent/tweet?url=${encodeURIComponent(shareUrl)}&text=${encodeURIComponent(`${property.title} (${priceText}) on DreamHomes Sri Lanka`)}`;
  const linkedinUrl = `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(shareUrl)}`;
  const emailUrl = `mailto:?subject=${encodeURIComponent(shareTitle)}&body=${encodeURIComponent(shareText)}`;

  const handleCopyLink = async () => {
    try {
      if (navigator.clipboard) {
        await navigator.clipboard.writeText(shareUrl);
      } else {
        const input = document.createElement("input");
        input.value = shareUrl;
        document.body.appendChild(input);
        input.select();
        document.execCommand("copy");
        document.body.removeChild(input);
      }
      setCopied(true);
      setTimeout(() => setCopied(false), 2500);
    } catch (err) {
      console.error("Failed to copy link", err);
    }
  };

  const handleNativeShare = async () => {
    if (navigator.share) {
      try {
        await navigator.share({
          title: shareTitle,
          text: `${property.title} (${priceText}) in ${locationText}`,
          url: shareUrl,
        });
      } catch (e) {
        // Share cancelled
      }
    }
  };

  return (
    <div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-md flex items-center justify-center p-4 animate-in fade-in duration-200">
      <div className="bg-white rounded-3xl max-w-lg w-full p-6 sm:p-8 shadow-2xl border border-slate-200 relative overflow-hidden space-y-6 animate-in zoom-in-95 duration-150">
        
        {/* Header */}
        <div className="flex items-center justify-between pb-3 border-b border-slate-100">
          <div className="flex items-center gap-2.5">
            <div className="w-9 h-9 rounded-2xl bg-[#4223de]/10 text-[#4223de] flex items-center justify-center font-bold">
              <Share2 className="w-4 h-4" />
            </div>
            <div>
              <h3 className="text-base font-extrabold text-slate-900 font-display-lg">
                Share Luxury Property
              </h3>
              <p className="text-[11px] text-slate-500">
                Generate rich social preview with thumbnail and details
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-1.5 rounded-xl text-slate-400 hover:text-slate-700 hover:bg-slate-100 transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* ------------------------------------------------------------- */}
        {/* SOCIAL SHARE PREVIEW CARD (How it appears in WhatsApp / FB) */}
        {/* ------------------------------------------------------------- */}
        <div className="space-y-1.5">
          <div className="flex items-center justify-between text-[11px] font-bold text-slate-500 uppercase tracking-wider">
            <span>Social Post Preview Card</span>
            <span className="text-emerald-600 flex items-center gap-1 font-semibold normal-case">
              <ShieldCheck className="w-3.5 h-3.5" /> Verified Preview
            </span>
          </div>

          <div className="bg-[#f8fafc] rounded-2xl border border-slate-200 overflow-hidden shadow-sm">
            {/* Thumbnail */}
            <div className="relative aspect-[16/9] bg-slate-200 overflow-hidden">
              <img
                src={heroImage}
                alt={property.title}
                className="w-full h-full object-cover"
              />
              <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent" />
              <div className="absolute bottom-2.5 left-3 right-3 flex items-center justify-between text-white">
                <span className="text-sm font-extrabold font-display-lg drop-shadow">
                  {priceText}
                </span>
                <span className="text-[10px] px-2 py-0.5 rounded-full bg-white/20 backdrop-blur-md font-bold">
                  {property.category || "Luxury Villa"}
                </span>
              </div>
            </div>

            {/* Post Card Text */}
            <div className="p-3.5 space-y-1.5 bg-white border-t border-slate-100">
              <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider block">
                dreamhomes.lk • Sri Lanka Luxury Real Estate
              </span>
              <h4 className="text-xs font-extrabold text-slate-900 leading-snug line-clamp-1">
                {property.title}
              </h4>
              <p className="text-[11px] text-slate-500 line-clamp-2 leading-relaxed">
                {property.description || `${bedrooms} Beds • ${bathrooms} Baths • ${Number(sqft).toLocaleString()} SqFt located in ${locationText}.`}
              </p>
              <div className="flex items-center gap-3 text-[10px] text-slate-600 font-semibold pt-1">
                <span className="flex items-center gap-1">
                  <Bed className="w-3 h-3 text-[#4223de]" /> {bedrooms} Beds
                </span>
                <span className="flex items-center gap-1">
                  <Bath className="w-3 h-3 text-[#4223de]" /> {bathrooms} Baths
                </span>
                <span className="flex items-center gap-1">
                  <MapPin className="w-3 h-3 text-[#4223de]" /> {locationText}
                </span>
              </div>
            </div>
          </div>
        </div>

        {/* ------------------------------------------------------------- */}
        {/* 1-CLICK SHARE CHANNELS (WhatsApp, Facebook, Twitter, etc.) */}
        {/* ------------------------------------------------------------- */}
        <div className="space-y-2">
          <label className="text-xs font-bold text-slate-700 block">
            Share Directly via App
          </label>
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-2.5">
            
            {/* WhatsApp */}
            <a
              href={whatsappUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="flex flex-col items-center justify-center p-3 rounded-2xl bg-[#25D366]/10 hover:bg-[#25D366]/20 border border-[#25D366]/30 text-[#128C7E] transition-all group cursor-pointer"
            >
              <div className="w-9 h-9 rounded-full bg-[#25D366] text-white flex items-center justify-center shadow-md mb-1.5 group-hover:scale-110 transition-transform">
                <MessageCircle className="w-5 h-5 fill-current" />
              </div>
              <span className="text-xs font-extrabold">WhatsApp</span>
              <span className="text-[9px] text-slate-500">Chat / Status</span>
            </a>

            {/* Facebook */}
            <a
              href={facebookUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="flex flex-col items-center justify-center p-3 rounded-2xl bg-[#1877F2]/10 hover:bg-[#1877F2]/20 border border-[#1877F2]/30 text-[#1877F2] transition-all group cursor-pointer"
            >
              <div className="w-9 h-9 rounded-full bg-[#1877F2] text-white flex items-center justify-center shadow-md mb-1.5 group-hover:scale-110 transition-transform font-bold text-base">
                f
              </div>
              <span className="text-xs font-extrabold">Facebook</span>
              <span className="text-[9px] text-slate-500">Feed / Group</span>
            </a>

            {/* Twitter / X */}
            <a
              href={twitterUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="flex flex-col items-center justify-center p-3 rounded-2xl bg-black/5 hover:bg-black/10 border border-black/20 text-black transition-all group cursor-pointer"
            >
              <div className="w-9 h-9 rounded-full bg-black text-white flex items-center justify-center shadow-md mb-1.5 group-hover:scale-110 transition-transform font-bold text-xs">
                𝕏
              </div>
              <span className="text-xs font-extrabold">X (Twitter)</span>
              <span className="text-[9px] text-slate-500">Post</span>
            </a>

            {/* Email */}
            <a
              href={emailUrl}
              className="flex flex-col items-center justify-center p-3 rounded-2xl bg-[#4223de]/10 hover:bg-[#4223de]/20 border border-[#4223de]/30 text-[#4223de] transition-all group cursor-pointer"
            >
              <div className="w-9 h-9 rounded-full bg-[#4223de] text-white flex items-center justify-center shadow-md mb-1.5 group-hover:scale-110 transition-transform">
                <Mail className="w-4 h-4" />
              </div>
              <span className="text-xs font-extrabold">Email</span>
              <span className="text-[9px] text-slate-500">Client Brief</span>
            </a>

          </div>
        </div>

        {/* ------------------------------------------------------------- */}
        {/* COPY LINK BAR */}
        {/* ------------------------------------------------------------- */}
        <div className="space-y-1.5 pt-1">
          <label className="text-xs font-bold text-slate-700 block">
            Copy Property Link
          </label>
          <div className="flex items-center gap-2">
            <div className="flex-1 bg-[#f8fafc] border border-slate-200 rounded-xl px-3.5 py-2.5 text-xs text-slate-600 font-mono truncate select-all">
              {shareUrl}
            </div>
            <button
              onClick={handleCopyLink}
              className={`px-4 py-2.5 rounded-xl font-bold text-xs flex items-center gap-1.5 transition-all cursor-pointer shrink-0 shadow-sm ${
                copied
                  ? "bg-emerald-600 text-white shadow-emerald-600/30"
                  : "bg-[#4223de] hover:bg-[#381dd0] text-white shadow-[#4223de]/30"
              }`}
            >
              {copied ? (
                <>
                  <Check className="w-4 h-4" />
                  <span>Copied!</span>
                </>
              ) : (
                <>
                  <Copy className="w-4 h-4" />
                  <span>Copy Link</span>
                </>
              )}
            </button>
          </div>
        </div>

      </div>
    </div>
  );
}
