/*
  DESIGN: "Global Nexus" — Command palette-style search dialog
  Full-text search across partners, products, services, and pages
  Keyboard shortcut: Ctrl+K / Cmd+K
*/
import { useState, useEffect, useRef, useMemo, useCallback } from "react";
import { useLocation } from "wouter";
import { Search, X, ArrowRight, Building2, Package, FileText, ExternalLink } from "lucide-react";
import { useLanguage } from "@/contexts/LanguageContext";

interface SearchItem {
  type: "partner" | "product" | "page" | "service";
  title: string;
  titleAr?: string;
  description: string;
  descriptionAr?: string;
  href: string;
  external?: boolean;
  industry?: string;
  tags: string[];
}

// Comprehensive search index of all site content
const searchIndex: SearchItem[] = [
  // === PAGES ===
  { type: "page", title: "Home", titleAr: "الرئيسية", description: "Alzar FZE homepage — engineering consulting services", descriptionAr: "الصفحة الرئيسية لشركة الزار", href: "/", tags: ["home", "main", "alzar", "engineering", "consulting"] },
  { type: "page", title: "About Alzar FZE", titleAr: "من نحن", description: "Our story, mission, vision, and values since 1997", descriptionAr: "قصتنا ورسالتنا ورؤيتنا وقيمنا منذ 1997", href: "/about", tags: ["about", "history", "mission", "vision", "values", "1997", "jebel ali"] },
  { type: "page", title: "Contact Us", titleAr: "اتصل بنا", description: "Get in touch — phone, WhatsApp, email, or visit us", descriptionAr: "تواصل معنا — هاتف، واتساب، بريد إلكتروني", href: "/contact", tags: ["contact", "phone", "email", "whatsapp", "location", "address"] },
  { type: "page", title: "All Partners", titleAr: "جميع الشركاء", description: "Complete directory of our global industrial partners", descriptionAr: "دليل كامل لشركائنا الصناعيين العالميين", href: "/partners", tags: ["partners", "directory", "all", "global"] },
  { type: "page", title: "Ceramics Industry", titleAr: "صناعة السيراميك", description: "Ceramic raw materials, additives, and technical consulting", descriptionAr: "المواد الخام للسيراميك والإضافات والاستشارات الفنية", href: "/industries/ceramics", tags: ["ceramics", "tiles", "sanitaryware", "porcelain", "tableware"] },
  { type: "page", title: "Glass & Aluminum", titleAr: "الزجاج والألمنيوم", description: "Glass industry equipment, refractories, automation, and aluminum extrusion lubricants", descriptionAr: "معدات صناعة الزجاج والحراريات والأتمتة ومواد تشحيم بثق الألمنيوم", href: "/industries/glass", tags: ["glass", "furnace", "refractories", "container glass", "float glass", "aluminum", "extrusion"] },
  { type: "page", title: "Cement Industry", titleAr: "صناعة الأسمنت", description: "Magnesia bricks, grinding aids, and refractory solutions", descriptionAr: "طوب المغنيسيا ومساعدات الطحن والحلول الحرارية", href: "/industries/cement", tags: ["cement", "kiln", "grinding", "clinker", "refractory"] },
  { type: "page", title: "Machinery", titleAr: "الآلات", description: "Loaders and feeding technology for agriculture and construction", descriptionAr: "اللوادر وتكنولوجيا التغذية للزراعة والبناء", href: "/industries/machinery", tags: ["machinery", "loaders", "feeding", "agriculture", "construction"] },

  // === GLASS INDUSTRY PARTNERS ===
  { type: "partner", title: "Futronic GmbH (Bucher Automation)", description: "Electronic controls & automation for glass industry — Germany", href: "/industries/glass", external: false, industry: "Glass", tags: ["futronic", "bucher", "automation", "electronic controls", "blow machine", "press machine", "servo", "IS machine", "germany", "glass"] },
  { type: "partner", title: "Zhongfu-Silica", description: "Silica bricks & refractories for glass furnaces — China", href: "/industries/glass", industry: "Glass", tags: ["zhongfu", "silica", "bricks", "refractories", "glass furnace", "china", "insulating", "mortar"] },
  { type: "partner", title: "Lingnan-AZS (LingNan Refractory)", description: "AZS fused cast refractories for glass melting — China", href: "/industries/glass", industry: "Glass", tags: ["lingnan", "azs", "fused cast", "alumina", "zircon", "glass melting", "china", "refractory", "electrode"] },
  { type: "partner", title: "Refmon Co. Ltd.", description: "Refractory & monolithic solutions — Hungary", href: "/industries/glass", external: false, industry: "Glass", tags: ["refmon", "hungary", "refractory", "monolithic", "corundum", "mullite", "fireclay", "insulation", "glass", "steel"] },
  { type: "partner", title: "UAS Messtechnik GmbH", description: "Measurement, control & combustion technology — Germany", href: "/industries/glass", external: false, industry: "Glass", tags: ["uas", "messtechnik", "measurement", "combustion", "temperature", "oxyfire", "siemens", "germany", "glass level"] },
  { type: "partner", title: "Hotwork International AG", description: "Furnace services & combustion technology — Switzerland", href: "/industries/glass", external: false, industry: "Glass", tags: ["hotwork", "furnace", "heat-up", "draining", "combustion", "hydrogen", "switzerland", "glass", "aluminium"] },
  { type: "partner", title: "Accuramech Industrial Engineering", description: "Precision spare parts for hollow glass industry — India", href: "/industries/glass", external: false, industry: "Glass", tags: ["accuramech", "spare parts", "IS machine", "hollow glass", "bottle", "india", "mechanisms", "repair kits"] },
  { type: "partner", title: "Interglass", description: "Glass-forming lubricants — Mexico", href: "/industries/glass", external: false, industry: "Glass", tags: ["interglass", "lubricants", "swabbing", "shear spray", "delivery oils", "IS machine", "glass-forming", "mexico", "interlub"] },
  { type: "partner", title: "Heat Applications India", description: "Furnace heat-up & combustion services — India", href: "/industries/glass", external: false, industry: "Glass", tags: ["heat applications", "furnace", "heat-up", "combustion", "india", "hotwork group"] },
  { type: "partner", title: "WBT Srl", description: "Conveyor belts & IS machine components — Italy", href: "/industries/glass", external: false, industry: "Glass", tags: ["wbt", "conveyor", "belts", "chains", "gears", "shear blades", "IS machine", "italy"] },

  // === MACHINERY PARTNERS ===
  { type: "partner", title: "Schaeffer Maschinenfabrik GmbH", description: "Compact & telescopic wheeled loaders — Germany", href: "/industries/machinery", industry: "Machinery", tags: ["schaeffer", "loader", "compact", "telescopic", "wheeled", "agriculture", "dairy", "construction", "electric", "germany"] },
  { type: "partner", title: "BvL Maschinenfabrik GmbH & Co. KG", description: "Feeding & bedding technology for dairy/livestock — Germany", href: "/industries/machinery", industry: "Machinery", tags: ["bvl", "van lengerich", "feeding", "mixer", "fodder", "straw blower", "bedding", "dairy", "livestock", "germany", "farm"] },
  { type: "partner", title: "Interlub S.A. de C.V. (Interlub Group)", description: "Aluminum extrusion lubricants — Mexico", href: "/industries/glass", industry: "Glass & Aluminum", tags: ["interlub", "lubricant", "aluminum", "extrusion", "die lubricant", "mexico", "billet", "container", "puller pad"] },

  // === CERAMICS PRODUCTS ===
  { type: "product", title: "Kaolin", description: "High-quality kaolin for ceramic body formulations and specialty ceramics", href: "/industries/ceramics", industry: "Ceramics", tags: ["kaolin", "clay", "ceramic", "body", "paper coating", "mineral"] },
  { type: "product", title: "Bentonite", description: "Bentonite for binding, plasticity, and green strength in ceramic bodies", href: "/industries/ceramics", industry: "Ceramics", tags: ["bentonite", "binding", "plasticity", "green strength", "ceramic"] },
  { type: "product", title: "Feldspar", description: "Sodium and potassium feldspar for ceramic and glass formulations", href: "/industries/ceramics", industry: "Ceramics", tags: ["feldspar", "sodium", "potassium", "flux", "ceramic", "glass"] },
  { type: "product", title: "Deflocculants & Dispersants", description: "Custom deflocculant systems for slip casting, spray drying, and glazing", href: "/industries/ceramics", industry: "Ceramics", tags: ["deflocculant", "dispersant", "slip", "casting", "spray drying", "glazing", "rheology"] },
  { type: "product", title: "CMC (Carboxy Methyl Cellulose)", description: "CMC for glaze suspension and application in ceramic production", href: "/industries/ceramics", industry: "Ceramics", tags: ["cmc", "carboxy methyl cellulose", "glaze", "suspension", "ceramic"] },
  { type: "product", title: "Ceramic Binders & Strength Enhancers", description: "Binders for MOR improvement, dry and green strength in tile and sanitaryware", href: "/industries/ceramics", industry: "Ceramics", tags: ["binder", "strength", "MOR", "tile", "sanitaryware", "pressing"] },
  { type: "product", title: "Coatings, Glazes & Additives", description: "Surface treatment solutions for ceramic and porcelain tiles", href: "/industries/ceramics", industry: "Ceramics", tags: ["coating", "glaze", "additive", "surfactant", "digital printing", "tile", "porcelain"] },
  { type: "product", title: "Refractory Binders & Plasticizers", description: "Specialized binders and plasticizers for refractory castables and shapes", href: "/industries/ceramics", industry: "Ceramics", tags: ["refractory", "binder", "plasticizer", "castable", "monolithic"] },
  { type: "product", title: "Superplasticizer for Concrete", description: "PCE-based admixtures for high-performance concrete production", href: "/industries/ceramics", industry: "Construction", tags: ["superplasticizer", "concrete", "PCE", "polycarboxylate", "admixture", "construction"] },
  { type: "product", title: "Superplasticizer for Refractory", description: "Superplasticizers reducing water demand in refractory applications", href: "/industries/ceramics", industry: "Ceramics", tags: ["superplasticizer", "refractory", "water reduction", "workability"] },
  { type: "product", title: "Accelerator for Concrete", description: "Setting and hardening accelerators for fast-track construction", href: "/industries/ceramics", industry: "Construction", tags: ["accelerator", "concrete", "setting", "hardening", "fast-track", "construction"] },
  { type: "product", title: "Flocculant for Mining Industry", description: "Solid-liquid separation solutions for mineral processing and tailings", href: "/industries/ceramics", industry: "Mining", tags: ["flocculant", "mining", "separation", "mineral processing", "tailings"] },

  // === CEMENT PRODUCTS ===
  { type: "product", title: "MGC Magnesia Bricks for Cement Kilns", description: "High-quality MGC magnesia bricks for cement rotary kiln lining", href: "/industries/cement", industry: "Cement", tags: ["mgc", "magnesia", "bricks", "cement", "kiln", "burning zone", "refractory", "spinel", "chrome", "dolomite"] },
  { type: "product", title: "Grinding Aids for Cement", description: "Advanced grinding aids to improve mill efficiency and reduce energy consumption", href: "/industries/cement", industry: "Cement", tags: ["grinding aid", "cement", "mill", "energy", "clinker", "glycol", "amine", "OPC", "PPC"] },
  { type: "product", title: "Refractory Solutions for Cement Plants", description: "Complete refractory lining for preheater, calciner, cooler, and kiln", href: "/industries/cement", industry: "Cement", tags: ["refractory", "cement", "preheater", "calciner", "cooler", "castable", "insulation", "lining"] },

  // === SERVICES ===
  { type: "service", title: "Engineering Consulting", description: "Expert technical advice for ceramics, glass, cement, and machinery industries", href: "/about", tags: ["consulting", "engineering", "technical", "advice", "expert"] },
  { type: "service", title: "Product Customization", description: "Tailored solutions to match your specific manufacturing requirements", href: "/contact", tags: ["customization", "custom", "tailored", "specific", "requirements"] },
  { type: "service", title: "After-Sales Support", description: "Ongoing technical support and maintenance guidance for all products", href: "/contact", tags: ["support", "after-sales", "maintenance", "technical", "guidance"] },
];

