import React, { useState } from "react";
import { Property } from "../types";
import { Search, RefreshCw, Compass, ArrowUpRight } from "lucide-react";
import { formatIDR, formatShortIDR } from "../utils";
import { motion, AnimatePresence } from "motion/react";

interface MapSearchProps {
  properties: Property[];
  onSelectProperty: (property: Property) => void;
  activeProperty: Property | null;
}

export default function MapSearch({ properties, onSelectProperty, activeProperty }: MapSearchProps) {
  const [selectedCity, setSelectedCity] = useState<"Bali" | "Jakarta" | "Surabaya" | "Bandung" | "All">("All");
  const [searchQuery, setSearchQuery] = useState("");
  const [hoveredProperty, setHoveredProperty] = useState<Property | null>(null);

  // Filter properties based on city and filter keywords
  const filteredProperties = properties.filter((p) => {
    const matchesCity = selectedCity === "All" || p.city === selectedCity;
    const matchesSearch =
      p.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      p.location.toLowerCase().includes(searchQuery.toLowerCase());
    return matchesCity && matchesSearch;
  });

  const cityCoordinateAnchors = {
    Jakarta: { x: 300, y: 220, label: "Metropolitan Jakarta" },
    Bandung: { x: 320, y: 245, label: "The Cool Hills of Bandung" },
    Surabaya: { x: 550, y: 250, label: "Graha Famili Surabaya" },
    Bali: { x: 680, y: 275, label: "Coastal Cliffs of Uluwatu" }
  };

  const getRelativePosition = (property: Property) => {
    if (property.city === "Jakarta") {
      return {
        x: property.id === "prop-jakarta-residence" ? 280 : 320,
        y: property.id === "prop-jakarta-residence" ? 200 : 230
      };
    } else if (property.city === "Bandung") {
      return {
        x: property.id === "prop-bandung-dago" ? 340 : 310,
        y: property.id === "prop-bandung-dago" ? 230 : 260
      };
    } else if (property.city === "Surabaya") {
      return {
        x: property.id === "prop-surabaya-famili" ? 540 : 570,
        y: property.id === "prop-surabaya-famili" ? 240 : 270
      };
    } else {
      return {
        x: property.id === "prop-glass-pavilion" ? 670 : 710,
        y: property.id === "prop-glass-pavilion" ? 270 : 290
      };
    }
  };

  return (
    <div className="bg-[#FDFCFB] border border-[#EEECE6] rounded-none overflow-hidden text-left" id="map-search-container">
      {/* Search Header */}
      <div className="p-6 md:p-8 border-b border-[#EEECE6]/70 flex flex-col lg:flex-row justify-between items-stretch lg:items-center gap-6">
        <div>
          <span className="font-sans text-[10px] font-bold uppercase tracking-[0.25em] text-[#C5A572] block mb-1.5">
            CARTOGRAPHIC EXPLORATION DIVISION
          </span>
          <h3 className="font-serif text-2xl md:text-3xl font-light tracking-tight text-[#1A1A1A]">Interactive Blueprint Atlas</h3>
        </div>

        {/* Filter Toolbar & Query Input inside Flexbox wrapper */}
        <div className="flex flex-wrap items-center gap-4 lg:self-center">
          {/* Cities selectors */}
          <div className="flex flex-wrap gap-1 bg-[#F5F3EF]/60 p-1 border border-[#EEECE6]/70 rounded-none">
            {(["All", "Bali", "Jakarta", "Surabaya", "Bandung"] as const).map((city) => (
              <button
                key={city}
                onClick={() => setSelectedCity(city)}
                className={`px-3.5 py-1.5 text-[9px] font-sans font-bold uppercase tracking-[0.15em] rounded-none transition-all duration-300 cursor-pointer ${
                  selectedCity === city
                    ? "bg-[#1A1A1A] text-[#FDFCFB]"
                    : "text-zinc-500 hover:text-[#1A1A1A]"
                }`}
              >
                {city}
              </button>
            ))}
          </div>

          {/* Search Box input with gold focus boarder */}
          <div className="relative max-w-xs w-full">
            <input
              type="text"
              placeholder="Search matching coordinate title..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-9 pr-4 py-2.5 bg-[#F5F3EF]/60 border border-[#EEECE6] focus:border-[#C5A572] focus:bg-white outline-none rounded-none text-xs text-[#1A1A1A] font-sans placeholder-zinc-400 transition-all"
            />
            <Search className="absolute left-3 top-3.5 text-zinc-400 w-3.5 h-3.5" />
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12">
        {/* Interactive Vector Map Grid (8 columns) */}
        <div className="lg:col-span-8 bg-[#F5F3EF]/70 relative h-[480px] overflow-hidden border-b lg:border-b-0 lg:border-r border-[#EEECE6] select-none">
          {/* Cartographer grid overlay lines representation */}
          <div className="absolute inset-0 grid grid-cols-12 grid-rows-8 opacity-[0.03] pointer-events-none">
            {Array.from({ length: 96 }).map((_, i) => (
              <div key={i} className="border border-[#1A1A1A]" />
            ))}
          </div>

          {/* Compass Rose Accent Details */}
          <div className="absolute bottom-6 left-6 pointer-events-none opacity-50 select-none flex items-center gap-3">
            <div className="w-9 h-9 rounded-full border border-dashed border-[#C5A572] flex items-center justify-center animate-spin-slow">
              <Compass className="text-[#C5A572] w-4 h-4" />
            </div>
            <div>
              <span className="font-sans text-[8px] uppercase tracking-[0.2em] block text-[#1A1A1A] font-bold">SOVEREIGN RADAR</span>
              <span className="font-sans text-[8px] text-zinc-400 block font-mono">115.125° E / 8.845° S</span>
            </div>
          </div>

          {/* Map Vector Artwork Graphic */}
          <svg className="w-full h-full text-zinc-300" viewBox="0 0 800 450" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M 50,150 C 150,170 200,90 350,110 C 500,130 550,220 700,180 C 750,160 800,210 800,210 L 800,450 L 0,450 Z" fill="#eae7e2" opacity="0.4" />
            <path d="M 0,320 C 180,310 250,380 430,340 C 610,300 680,410 800,390 L 800,450 L 0,450 Z" fill="#e2ded9" opacity="0.5" />

            {/* Java & Bali stylized visual contour arches */}
            <g opacity="0.25" stroke="#1A1A1A" strokeWidth="1.2" strokeLinecap="round" strokeDasharray="3 4">
              <path d="M120,240 C170,230 220,220 280,230 C340,240 400,245 460,245 C520,245 580,250 630,260 C660,265 670,270 685,270" />
              <path d="M688,271 C691,272 696,274 705,273 C710,272 715,275 720,278" />
            </g>

            {/* City Regional Anchor Markers */}
            {Object.entries(cityCoordinateAnchors).map(([city, info]) => {
              const showThis = selectedCity === "All" || selectedCity === city;
              return (
                <g key={city} opacity={showThis ? 0.9 : 0.15} className="transition-opacity duration-300">
                  <circle cx={info.x} cy={info.y} r="3" fill="#C5A572" />
                  <circle cx={info.x} cy={info.y} r="8" stroke="#C5A572" strokeWidth="0.5" strokeDasharray="2 2" className="animate-pulse" />
                  <text x={info.x + 12} y={info.y + 3} fill="#1A1A1A" className="font-sans font-bold text-[9px] tracking-[0.16em] uppercase">
                    {city}
                  </text>
                </g>
              );
            })}
          </svg>

          {/* Absolute layers coordinate property pins */}
          {filteredProperties.map((prop) => {
            const pos = getRelativePosition(prop);
            const isSelected = activeProperty?.id === prop.id;
            const isHovered = hoveredProperty?.id === prop.id;

            return (
              <div
                key={prop.id}
                className="absolute transition-all duration-300"
                style={{
                  left: `${(pos.x / 800) * 100}%`,
                  top: `${(pos.y / 450) * 100}%`,
                  transform: "translate(-50%, -100%)",
                  zIndex: isSelected ? 40 : isHovered ? 30 : 20
                }}
              >
                {/* Visual marker pin */}
                <button
                  onClick={() => onSelectProperty(prop)}
                  onMouseEnter={() => setHoveredProperty(prop)}
                  onMouseLeave={() => setHoveredProperty(null)}
                  className="flex flex-col items-center group cursor-pointer focus:outline-none"
                >
                  <div className={`px-2.5 py-1.5 shadow-md font-mono text-[9px] font-bold tracking-tight transition-all duration-300 border flex items-center gap-1 leading-none ${
                    isSelected
                      ? "bg-[#1A1A1A] text-white border-[#1A1A1A] scale-[1.07]"
                      : "bg-white text-[#1A1A1A] border-[#EEECE6] group-hover:border-[#C5A572] group-hover:text-[#C5A572]"
                  }`}>
                    <span className="w-1.5 h-1.5 rounded-full bg-[#C5A572] block shrink-0" />
                    {formatShortIDR(prop.price)}
                  </div>
                  {/* Pin tail */}
                  <div className={`w-[1px] h-2 transition-colors duration-300 ${
                    isSelected ? "bg-[#1A1A1A]" : "bg-zinc-300 group-hover:bg-[#C5A572]"
                  }`} />
                </button>

                {/* Floating summary bubble card */}
                <AnimatePresence>
                  {(isHovered || isSelected) && (
                    <motion.div 
                      initial={{ opacity: 0, y: -5, scale: 0.95 }}
                      animate={{ opacity: 1, y: 0, scale: 1 }}
                      exit={{ opacity: 0, scale: 0.95 }}
                      className="absolute bottom-full left-1/2 -translate-x-1/2 mb-1.5 w-64 bg-[#FDFCFB] border border-[#EEECE6] rounded-none p-3 shadow-xl z-50 pointer-events-auto text-left"
                    >
                      <div className="aspect-[4/3] w-full bg-[#F5F3EF] overflow-hidden mb-2.5 relative">
                        <img
                          src={prop.heroImage}
                          alt={prop.title}
                          className="w-full h-full object-cover"
                        />
                        <div className="absolute top-2 left-2 bg-[#1A1A1A] text-white font-mono text-[7px] uppercase tracking-widest px-2 py-0.5">
                          {prop.category}
                        </div>
                      </div>
                      <div className="space-y-1">
                        <div className="flex justify-between items-baseline gap-1">
                          <span className="font-sans text-[8px] font-bold text-[#C5A572] uppercase tracking-[0.15em] shrink-0">{prop.location}</span>
                          <span className="font-serif text-[11px] font-bold text-[#1A1A1A] font-mono leading-none">{formatIDR(prop.price)}</span>
                        </div>
                        <h4 className="font-serif text-sm font-normal text-[#1A1A1A] truncate tracking-tight">{prop.title}</h4>
                      </div>
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
            );
          })}
        </div>

        {/* Sidebar directory list grid (4 columns) */}
        <div className="lg:col-span-4 h-[480px] overflow-y-auto divide-y divide-[#EEECE6]/60 bg-[#FDFCFB] select-none">
          <div className="p-4 bg-[#F5F3EF]/70 sticky top-0 z-10 flex justify-between items-center border-b border-[#EEECE6]">
            <span className="font-sans text-[9px] font-bold uppercase tracking-[0.2em] text-zinc-400">
              COORDINATES ({filteredProperties.length} DISCOVERED)
            </span>
            <button
              onClick={() => {
                setSelectedCity("All");
                setSearchQuery("");
              }}
              className="font-sans text-[9px] font-bold uppercase tracking-[0.2em] text-[#C5A572] flex items-center gap-1.5 hover:text-[#1A1A1A] transition-colors cursor-pointer focus:outline-none"
            >
              <RefreshCw className="w-2.5 h-2.5" /> REBOOT
            </button>
          </div>

          {filteredProperties.length === 0 ? (
            <div className="p-16 text-center font-serif italic text-zinc-400 text-sm">
              No architectural coordinates found matching the filtration parameters.
            </div>
          ) : (
            filteredProperties.map((prop) => {
              const isSelected = activeProperty?.id === prop.id;
              return (
                <div
                  key={prop.id}
                  onClick={() => onSelectProperty(prop)}
                  className={`p-4 transition-all duration-300 cursor-pointer flex gap-4 hover:bg-[#F5F3EF]/40 ${
                    isSelected ? "bg-[#F5F3EF]/80 border-l-2 border-[#C5A572]" : ""
                  }`}
                >
                  <img
                    src={prop.heroImage}
                    alt={prop.title}
                    className="w-16 h-16 object-cover rounded-none bg-zinc-100 shrink-0 border border-zinc-200"
                  />
                  <div className="space-y-0.5 min-w-0 flex flex-col justify-center">
                    <span className="font-sans text-[8px] uppercase tracking-[0.2em] text-[#C5A572] font-semibold">
                      {prop.location.toUpperCase()}
                    </span>
                    <h4 className="font-serif text-sm text-[#1A1A1A] font-normal truncate leading-snug tracking-tight">{prop.title}</h4>
                    <p className="font-serif text-[11px] font-normal text-zinc-400 leading-none font-mono pt-0.5">{formatIDR(prop.price)}</p>
                  </div>
                </div>
              );
            })
          )}
        </div>
      </div>
    </div>
  );
}
