"use client";
import { useState, useEffect, useRef } from "react";
import Image from "next/image";
import Link from "next/link";
import GetStartedModal from "@/components/getstartedmodal";
import products from "@/lib/data/products.json";
import useClickOutside from "@/lib/hooks/useclickoutside";
import { searchProducts } from "@/lib/utils/searchProducts"; // <-- new import

export default function Header() {
  const [main, setMain] = useState(false);
  const [search, setSearch] = useState(false);
  const [lang, setLang] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const [isDesktop, setIsDesktop] = useState(false);
  const [showModal, setShowModal] = useState(false);

  // NEW: State for search term
  const [searchTerm, setSearchTerm] = useState("");

  // Refs
  const mainRef = useRef(null);
  const langDropdownRef = useRef(null);
  const searchRef = useRef(null);

  useClickOutside(mainRef, () => setMain(false));
  useClickOutside(langDropdownRef, () => setLang(false));
  useClickOutside(searchRef, () => {
    setSearchTerm("");
    if (!isDesktop) setSearch(false);
  });

  useEffect(() => {
    const handleScroll = () => {
      requestAnimationFrame(() => setScrolled(window.scrollY > 50));
    };
    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  useEffect(() => {
    const mediaQuery = window.matchMedia("(min-width: 1280px)");
    const handleMediaQueryChange = (e) => {
      setIsDesktop(e.matches);
      setSearch(e.matches); // Always show search on desktop, hide on mobile
    };
    handleMediaQueryChange(mediaQuery);
    mediaQuery.addEventListener("change", handleMediaQueryChange);
    return () => mediaQuery.removeEventListener("change", handleMediaQueryChange);
  }, []);

  // Extract unique types
  const types = [...new Set(products.map((p) => p.types))];
  const [selectedTypes, setSelectedTypes] = useState(types[0] || "");

  // Latest products for selected type (existing functionality)
  const filteredProducts = products
    .filter((p) => p.types === selectedTypes)
    .slice(-5)
    .reverse();

  useEffect(() => {
    const handleRouteChange = () => {
      setMain(false);
    };
    window.addEventListener("routeChangeComplete", handleRouteChange);
    return () => window.removeEventListener("routeChangeComplete", handleRouteChange);
  }, []);

  // NEW: Get search results using our utility function
  const searchResults = searchProducts(products, searchTerm);

  return (
    <>
      <GetStartedModal isOpen={showModal} onClose={() => setShowModal(false)} />
      <header className={`banner fixed mx-auto top-0 z-30 w-full bg-gradient-to-b from-white to-transparent transition duration-500 ease-in-out ${scrolled ? "hide" : ""}`}>
        {/* Top Bar */}
        <div className="topbar mx-auto hidden max-w-screen-2xl px-5 sm:px-8 lg:block lg:px-10">
          <div className="flex h-12 flex-row items-center justify-between gap-10 text-sm">
            {/* Language Dropdown */}
            <div className="relative flex flex-row items-center justify-end">
              <button onClick={() => setLang(!lang)} className="flex flex-row items-center">
                <span>English</span>
                <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 24 24" className="size-4 shrink-0">
                  <path d="M18.71 8.21a1 1 0 0 0-1.42 0l-4.58 4.58a1.001 1.001 0 0 1-1.42 0L6.71 8.21a1 1 0 1 0-1.42 1.41l4.59 4.59a3 3 0 0 0 4.24 0l4.59-4.59a1 1 0 0 0 0-1.41Z" />
                </svg>
              </button>
              {lang && (
                <div ref={langDropdownRef} className="absolute left-0 top-7 z-40 flex w-44 flex-col gap-4 rounded-lg border border-slate-300 bg-white p-5">
                  <Link href="">English</Link>
                  <Link className="hidden" href="">
                    Bahasa Indonesia
                  </Link>
                </div>
              )}
            </div>
            {/* Warranty and Shipping Info */}
            <div className="col-span-2 flex flex-row items-center justify-center gap-12">
              {/* Warranty */}
              <div className="flex flex-row items-center gap-2">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" className="size-5 shrink-0">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M9 12.75 11.25 15 15 9.75m-3-7.036A11.959 11.959 0 0 1 3.598 6 11.99 11.99 0 0 0 3 9.749c0 5.592 3.824 10.29 9 11.623 5.176-1.332 9-6.03 9-11.622 0-1.31-.21-2.571-.598-3.751h-.152c-3.196 0-6.1-1.248-8.25-3.285Z" />
                </svg>
                <span>
                  2 Years <span className="font-medium">Warranty</span>
                </span>
              </div>
              {/* Free Installation */}
              <div className="flex flex-row items-center gap-2">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" className="size-5 shrink-0">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M21.75 6.75a4.5 4.5 0 0 1-4.884 4.484c-1.076-.091-2.264.071-2.95.904l-7.152 8.684a2.548 2.548 0 1 1-3.586-3.586l8.684-7.152c.833-.686.995-1.874.904-2.95a4.5 4.5 0 0 1 6.336-4.486l-3.276 3.276a3.004 3.004 0 0 0 2.25 2.25l3.276-3.276c.256.565.398 1.192.398 1.852Z" />
                </svg>
                <span>
                  Free <span className="font-medium">Installation</span>
                </span>
              </div>
            </div>
          </div>
        </div>
        {/* Main Header */}
        <div ref={mainRef} className="w-full mx-auto max-w-screen-2xl">
          <div className="relative z-30 mx-auto w-full px-2 pt-2 sm:px-3 sm:pt-3 lg:px-10 lg:pt-0">
            <div className="flex h-16 flex-row items-center justify-between gap-6 rounded-xl border border-black/5 bg-white/80 px-3 backdrop-blur-sm lg:gap-12">
              {/* Logo and Menu Button */}
              <div className="flex shrink-0 flex-row items-center gap-4 lg:gap-6">
                <button onClick={() => setMain(!main)} className="flex size-10 cursor-pointer items-center justify-center rounded-lg border border-slate-200 transition duration-100 ease-in-out hover:border-slate-300">
                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 18" fill="currentColor" className="size-5 shrink-0">
                    <g>
                      <path className={`origin-top-left transition duration-500 ease-in-out ${main ? "rotate-45 translate-x-1 translate-y-[1px]" : ""}`} d="M0 0H20V2H0V0Z" />
                      <path className={`origin-bottom-left transition duration-500 ease-in-out ${main ? "-rotate-45 translate-x-1 -translate-y-[1px]" : ""}`} d="M0 16H20V18H0V16Z" />
                      <path className={`transition duration-300 ease-in-out ${main ? "opacity-0" : "opacity-100"}`} d="M0 8H20V10H0V8Z" />
                    </g>
                  </svg>
                </button>
                <Link href="/" onClick={() => setMain(false)} className="flex items-center">
                  <Image src="/assets/img/logo-verola-black.svg" alt="logo" width={0} height={0} sizes="100vw" style={{ width: "auto", height: "20px" }} />
                </Link>
              </div>
              {/* Navigation Links */}
              <div className="hidden grow flex-row items-center gap-12 font-medium lg:flex">
                <Link className="flex flex-row items-center gap-2 text-[#E27A00]" href="/inspirations">
                  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" className="size-6 shrink-0">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M9.813 15.904 9 18.75l-.813-2.846a4.5 4.5 0 0 0-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 0 0 3.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 0 0 3.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 0 0-3.09 3.09ZM18.259 8.715 18 9.75l-.259-1.035a3.375 3.375 0 0 0-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 0 0 2.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 0 0 2.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 0 0-2.456 2.456ZM16.894 20.567 16.5 21.75l-.394-1.183a2.25 2.25 0 0 0-1.423-1.423L13.5 18.75l1.183-.394a2.25 2.25 0 0 0 1.423-1.423l.394-1.183.394 1.183a2.25 2.25 0 0 0 1.423 1.423l1.183.394-1.183.394a2.25 2.25 0 0 0-1.423 1.423Z" />
                  </svg>
                  <span>Inspirations</span>
                </Link>
                <Link href="/projects" onClick={() => setMain(false)}>
                  Projects
                </Link>
                <button
                  onClick={() => {
                    setShowModal(true);
                    setMain(false);
                  }}
                >
                  Verola for Business
                </button>
              </div>
              {/* Search Bar */}
              <div ref={searchRef} onClick={() => setMain(false)} className="mr-3 flex flex-row items-center justify-end gap-5 sm:gap-6 xl:mr-0">
                {/* Search Icon Button (mobile only) */}
                <button onClick={() => setSearch((prev) => !prev)} className="xl:hidden">
                  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" className="size-6 shrink-0">
                    <path strokeLinecap="round" strokeLinejoin="round" d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z" />
                  </svg>
                </button>
                {/* Search Input & Results */}
                {search && (
                  <div className="absolute right-0 top-[72px] w-dvw max-w-full sm:max-w-[360px] z-40 flex flex-col gap-4 rounded-xl bg-white p-3 shadow-lg xl:relative xl:right-auto xl:top-auto xl:bg-transparent xl:p-0 xl:shadow-none" onClick={(e) => e.stopPropagation()}>
                    <input className="h-10 w-full appearance-none rounded-lg border-none bg-white/50 bg-search bg-4 bg-left bg-no-repeat bg-origin-content px-5 indent-6 text-base outline-none ring-1 ring-inset ring-slate-300 transition duration-100 ease-in-out placeholder:text-sm placeholder:text-slate-400 focus:ring-inset focus:ring-slate-400" type="text" placeholder="Search Products" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} />
                    {searchTerm.trim() && (
                      <div className="xl:p-5 w-full xl:rounded-xl   max-h-[calc(100dvh-180px)] xl:bg-white xl:shadow-lg overflow-y-auto xl:absolute xl:top-[62px]">
                        <div className="w-full flex pb-4 text-xs   text-slate-400 flex-col gap-4">
                          {searchResults.length === 0 ? (
                            <p className="text-sm">Sorry, we couldn't find any results</p>
                          ) : (
                            searchResults.map((product) => (
                              <Link
                                key={product.slug}
                                href={`/products/${product.slug}`}
                                onClick={() => {
                                  setSearchTerm("");
                                  if (!isDesktop) setSearch(false);
                                }}
                                className="grid-cols-4 grid gap-4"
                              >
                                <Image src={product.images[0]} alt={product.title} width={120} height={120} className="aspect-square w-full border border-slate-200 rounded-md shrink-0 object-contain" />
                                <div className="col-span-3 justify-between h-full flex flex-col">
                                  <div className="flex flex-col">
                                    <p>{product.types}</p>
                                    <p className="text-base font-bold text-slate-800">{product.title}</p>
                                  </div>
                                  <div className="flex flex-row gap-2 justify-between">
                                    <p>{product.category}</p>
                                    <p>Brand: {product.brand}</p>
                                  </div>
                                </div>
                              </Link>
                            ))
                          )}
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>
          {/* Main Navigation Menu */}
          {main && (
            <nav className={`${main ? "opacity-100 translate-y-0" : "opacity-0 translate-y-10"} relative lg:mx-auto z-40 w-dvw max-w-[400px] lg:w-full lg:max-w-screen-2xl`}>
              <div className="flex flex-col gap-8 px-2 pt-2 sm:px-3 sm:pt-3 lg:px-10">
                <div className=" flex max-h-[calc(100dvh-100px)] flex-col gap-10 overflow-y-auto overscroll-y-none rounded-lg border border-black/5 bg-white p-8 py-10 shadow-sm lg:h-fit lg:max-h-dvh lg:min-h-0 lg:flex-row lg:p-10 transition-all duration-1000 ease-in-out">
                  {/* Menu Content */}
                  <div className="flex flex-col gap-10 lg:grow">
                    {/* Modified Dynamic Tabs */}
                    <div className="flex flex-col items-start gap-6 text-base font-semibold lg:flex-row lg:items-center lg:gap-10">
                      {types.map((type) => (
                        <div key={type} className="group relative">
                          {isDesktop ? (
                            // Desktop: Button with click handler
                            <button onClick={() => setSelectedTypes(type)} className="flex flex-row items-center gap-4 lg:gap-0">
                              <span className={selectedTypes === type ? "text-green-500" : ""}>{type}</span>
                              <div className={`absolute -bottom-2 hidden h-[2px] transform bg-green-500 duration-200 ease-in-out lg:block ${selectedTypes === type ? "w-full" : "w-0"}`} />
                            </button>
                          ) : (
                            // Mobile: Link with href
                            <Link href={`/products?types=${encodeURIComponent(type)}`} onClick={() => setMain(false)} className="flex flex-row items-center gap-4 lg:gap-0">
                              <span className={selectedTypes === type ? "text-green-500" : ""}>{type}</span>
                              <div className={`absolute -bottom-2 hidden h-[2px] transform bg-green-500 duration-200 ease-in-out lg:block ${selectedTypes === type ? "w-full" : "w-0"}`} />
                            </Link>
                          )}
                        </div>
                      ))}
                    </div>

                    {/* Latest Products */}
                    <div className="hidden flex-col gap-10 lg:flex">
                      <div className="flex flex-wrap gap-x-10 gap-y-6 overflow-hidden lg:max-h-[200px] lg:gap-12">
                        {filteredProducts.map((product) => (
                          <Link key={product.slug} className="flex relative w-[120px] flex-col" href={`/products/${product.slug}`} onClick={() => setMain(false)}>
                            <Image src={product.images[0]} alt={product.title} width={120} height={120} className="aspect-square w-full shrink-0 object-contain" />
                            <span className="mt-4 text-xs font-semibold text-center">{product.title}</span>
                            {product.isNew && <div className="absolute right-0 top-0 flex h-5 items-center rounded-md bg-green-500 px-1.5 text-xs text-white">New</div>}
                          </Link>
                        ))}
                      </div>

                      <Link className="flex w-fit flex-row items-center gap-1" href={`/products?types=${encodeURIComponent(selectedTypes)}`} onClick={() => setMain(false)}>
                        See All {selectedTypes}
                        <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 24 24" className="size-5 shrink-0">
                          <path d="M18 12a2 2 0 0 0-.59-1.4l-4.29-4.3a1 1 0 1 0-1.41 1.42L15 11H5a1 1 0 1 0 0 2h10l-3.29 3.29a1 1 0 1 0 1.41 1.42l4.29-4.3A2 2 0 0 0 18 12Z" />
                        </svg>
                      </Link>
                    </div>
                  </div>
                  {/* Additional Links */}
                  <div className="h-px w-full shrink-0 bg-slate-800/10 lg:h-auto lg:min-h-full lg:w-px" />
                  <div className="flex flex-col items-start gap-6 lg:hidden">
                    <Link className="flex flex-row items-center gap-2 text-[#E27A00]" href="/inspirations" onClick={() => setMain(false)}>
                      <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 24 24" className="size-5 shrink-0">
                        <path d="M18 9.064a3.05 3.05 0 0 0-.9-2.164 3.14 3.14 0 0 0-4.334 0L.9 18.769A3.064 3.064 0 0 0 5.23 23.1L17.1 11.231a3.045 3.045 0 0 0 .9-2.167ZM3.816 21.688a1.087 1.087 0 0 1-1.5 0 1.062 1.062 0 0 1 0-1.5l7.769-7.77 1.505 1.505-7.774 7.765ZM15.688 9.816 13 12.505 11.5 11l2.689-2.688a1.063 1.063 0 1 1 1.5 1.5l-.001.004ZM4.863 2.855l1.55-.442.442-1.55a1.191 1.191 0 0 1 2.29 0l.442 1.55 1.55.442a1.19 1.19 0 0 1 0 2.29l-1.55.442-.442 1.55a1.191 1.191 0 0 1-2.29 0l-.442-1.55-1.55-.442a1.19 1.19 0 0 1 0-2.29Zm18.274 14.29-1.55.442-.442 1.55a1.19 1.19 0 0 1-2.29 0l-.442-1.55-1.55-.442a1.19 1.19 0 0 1 0-2.29l1.55-.442.442-1.55a1.19 1.19 0 0 1 2.29 0l.442 1.55 1.55.442a1.19 1.19 0 0 1 0 2.29ZM17.755 2.5l1.356-.387L19.5.755a1.042 1.042 0 0 1 2 0l.387 1.356 1.356.387a1.042 1.042 0 0 1 0 2l-1.356.387-.387 1.359a1.042 1.042 0 0 1-2 0l-.387-1.355-1.358-.389a1.042 1.042 0 0 1 0-2Z" />
                      </svg>
                      <span>Inspirations</span>
                    </Link>
                    <Link href="/projects" onClick={() => setMain(false)}>
                      Projects
                    </Link>
                    <button
                      onClick={() => {
                        setShowModal(true);
                        setMain(false);
                      }}
                    >
                      Verola for Business
                    </button>
                  </div>
                  <div className="h-px w-full shrink-0 bg-slate-800/10 lg:h-auto lg:min-h-full lg:w-px lg:hidden" />
                  <div className="flex shrink-0 flex-col gap-6 text-sm lg:w-[160px] lg:gap-4">
                    <Link className="hidden" href="/about" onClick={() => setMain(false)}>
                      About Verola
                    </Link>
                    <Link className="hidden" href="/contact" onClick={() => setMain(false)}>
                      Contact Us
                    </Link>
                    <Link className="my-2 flex h-8 w-fit flex-row items-center gap-2 rounded-lg border border-slate-800/20 px-3 text-xs font-semibold" href="/warranty" onClick={() => setMain(false)}>
                      <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 24 24" className="size-4 shrink-0">
                        <path d="M8.965 24H4a4 4 0 0 1-4-4v-5a4 4 0 0 1 4-4h8.857a3.144 3.144 0 0 1 2.69 1.519l3.217-3.535a3.01 3.01 0 0 1 4.254-.2 3.022 3.022 0 0 1 .217 4.23l-6.8 7.637A10.013 10.013 0 0 1 8.965 24ZM4 13a2 2 0 0 0-2 2v5a2 2 0 0 0 2 2h4.965a8.006 8.006 0 0 0 5.972-2.678l6.805-7.638a1.015 1.015 0 0 0-.072-1.421c-.2-.18-.46-.273-.728-.263a1 1 0 0 0-.7.329L15.816 15.2a3.158 3.158 0 0 1-2.516 2.052l-5.161.738a1 1 0 1 1-.284-1.98l5.162-.737a1.142 1.142 0 0 0-.16-2.273H4Zm7-3.926a1.986 1.986 0 0 1-1.247-.436C8.041 7.264 6 5.2 6 3.2A3.109 3.109 0 0 1 9 0a2.884 2.884 0 0 1 2 .817A2.884 2.884 0 0 1 13 0a3.109 3.109 0 0 1 3 3.2c0 2-2.041 4.064-3.754 5.439A1.986 1.986 0 0 1 11 9.074ZM9 2a1.115 1.115 0 0 0-1 1.2c0 .9 1.151 2.39 3.006 3.879C12.849 5.59 14 4.1 14 3.2A1.115 1.115 0 0 0 13 2a1.115 1.115 0 0 0-1 1.2 1 1 0 0 1-2 0A1.115 1.115 0 0 0 9 2Z" />
                      </svg>
                      <span>Warranty Care</span>
                    </Link>
                  </div>
                </div>
              </div>
            </nav>
          )}
        </div>
      </header>
    </>
  );
}