const typeIcons = {
  partner: Building2,
  product: Package,
  page: FileText,
  service: ArrowRight,
};

const typeLabels = {
  partner: { en: "Partner", ar: "شريك" },
  product: { en: "Product", ar: "منتج" },
  page: { en: "Page", ar: "صفحة" },
  service: { en: "Service", ar: "خدمة" },
};

const typeColors = {
  partner: "bg-teal/10 text-teal",
  product: "bg-amber-500/10 text-amber-600",
  page: "bg-navy/10 text-navy",
  service: "bg-emerald-500/10 text-emerald-600",
};

interface SearchDialogProps {
  open: boolean;
  onClose: () => void;
}

export default function SearchDialog({ open, onClose }: SearchDialogProps) {
  const [query, setQuery] = useState("");
  const [selectedIndex, setSelectedIndex] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);
  const resultsRef = useRef<HTMLDivElement>(null);
  const [, navigate] = useLocation();
  const { lang } = useLanguage();

  const results = useMemo(() => {
    if (!query.trim()) return [];
    const q = query.toLowerCase().trim();
    const words = q.split(/\s+/);

    return searchIndex
      .map((item) => {
        const searchableText = [
          item.title,
          item.titleAr || "",
          item.description,
          item.descriptionAr || "",
          item.industry || "",
          ...item.tags,
        ]
          .join(" ")
          .toLowerCase();

        // Score: how many words match
        let score = 0;
        for (const word of words) {
          if (searchableText.includes(word)) {
            score += 1;
            // Bonus for title match
            if (item.title.toLowerCase().includes(word)) score += 2;
            // Bonus for exact tag match
            if (item.tags.some((t) => t.toLowerCase() === word)) score += 1;
          }
        }
        return { item, score };
      })
      .filter((r) => r.score > 0)
      .sort((a, b) => b.score - a.score)
      .slice(0, 12)
      .map((r) => r.item);
  }, [query]);

  useEffect(() => {
    setSelectedIndex(0);
  }, [results]);

  useEffect(() => {
    if (open) {
      setQuery("");
      setTimeout(() => inputRef.current?.focus(), 100);
    }
  }, [open]);

  // Scroll selected item into view
  useEffect(() => {
    if (resultsRef.current) {
      const selected = resultsRef.current.children[selectedIndex] as HTMLElement;
      if (selected) {
        selected.scrollIntoView({ block: "nearest" });
      }
    }
  }, [selectedIndex]);

  const handleSelect = useCallback(
    (item: SearchItem) => {
      onClose();
      setQuery("");
      if (item.external && item.href.startsWith("http")) {
        window.open(item.href, "_blank");
      } else {
        navigate(item.href);
      }
    },
    [onClose, navigate]
  );

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === "ArrowDown") {
        e.preventDefault();
        setSelectedIndex((prev) => Math.min(prev + 1, results.length - 1));
      } else if (e.key === "ArrowUp") {
        e.preventDefault();
        setSelectedIndex((prev) => Math.max(prev - 1, 0));
      } else if (e.key === "Enter" && results[selectedIndex]) {
        e.preventDefault();
        handleSelect(results[selectedIndex]);
      } else if (e.key === "Escape") {
        onClose();
      }
    },
    [results, selectedIndex, handleSelect, onClose]
  );

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-[100] flex items-start justify-center pt-[10vh] sm:pt-[15vh]">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-navy/60 backdrop-blur-sm"
        onClick={onClose}
      />

      {/* Dialog */}
      <div
        className="relative w-full max-w-2xl mx-4 bg-white rounded-xl shadow-2xl shadow-navy/30 border border-navy/10 overflow-hidden"
        role="dialog"
        aria-modal="true"
        aria-label="Search"
      >
        {/* Search input */}
        <div className="flex items-center gap-3 px-5 border-b border-navy/10">
          <Search className="w-5 h-5 text-navy/40 shrink-0" />
          <input
            ref={inputRef}
            type="text"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder={lang === "ar" ? "ابحث عن شركاء، منتجات، خدمات..." : "Search partners, products, services..."}
            className="w-full py-4 text-base text-navy bg-transparent outline-none placeholder:text-navy/35"
            autoComplete="off"
          />
          {query && (
            <button
              onClick={() => setQuery("")}
              className="p-1 hover:bg-navy/5 rounded transition-colors"
            >
              <X className="w-4 h-4 text-navy/40" />
            </button>
          )}
          <kbd className="hidden sm:inline-flex items-center gap-0.5 px-2 py-1 text-[10px] font-mono text-navy/40 bg-navy/5 rounded border border-navy/10 shrink-0">
            ESC
          </kbd>
        </div>

        {/* Results */}
        <div ref={resultsRef} className="max-h-[50vh] overflow-y-auto">
          {query.trim() && results.length === 0 && (
            <div className="px-5 py-12 text-center">
              <Search className="w-10 h-10 text-navy/15 mx-auto mb-3" />
              <p className="text-navy/50 text-sm">
                {lang === "ar"
                  ? `لا توجد نتائج لـ "${query}"`
                  : `No results found for "${query}"`}
              </p>
              <p className="text-navy/30 text-xs mt-1">
                {lang === "ar"
                  ? "جرّب البحث بكلمات مختلفة"
                  : "Try searching with different keywords"}
              </p>
            </div>
          )}

          {results.map((item, i) => {
            const Icon = typeIcons[item.type];
            const label = typeLabels[item.type][lang];
            const colorClass = typeColors[item.type];

            return (
              <button
                key={`${item.type}-${item.title}-${i}`}
                onClick={() => handleSelect(item)}
                className={`w-full flex items-start gap-3 px-5 py-3.5 text-left transition-colors ${
                  i === selectedIndex
                    ? "bg-teal/5 border-l-2 border-teal"
                    : "border-l-2 border-transparent hover:bg-navy/[0.02]"
                }`}
              >
                <div className={`p-2 rounded-lg shrink-0 mt-0.5 ${colorClass}`}>
                  <Icon className="w-4 h-4" />
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <span className="font-heading font-semibold text-sm text-navy truncate">
                      {lang === "ar" && item.titleAr ? item.titleAr : item.title}
                    </span>
                    {item.industry && (
                      <span className="text-[10px] bg-navy/5 text-navy/50 px-1.5 py-0.5 rounded-full shrink-0">
                        {item.industry}
                      </span>
                    )}
                    {item.external && (
                      <ExternalLink className="w-3 h-3 text-navy/30 shrink-0" />
                    )}
                  </div>
                  <p className="text-xs text-navy/50 mt-0.5 truncate">
                    {lang === "ar" && item.descriptionAr ? item.descriptionAr : item.description}
                  </p>
                </div>
                <span className={`text-[10px] font-medium px-2 py-0.5 rounded-full shrink-0 mt-1 ${colorClass}`}>
                  {label}
                </span>
              </button>
            );
          })}
        </div>

        {/* Footer hints */}
        {query.trim() && results.length > 0 && (
          <div className="px-5 py-2.5 border-t border-navy/5 bg-navy/[0.02] flex items-center justify-between">
            <div className="flex items-center gap-3 text-[10px] text-navy/35">
              <span className="flex items-center gap-1">
                <kbd className="px-1.5 py-0.5 bg-navy/5 rounded border border-navy/10 font-mono">↑↓</kbd>
                {lang === "ar" ? "تنقل" : "Navigate"}
              </span>
              <span className="flex items-center gap-1">
                <kbd className="px-1.5 py-0.5 bg-navy/5 rounded border border-navy/10 font-mono">↵</kbd>
                {lang === "ar" ? "اختر" : "Select"}
              </span>
            </div>
            <span className="text-[10px] text-navy/30">
              {results.length} {lang === "ar" ? "نتيجة" : results.length === 1 ? "result" : "results"}
            </span>
          </div>
        )}

        {/* Empty state - show categories */}
        {!query.trim() && (
          <div className="px-5 py-6">
            <p className="text-xs text-navy/40 mb-3 font-medium uppercase tracking-wider">
              {lang === "ar" ? "بحث سريع" : "Quick Search"}
            </p>
            <div className="flex flex-wrap gap-2">
              {[
                { label: lang === "ar" ? "زجاج" : "Glass", q: "glass" },
                { label: lang === "ar" ? "سيراميك" : "Ceramics", q: "ceramics" },
                { label: lang === "ar" ? "أسمنت" : "Cement", q: "cement" },
                { label: lang === "ar" ? "آلات" : "Machinery", q: "machinery" },
                { label: "Schaeffer", q: "schaeffer" },
                { label: "BvL", q: "bvl" },
                { label: lang === "ar" ? "حراريات" : "Refractories", q: "refractory" },
                { label: lang === "ar" ? "طحن" : "Grinding Aid", q: "grinding" },
                { label: lang === "ar" ? "لوادر" : "Loaders", q: "loader" },
              ].map((chip) => (
                <button
                  key={chip.q}
                  onClick={() => setQuery(chip.q)}
                  className="px-3 py-1.5 text-xs text-navy/60 bg-navy/5 hover:bg-teal/10 hover:text-teal rounded-full transition-colors"
                >
                  {chip.label}
                </button>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
