"use client";
import logo from "@/public/assets/header/headerlogo.svg";
import searchImage from "@/public/assets/icons/search-normal.svg";
import { useLocale, useTranslations } from "next-intl";
import Image from "next/image";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { ChangeEvent, useState, useEffect, useRef } from "react";
import { useQuery } from "@tanstack/react-query";
import apiServiceCall from "@/lib/apiServiceCall";
import normalSearch from "@/public/assets/icons/searchwhite.svg";
import primeSearch from "@/public/assets/icons/primarysearch.svg";
import { useSearchParams } from "next/navigation";
import menux from "@/public/assets/icons/menunavs.svg";
import OverLay from "../modify/OverLay";
import close from "../../../public/assets/icons/close1.svg";
import SearchBox from "../modify/SearchBox";

const Header2 = ({ locale }: any) => {
  const [open, setOpen] = useState(false);
  const pathname = usePathname();

  const segments = pathname.split("/").filter(Boolean);
  const isHome =
    segments.length === 0 || (segments.length === 1 && segments[0] === locale);
  const [showSearch, setShowSearch] = useState(isHome);
  // Logic: Always show icon. Show input if home page or toggled on other pages.
  const shouldShowInput = isHome || showSearch;
  // TODO: get categories from api and set ids here
  const links = [
    { id: 1, title: "Home", path: `/${locale}` },
    {
      id: 2,
      title: "Ready to Move",
      path: `/${locale}/1/filter?category_id=1`,
    },
    { id: 3, title: "Off Plan", path: `/${locale}/2/filter?category_id=2` },
    { id: 4, title: "Best Deals", path: `/${locale}/3/filter?category_id=3` },
    { id: 5, title: "Developers", path: `/${locale}/developers` },
    { id: 6, title: "About Us", path: `/${locale}/about-us` },
  ];

  const t = useTranslations("Header");
  const router = useRouter();

  const searchParams = useSearchParams();

  const search = searchParams.get("category_id");
  const oppositeLocale = locale === "ar" ? "en" : "ar";
  const newPath = `/${oppositeLocale}${pathname.replace(/^\/(en|ar)/, "")}`;
  const currentPage = "/" + pathname.split("/").slice(2).join("/");
  const [searchTerm, setSearchTerm] = useState("");
  const [openLangMenu, setOpenLangMenu] = useState(false);
  const [showResults, setShowResults] = useState(false);
  const searchTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const searchResultsRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Close dropdown when clicking outside
    const handleClickOutside = (event: MouseEvent) => {
      if (
        searchResultsRef.current &&
        !searchResultsRef.current.contains(event.target as Node)
      ) {
        setShowResults(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  // Debounce function for search
  const handleSearchChange = (e: ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setSearchTerm(value);

    // Clear previous timeout
    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }

    // Set new timeout (300ms debounce)
    searchTimeoutRef.current = setTimeout(() => {
      if (value.trim().length >= 2) {
        refetchSearchData();
        setShowResults(true);
      } else {
        setShowResults(false);
      }
    }, 300);
  };

  // Clear timeout on component unmount
  useEffect(() => {
    return () => {
      if (searchTimeoutRef.current) {
        clearTimeout(searchTimeoutRef.current);
      }
    };
  }, []);

  const handleLangChange = (e: ChangeEvent<HTMLSelectElement>) => {
    const newLocale = e.target.value as string;
    const path = pathname.split("/").slice(2).join("/");

    router.push(`/${newLocale}/${path}`);
  };

  const [openSearch, setOpenSearch] = useState(false);
  const handleOpenandClose = () => {
    setOpenSearch((p) => !p);
  };

  const {
    data: searchData,
    isLoading: isSearchLoading,
    refetch: refetchSearchData,
  } = useQuery({
    queryKey: ["search", searchTerm],
    queryFn: async () => {
      return apiServiceCall({
        url: `search?search=${encodeURIComponent(searchTerm)}`,
        method: "GET",
        headers: {
          "Accept-language": locale,
        },
      });
    },
    enabled: false, // Don't run on mount, only when refetch is called
  });

  return (
    <>
      <div
        className="shadow-[0px_8px_18px_0px_rgba(0,_0,_0,_0.1)] relative z-[500]"
        data-aos="fade-down"
        data-aos-duration="1500"
        data-aos-delay="100"
      >
        <div className="container w-full mx-auto h-[100px] flex items-center justify-between lg:px-[35px]  ">
          <Link href={`/${locale}`} className="hidden lg:flex">
            <Image alt="logo" src={logo} className="w-[87px] h-[62px] " />
          </Link>
          <div className="hidden lg:flex items-center gap-[25px] xl:gap-[40px] 2xl:gap-[50px]">
            {links.map((item) => {
              const isActive =
                pathname === item.path ||
                pathname + "?category_id=" + search === item.path;

              return (
                <Link
                  href={`${item.path}`}
                  key={item.id}
                  className={` text-[15px] xl:text-[18px] font-extralight text-dark hover:text-primary  ${
                    isActive ? "text-primary font-light" : "text-dark"
                  } `}
                >
                  {t(item.title)}
                  <div className="flex justify-center items-center">
                    <span
                      className={` ${
                        isActive ? "border-b-2 border-primary w-[25px]" : ""
                      } `}
                    ></span>
                  </div>
                </Link>
              );
            })}

            <div className="relative text-dark cursor-pointer text-[18px] font-extralight hover:text-primary z-[1001]">
              <a href={newPath}>{oppositeLocale.toUpperCase()}</a>
            </div>
          </div>
          <div className="relative hidden lg:flex flex-row-reverse items-center border-b border-bo-color z-[1001]">
            {/* Always visible search icon */}
            <div
              className={` ${
                !isHome && !shouldShowInput
                  ? "flex items-center justify-center absolute w-[54px] h-[54px] border rounded-full "
                  : ""
              }`}
              onClick={() => {
                if (!isHome) setShowSearch((prev) => !prev);
              }}
            >
              <Image
                alt="search"
                src={searchImage}
                className={`w-[20px] h-[20px] cursor-pointer flex items-start ${
                  locale === "ar" ? "rotate-[-270deg]" : ""
                } `}
                width={20}
                height={20}
              />
            </div>

            {/* Conditionally visible input */}
            {shouldShowInput && (
              <input
                type="text"
                placeholder={t("Search")}
                className="p-3.5 text-black"
                value={searchTerm}
                onChange={handleSearchChange}
                onFocus={() =>
                  searchTerm.trim().length > 2 && setShowResults(true)
                }
                data-aos={`${locale === "ar" ? "fade-right" : "fade-left"}`}
                data-aos-duration="1500"
                data-aos-delay="100"
              />
            )}

            {/* Search results dropdown with proper z-index */}
            {showResults && searchData?.data?.length > 0 && (
              <div
                ref={searchResultsRef}
                className="absolute top-full left-0 w-full bg-white shadow-lg rounded-md mt-1 z-[9999] max-h-60 overflow-y-auto border border-gray-200"
              >
                {searchData?.data?.map((item: any, index: number) => {
                  const url =
                    item.type === "developers"
                      ? `developers/${item.slug}`
                      : item.type === "properties"
                      ? `properties/${item.slug}`
                      : item.type === "blogs"
                      ? `blogs/${item.slug}`
                      : "";

                  return (
                    <div
                      key={index}
                      className="p-3 text-black hover:bg-gray-100 cursor-pointer border-b border-gray-100 last:border-b-0 transition-colors duration-200"
                      onClick={() => {
                        router.push(`/${locale}/${url}`);
                        setShowResults(false);
                        setSearchTerm("");
                      }}
                    >
                      <p className="text-sm font-medium">{item.name}</p>
                      <p className="text-xs text-gray-500 capitalize">
                        {item.type}
                      </p>
                    </div>
                  );
                })}
              </div>
            )}
          </div>

          {/* Mobile search and menu bar */}
          <div className="flex justify-between w-full p-4 md:px-12 lg:hidden inset-0 z-30">
            <Link href={`/${locale}`}>
              <Image
                src={logo}
                alt="logo"
                className="w-[48px] h-[34px]"
                priority
                fetchPriority="high"
              />
            </Link>

            <div className="flex gap-6 flex-col">
              <div className="flex gap-6">
                <div className="w-[24px] h-[24px] ">
                  {openSearch ? (
                    <Image
                      src={close}
                      alt="close"
                      className="w-[24px] h-[24px] "
                      onClick={handleOpenandClose}
                    />
                  ) : (
                    <Image
                      src={searchImage}
                      onClick={handleOpenandClose}
                      alt="search"
                      className="w-[24px] h-[24px]"
                    />
                  )}
                </div>
                <div
                  className="cursor-pointer w-[24px] h-[24px]"
                  onClick={() => setOpen(true)}
                >
                  <Image src={menux} alt="menu" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <SearchBox
        openSearch={openSearch}
        searchC={handleOpenandClose}
        locale={locale}
      />
      <OverLay open={open} setOpen={setOpen} locale={locale} />
    </>
  );
};

export default Header2;
