import React, { useState, useMemo } from "react";
import { Property } from "../types";
import { Search, Bookmark, ArrowRightLeft, Layers } from "lucide-react";
import { formatIDR } from "../utils";
import { motion, AnimatePresence } from "motion/react";
import { translations } from "../translations";

interface PropertiesListProps {
  lang: "en" | "id";
  properties: Property[];
  currentCityFilter: "Bali" | "Jakarta" | "Surabaya" | "Bandung" | "All";
  currentCategoryFilter: "villas" | "apartments" | "houses" | "commercial" | "All";
  onSelectProperty: (property: Property) => void;
  savedIds: string[];
  onToggleSave: (propertyId: string) => void;
  compareIds: string[];
  onToggleCompare: (property: Property) => void;
  onNavigate: (path: string) => void;
}

export default function PropertiesList({
  lang,
  properties,
  currentCityFilter,
  currentCategoryFilter,
  onSelectProperty,
  savedIds,
  onToggleSave,
  compareIds,
  onToggleCompare,
  onNavigate
}: PropertiesListProps) {
  const isEn = lang === "en";
  const t = translations[lang];

  const [searchQuery, setSearchQuery] = useState("");
  const [maxPrice, setMaxPrice] = useState(40000000000); // Default Rp 40 Billion
  const [minBeds, setMinBeds] = useState(0);
  const [sortBy, setSortBy] = useState<"price-asc" | "price-desc" | "area-desc" | "default">("default");
  const [showSavedOnly, setShowSavedOnly] = useState(false);

  // Localized high-end descriptions
  const portfolioMetadata = useMemo(() => {
    if (currentCityFilter === "Bali" && currentCategoryFilter === "villas") {
      return {
        title: isEn ? "The Bali Portfolio" : "Portofolio Bali",
        subtitle: isEn ? "Luxury Cliffside & Coastal Villas" : "Vila Pesisir & Tebing Mewah",
        desc: isEn 
          ? "A meticulously curated survey of absolute spatial sanctuaries scattered across the pristine coastal thresholds of Uluwatu and Sayan, Ubud."
          : "Survei teliti tentang tempat perlindungan spasial mutlak yang tersebar di sepanjang pesisir murni Uluwatu dan Sayan, Ubud."
      };
    } else if (currentCityFilter === "Jakarta" && currentCategoryFilter === "apartments") {
      return {
        title: isEn ? "The Jakarta Portfolio" : "Portofolio Jakarta",
        subtitle: isEn ? "Exquisite Sky Residences & Penthouses" : "Residensi Langit & Penthouse Eksklusif",
        desc: isEn
          ? "Soaring architecture framing breathtaking metropolitan horizons. Curated for maximum structural scale, urban security, and quiet luxury."
          : "Arsitektur membumbung tinggi yang membingkai cakrawala metropolitan yang menakjubkan. Dikurasi untuk skala struktural maksimal, keamanan urban, dan kenyamanan senyap."
      };
    } else if (currentCityFilter === "Surabaya" && currentCategoryFilter === "houses") {
      return {
        title: isEn ? "The Surabaya Portfolio" : "Portofolio Surabaya",
        subtitle: isEn ? "Contemporary Gated Sanctuaries" : "Hunian Kontemporer Terpadu & Terjaga",
        desc: isEn
          ? "A masterful examination of multi-generational residential layout flow, situated within prestigious residential reserves."
          : "Pemeriksaan ahli atas aliran tata letak perumahan multi-generasi, yang terletak di kawasan hunian yang paling bergengsi."
      };
    } else if (currentCityFilter === "Bandung" && currentCategoryFilter === "commercial") {
      return {
        title: isEn ? "The Bandung Portfolio" : "Portofolio Bandung",
        subtitle: isEn ? "Minimalist Commercial Architectures" : "Arsitektur Komersial Minimalis",
        desc: isEn
          ? "Passive ventilated design laboratories and Dutch-Indies architectural revival structures situated in the rolling hills and historical alleys of Bandung."
          : "Laboratorium desain berventilasi pasif dan struktur kebangkitan arsitektur Hindia-Belanda yang terletak di perbukitan hijau dan gang bersejarah Bandung."
      };
    }

    return {
      title: isEn ? "The Global Portfolio" : "Portofolio Global",
      subtitle: isEn ? "The Entire Curated Roster" : "Seluruh Daftar Terkurasi",
      desc: isEn
        ? "Browsing all architectural formats, from coastal volcanic stone monoliths to soaring high-floor private penthouses."
        : "Menjelajahi semua format arsitektur, mulai dari monolit batu vulkanik pesisir hingga penthouse pribadi di lantai tinggi yang menjulang."
    };
  }, [currentCityFilter, currentCategoryFilter, isEn]);

  const portfolioTabs = [
    { label: isEn ? "Bali Villas" : "Vila Bali", path: "/luxury-villas-bali", active: currentCityFilter === "Bali" },
    { label: isEn ? "Jakarta Apartments" : "Apartemen Jakarta", path: "/apartments-jakarta", active: currentCityFilter === "Jakarta" },
    { label: isEn ? "Surabaya Houses" : "Rumah Surabaya", path: "/houses-surabaya", active: currentCityFilter === "Surabaya" },
    { label: isEn ? "Bandung Commercial" : "Komersial Bandung", path: "/commercial-property-bandung", active: currentCityFilter === "Bandung" }
  ];

  const filteredList = useMemo(() => {
    return properties
      .filter((p) => {
        if (currentCityFilter !== "All" && p.city !== currentCityFilter) return false;
        if (currentCategoryFilter !== "All" && p.category !== currentCategoryFilter) return false;
        if (searchQuery) {
          const query = searchQuery.toLowerCase();
          const matchesTitle = p.title.toLowerCase().includes(query);
          const matchesLocation = p.location.toLowerCase().includes(query);
          const matchesNarrative = p.narrativeTitle.toLowerCase().includes(query);
          if (!matchesTitle && !matchesLocation && !matchesNarrative) return false;
        }
        if (p.price > maxPrice) return false;
        if (minBeds > 0 && p.beds < minBeds) return false;
        if (showSavedOnly && !savedIds.includes(p.id)) return false;
        return true;
      })
      .sort((a, b) => {
        if (sortBy === "price-asc") return a.price - b.price;
        if (sortBy === "price-desc") return b.price - a.price;
        if (sortBy === "area-desc") return b.area - a.area;
        return 0;
      });
  }, [properties, currentCityFilter, currentCategoryFilter, searchQuery, maxPrice, minBeds, sortBy, showSavedOnly, savedIds]);

  // Translate category codes to beautiful readable values
  const getCategoryLabel = (category: string) => {
    if (category === "villas") return t.villas;
    if (category === "apartments") return t.apartments;
    if (category === "houses") return t.houses;
    if (category === "commercial") return t.commercial;
    return category;
  };

  return (
    <div className="space-y-16" id="portfolio-browser">
      {/* Portfolio Header details */}
      <div className="space-y-4 max-w-4xl text-left">
        <span className="font-sans text-[10px] font-bold uppercase tracking-[0.25em] text-[#C5A572] block">
          {isEn ? "PORTFOLIO EXPEDITION" : "EKSPEDISI PORTOFOLIO"}
        </span>
        <h1 className="font-serif text-4xl md:text-5xl font-light tracking-tight text-[#1A1A1A]" id="portfolio-title">
          {portfolioMetadata.title}
        </h1>
        <h2 className="font-serif text-xl text-[#C5A572] italic font-normal tracking-wide">
          {portfolioMetadata.subtitle}
        </h2>
        <p className="font-sans text-xs md:text-sm text-[#555555] leading-relaxed max-w-3xl font-light">
          {portfolioMetadata.desc}
        </p>
      </div>

      {/* Portfolio Selector Tabs */}
      <div className="border-b border-[#EEECE6]/70 pb-0.5 flex flex-wrap gap-6 md:gap-12">
        {portfolioTabs.map((tab) => (
          <button
            key={tab.path}
            onClick={() => onNavigate(tab.path)}
            className={`font-sans text-[11px] font-bold uppercase tracking-[0.2em] pb-3.5 cursor-pointer transition-all duration-500 relative focus:outline-none ${
              tab.active
                ? "text-[#C5A572] font-semibold"
                : "text-zinc-400 hover:text-[#1A1A1A]"
            }`}
          >
            {tab.label}
            {tab.active && (
              <motion.span 
                layoutId="activeFilterTabLine"
                className="absolute bottom-0 left-0 right-0 h-[1.5px] bg-[#C5A572]" 
              />
            )}
          </button>
        ))}
      </div>

      {/* Luxury, Modular Filtration Control Drawer */}
      <div className="bg-[#FDFCFB] border border-[#EEECE6] rounded-none p-5 md:p-7 grid grid-cols-1 md:grid-cols-12 gap-6 items-center shadow-sm">
        {/* Keyword Search (4 cols) */}
        <div className="md:col-span-4 relative text-left">
          <label htmlFor="search-input" className="block text-[9px] font-bold uppercase tracking-[0.2em] text-zinc-400 font-sans mb-2">
            {isEn ? "REFINED KEYWORD QUERY" : "PENYARINGAN KATA KUNCI"}
          </label>
          <div className="relative">
            <input
              id="search-input"
              type="text"
              placeholder={isEn ? "E.g., Cliffside, Sayan, Penthouse..." : "Contoh: Pesisir tebing, Sayan, Penthouse..."}
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full bg-[#F5F3EF]/60 border border-[#EEECE6] focus:border-[#C5A572] focus:bg-white outline-none text-xs px-9 py-3 rounded-none text-[#1A1A1A] font-sans transition-all placeholder-zinc-400"
            />
            <Search className="w-3.5 h-3.5 text-zinc-400 absolute left-3 top-3.5" />
          </div>
        </div>

        {/* Price slider (3 cols) */}
        <div className="md:col-span-3 space-y-2 text-left">
          <div className="flex justify-between items-center text-[9px] font-bold uppercase tracking-[0.2em] text-zinc-400 font-sans">
            <span>{isEn ? "MAXIMUM VALUATION LIMIT" : "BATAS MAKSIMUM VALUASI"}</span>
            <span className="font-mono text-[#C5A572] font-bold">
              Rp {(maxPrice / 1000000000).toFixed(1)} {isEn ? "Billion" : "Miliar"}
            </span>
          </div>
          <div className="relative pt-1">
            <input
              type="range"
              min={1000000000}
              max={40000000000}
              step={500000000}
              value={maxPrice}
              onChange={(e) => setMaxPrice(Number(e.target.value))}
              className="w-full h-[3px] bg-[#EEECE6] rounded-none cursor-pointer accent-[#C5A572]"
            />
          </div>
        </div>

        {/* Beds Filter (2 cols) */}
        <div className="md:col-span-2 space-y-2 text-left">
          <span className="block text-[9px] font-bold uppercase tracking-[0.2em] text-zinc-400 font-sans">
            {isEn ? "MINIMUM CHAMBERS" : "KAMAR TIDUR MINIMUM"}
          </span>
          <div className="flex gap-1 bg-[#F5F3EF]/60 border border-[#EEECE6] p-1 rounded-none">
            {[0, 2, 4, 6].map((num) => (
              <button
                key={num}
                onClick={() => setMinBeds(num)}
                className={`flex-1 text-[10px] font-mono py-1.5 rounded-none cursor-pointer transition-all duration-300 ${
                  minBeds === num
                    ? "bg-[#1A1A1A] text-white font-bold"
                    : "text-zinc-500 hover:text-[#1A1A1A]"
                }`}
              >
                {num === 0 ? (isEn ? "ANY" : "SEMUA") : `${num}+`}
              </button>
            ))}
          </div>
        </div>

        {/* Sorting Dropdown (2 cols) */}
        <div className="md:col-span-2 space-y-2 text-left">
          <label htmlFor="sorting-select" className="block text-[9px] font-bold uppercase tracking-[0.2em] text-zinc-400 font-sans">
            {isEn ? "SEQUENCE METRIC" : "METRIK URUTAN"}
          </label>
          <select
            id="sorting-select"
            value={sortBy}
            onChange={(e: any) => setSortBy(e.target.value)}
            className="w-full bg-[#F5F3EF]/60 border border-[#EEECE6] focus:border-[#C5A572] focus:bg-white text-xs py-3 px-3 outline-none rounded-none text-zinc-600 font-sans cursor-pointer transition-all"
          >
            <option value="default">{isEn ? "Default Cataloging" : "Sesuai Katalog"}</option>
            <option value="price-asc">{isEn ? "Price Index: Low to High" : "Harga: Rendah ke Tinggi"}</option>
            <option value="price-desc">{isEn ? "Price Index: High to Low" : "Harga: Tinggi ke Rendah"}</option>
            <option value="area-desc">{isEn ? "Spatial Area: High to Low" : "Luas Spasial: Besar ke Kecil"}</option>
          </select>
        </div>

        {/* Saved toggle (1 col) */}
        <div className="md:col-span-1 flex flex-col items-center justify-center space-y-2">
          <span className="text-[9px] font-bold uppercase tracking-[0.2em] text-zinc-400 font-sans">
            {isEn ? "ARCHIVED" : "DIARSIP"}
          </span>
          <button
            onClick={() => setShowSavedOnly(!showSavedOnly)}
            className={`w-[44px] h-[44px] border rounded-none flex items-center justify-center transition-all duration-500 cursor-pointer ${
              showSavedOnly ? "bg-[#C5A572] border-[#C5A572] text-white" : "border-[#EEECE6] text-zinc-400 hover:border-[#1A1A1A] hover:text-[#1A1A1A]"
            }`}
            title={isEn ? "Filter saved archives" : "Saring arsip tersimpan"}
          >
            <Bookmark className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* Dynamic Counter of Structured Grid results */}
      <div className="text-left py-1 flex items-center justify-between border-b border-[#EEECE6]/40">
        <span className="font-mono text-[9px] uppercase tracking-widest text-zinc-400 font-semibold">
          {isEn ? "INDEX ANALYSIS:" : "ANALISIS INDEKS:"} {filteredList.length} {isEn ? "SPECTRA DETECTED" : "SPEKTRA TERDETEKSI"}
        </span>
        {searchQuery && (
          <button 
            onClick={() => setSearchQuery("")} 
            className="font-mono text-[9px] text-[#C5A572] hover:underline"
          >
            {isEn ? "CLEAR KEYWORD FILTER" : "HAPUS PENYARING KATA KUNCI"}
          </button>
        )}
      </div>

      {/* Structured Grid of Editorial Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-y-16 gap-x-[32px]" id="listings-grid">
        <AnimatePresence mode="popLayout">
          {filteredList.length === 0 ? (
            <motion.div 
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="col-span-full py-28 text-center border border-dashed border-[#EEECE6] text-zinc-400 font-serif italic text-lg bg-[#FDFCFB]/40"
            >
              {t.noProperties}
            </motion.div>
          ) : (
            filteredList.map((prop, idx) => {
              const actsSaved = savedIds.includes(prop.id);
              const actsCompared = compareIds.includes(prop.id);

              return (
                <motion.article
                  layout
                  key={prop.id}
                  initial={{ opacity: 0, y: 30 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, scale: 0.95 }}
                  viewport={{ once: true }}
                  transition={{ duration: 0.65, delay: idx * 0.05, ease: [0.16, 1, 0.3, 1] }}
                  className="group flex flex-col justify-between h-full bg-[#FDFCFB] border border-[#EEECE6]/60 rounded-none overflow-hidden transition-all duration-500 luxury-shadow relative"
                  id={`property-card-${prop.id}`}
                >
                  {/* Image Block */}
                  <div className="aspect-[4/3] w-full bg-[#F5F3EF] overflow-hidden relative cursor-pointer" onClick={() => onSelectProperty(prop)}>
                    <img
                      src={prop.heroImage}
                      alt={prop.title}
                      className="w-full h-full object-cover group-hover:scale-[1.04] transition-transform duration-[1.2s] ease-[0.16, 1, 0.3, 1]"
                    />
                    
                    {/* Badges metadata on top */}
                    <div className="absolute top-4 left-4 flex flex-col items-start gap-1.5 pointer-events-none z-10">
                      {prop.isFeatured && (
                        <span className="bg-[#1A1A1A] text-white font-sans text-[8px] font-bold uppercase tracking-[0.25em] px-2.5 py-1">
                          {isEn ? "FEATURED" : "UNGGULAN"}
                        </span>
                      )}
                      {prop.recentlyAdded && (
                        <span className="bg-[#C5A572] text-white font-sans text-[8px] font-bold uppercase tracking-[0.25em] px-2.5 py-1">
                          {isEn ? "LATEST RECRUIT" : "ARSIP TERBARU"}
                        </span>
                      )}
                    </div>

                    {/* Action buttons (Bookmark & Compare) */}
                    <div className="absolute top-4 right-4 flex flex-col gap-2 z-10">
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          onToggleSave(prop.id);
                        }}
                        className={`w-9 h-9 rounded-none flex items-center justify-center border transition-all duration-300 cursor-pointer ${
                          actsSaved
                            ? "bg-[#1A1A1A] text-white border-[#1A1A1A]"
                            : "bg-white/95 text-[#1A1A1A] border-[#EEECE6] hover:bg-[#C5A572] hover:text-white"
                        }`}
                        title={actsSaved ? (isEn ? "Remove from books" : "Hapus penanda") : (isEn ? "Save structure" : "Simpan struktur")}
                      >
                        <Bookmark className="w-3.5 h-3.5" />
                      </button>

                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          onToggleCompare(prop);
                        }}
                        className={`w-9 h-9 rounded-none flex items-center justify-center border transition-all duration-300 cursor-pointer ${
                          actsCompared
                            ? "bg-[#C5A572] text-white border-[#C5A572]"
                            : "bg-white/95 text-[#1A1A1A] border-[#EEECE6] hover:bg-[#1A1A1A] hover:text-white"
                        }`}
                        title={actsCompared ? (isEn ? "Remove comparison" : "Hapus perbandingan") : (isEn ? "Compare structure" : "Bandingkan struktur")}
                      >
                        <ArrowRightLeft className="w-3.5 h-3.5" />
                      </button>
                    </div>

                    <div className="absolute bottom-3 left-4 bg-white/95 px-2.5 py-[3px] border border-[#EEECE6] font-mono text-[8px] font-bold text-[#1A1A1A] uppercase tracking-widest">
                      {getCategoryLabel(prop.category)}
                    </div>
                  </div>

                  {/* Editorial text details */}
                  <div className="p-7 space-y-4 flex flex-col justify-between flex-1">
                    <div className="space-y-2">
                      <div className="flex items-center gap-1.5">
                        <span className="w-1.5 h-1.5 bg-[#C5A572] rounded-full inline-block animate-pulse" />
                        <span className="font-sans text-[10px] uppercase tracking-[0.2em] text-[#C5A572] font-semibold">
                          {prop.location}
                        </span>
                      </div>

                      <h3
                        onClick={() => onSelectProperty(prop)}
                        className="font-serif text-xl tracking-tight text-[#1A1A1A] font-normal hover:text-[#C5A572] cursor-pointer transition-colors duration-300 leading-tight block"
                      >
                        {prop.title}
                      </h3>

                      <div className="flex items-center gap-4 text-zinc-500 font-mono text-[10px] uppercase tracking-[0.1em] border-t border-[#F5F3EF] pt-2 mt-1">
                        <div className="flex items-center gap-1">
                          <Layers className="w-3 h-3 text-[#C5A572]" />
                          <span>{prop.area.toLocaleString()} SQFT</span>
                        </div>
                        <span>•</span>
                        <span>{prop.beds} {t.beds}</span>
                        <span>•</span>
                        <span>{prop.baths} {t.baths}</span>
                      </div>
                    </div>

                    <div className="flex justify-between items-center pt-4 border-t border-[#EEECE6]/60">
                      <span className="font-serif text-lg font-bold text-[#1A1A1A]">
                        {formatIDR(prop.price)}
                      </span>
                      <button
                        onClick={() => onSelectProperty(prop)}
                        className="font-sans text-[9px] font-bold uppercase tracking-[0.25em] text-[#C5A572] hover:text-[#1A1A1A] transition-colors duration-300 flex items-center gap-1.5 cursor-pointer group/lnk"
                      >
                        <span>{isEn ? "DOSSIER" : "DOSIR"}</span>
                        <span className="material-symbols-outlined text-[10px] transition-transform duration-300 group-hover/lnk:translate-x-1">arrow_outward</span>
                      </button>
                    </div>
                  </div>
                </motion.article>
              );
            })
          )}
        </AnimatePresence>
      </div>
    </div>
  );
}
