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

export default function StyleFiveSearchBox() {
  const locale = useLocale();
  const t = useTranslations("navbar");
  const { currencyShortname, rate } = useCurrency();

  const [searchTerm, setSearchTerm] = useState("");
  const [searchResults, setSearchResults] = useState([]);
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  // Debounce function
  const debounce = (func, delay) => {
    let timeout;
    return (...args) => {
      clearTimeout(timeout);
      timeout = setTimeout(() => func(...args), delay);
    };
  };

  const fetchSearchResults = async () => {
    try {
      setIsLoading(true);
      const response = await fetchData({
        endPoint: `/search?term=${searchTerm}`,
      });

      // Filter results based on numeric keys
      const data = Object.keys(response)
        .filter((key) => !isNaN(key))
        .map((key) => response[key]);

      setSearchResults(data);
    } catch (error) {
      console.error("Error fetching search results:", error);
      setSearchResults([]); // Optionally show a message for error handling
    } finally {
      setIsLoading(false);
    }
  };

  const debouncedFetchSearchResults = useRef(debounce(fetchSearchResults, 300));

  useEffect(() => {
    if (searchTerm) {
      debouncedFetchSearchResults.current();
    } else {
      setSearchResults([]);
    }
  }, [searchTerm]);

  const handleInputChange = (e) => {
    const value = e.target.value;
    setSearchTerm(value);
    setIsDropdownOpen(value.length > 0); // Open dropdown when there is input
  };

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

  return (
    <div className="relative grow">
      {/* Search Input */}
      <input
        type="search"
        placeholder={t("search")}
        className="form-control bg-white text-black placeholder:text-black border-white border-[3px] rounded-sm placeholder:text-sm focus:ring-2 focus:ring-white focus:border-white"
        value={searchTerm}
        onChange={handleInputChange}
        onBlur={handleBlur}
        onFocus={() => setIsDropdownOpen(searchTerm.length > 0)}
      />

      {/* Search Button */}
      <button className="p-4 m-1 absolute top-0 bottom-0 end-0 bg-secondary rounded-sm text-white text-xl font-semibold flex items-center justify-center">
        <FaSearch className="text-white" />
      </button>

      {/* Dropdown Results */}
      {isDropdownOpen && (
        <div className="absolute left-0 right-0 mt-2 text-black rounded-sm bg-white border border-gray-300 shadow-lg z-10 max-h-80 overflow-y-auto">
          <ul className="py-2">
            {isLoading ? (
              <li className="px-4 py-2 text-gray-500 flex items-center justify-center">
                <FaSpinner className="animate-spin" />
              </li>
            ) : searchResults.length > 0 ? (
              searchResults.map((result, index) => (
                <li
                  key={index}
                  className="px-4 py-2 hover:bg-gray-200 hover:rounded-sm cursor-pointer"
                >
                  <Link
                    href={`/products/${result.id}`}
                    className="block space-y-1"
                  >
                    {/* Result Title */}
                    <p className="line-clamp-1">{result.title}</p>

                    {/* Result Cost */}
                    <p className="text-black 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">
                {t("search-notfound-result")}
              </li>
            )}
          </ul>
        </div>
      )}
    </div>
  );
}
