"use client";
import fetchData from "@/api/fetch-data";
import { Input } from "@/components/ui/input";
import { useCurrency } from "@/stores/currency-state";
import { useLocale, useTranslations } from "next-intl";
import Link from "next/link";
import { useState, useEffect } from "react";
import { FaSpinner } from "react-icons/fa";
import { IoSearch } from "react-icons/io5";

{
  /* EDITED BY :MOHAMMED HOSSAM */
}
{
  /* DATE :11-9-2024 */
}
{
  /* DESC :ADDED LOADER WHEN REQUESTING DATA*/
}
export default function StyleFourSearchBox() {
  const locale = useLocale();
  const [searchTerm, setSearchTerm] = useState("");
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const [searchResults, setSearchResults] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const { currencyShortname, rate } = useCurrency();
  const t = useTranslations("navbar");

  const handleInputChange = (e) => {
    const value = e.target.value;
    setSearchTerm(value);
    setIsDropdownOpen(value.length > 0); // Open dropdown if there's input
  };
  // Assuming `response` is the data you received from the API
  const handleResponseData = (response) => {
    // Filter only the entries with numeric keys and ignore others
    const resultsArray = Object.keys(response)
      .filter((key) => !isNaN(key)) // Keep only numeric keys
      .map((key) => response[key]); // Map to array

    return resultsArray;
  };
  // handled search results
  async function handleSearchResults() {
    setIsLoading(true);
    const response = await fetchData({
      endPoint: `/search?term=${searchTerm}`,
      locale,
    });
    const data = handleResponseData(response);
    setIsLoading(false);
    setSearchResults(data);
  }
  useEffect(() => {
    if (searchTerm) {
      // Fetch search results from API
      handleSearchResults();
    } else {
      setSearchResults([]);
    }
  }, [searchTerm]);

  const handleBlur = () => {
    setTimeout(() => setIsDropdownOpen(false), 150);
  };

  return (
    <div className="relative grow">
      <div className="absolute start-2 top-1/2 -translate-y-1/2  flex items-center justify-center ">
        <IoSearch className="text-main" size={22} />
      </div>
      <input
        type="search"
        placeholder={t("search")}
        className="form-control bg-transparent border-gray-300 ps-10 rounded-md placeholder:text-sm focus:ring-2 focus:ring-main focus:border-[#F0E9E9]"
        value={searchTerm}
        onChange={handleInputChange}
        onBlur={handleBlur}
        onFocus={() => setIsDropdownOpen(searchTerm.length > 0)}
      />
      {isDropdownOpen && (
        <div className="absolute left-0 right-0 mt-2 bg-white border border-gray-300 shadow-lg z-10 max-h-80 overflow-y-auto">
          <ul className="py-2">
            {searchResults.length > 0 ? (
              searchResults.map((result, index) => (
                <li
                  key={index}
                  className="px-4 py-2 hover:bg-gray-100 cursor-pointer"
                >
                  <Link
                    href={`/products/${result.id}`}
                    className="block space-y-1"
                  >
                    <p className="line-clamp-1">{result.title}</p>
                    <p className="text-main font-semibold">
                      {parseFloat(result.cost * rate).toFixed(2)}{" "}
                      <span className="text-xs font-medium text-black ">
                        {currencyShortname}
                      </span>
                    </p>
                  </Link>
                </li>
              ))
            ) : (
              <li className="px-4 py-2 text-gray-500">
                {isLoading ? (
                  <FaSpinner className="animate-spin  " />
                ) : (
                  t("search-notfound-result")
                )}
              </li>
            )}
          </ul>
        </div>
      )}
    </div>
  );
}
