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

export default function SearchBoxRedesignThree() {
  const t = useTranslations("navbar");
  const { currencyShortname, rate } = useCurrency();
  const [searchResults, setSearchResults] = useState([]);
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [inputValue, setInputValue] = useState("");

  // Function to perform the actual search (e.g., API call)
  const performSearch = async (query) => {
    setIsLoading(true);
    const response = await fetchData({
      endPoint: `/search?term=${query}`,
    });
    setIsLoading(false);
    // Filter results based on numeric keys
    const data = Object.keys(response)
      .filter((key) => !isNaN(key))
      .map((key) => response[key]);
    setSearchResults(data);
  };

  useEffect(() => {
    const timer = setTimeout(() => {
      performSearch(inputValue);
    }, 500);

    return () => clearTimeout(timer);
  }, [inputValue]);

  return (
    <div className="grow relative flex items-center gap-2">
      <div className="grow ">
        {/* Search Input */}
        <input
          type="search"
          placeholder={t("search")}
          className="form-control h-10 bg-white text-black placeholder:text-black rounded-sm placeholder:text-sm border-main"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          onFocus={() => setIsDropdownOpen(true)}
          onBlur={() => {
            setTimeout(() => setIsDropdownOpen(false), 200);
          }}
        />
        {/* 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>
      {/* Search Button */}
      <button className="flex items-center justify-center w-32 h-10 bg-secondary rounded-sm text-main text-2xl font-semibold">
        {t("search-btn")}
      </button>
    </div>
  );
}
