"use client";
import { useCurrency } from "@/stores/currency-state";
import { useTranslations } from "next-intl";
import Link from "next/link";
import { useDeferredValue, useEffect, useState } from "react";
import { IoSearch } from "react-icons/io5";


export default function SearchBox() {
  const [query, setQuery] = useState('');
  const deferredQuery = useDeferredValue(query);
  const [searchResults, setSearchResults] = useState([]);
  const { currencyShortname, rate } = useCurrency();
  const t = useTranslations('navbar');

  useEffect(() => {
    (async () => {
      const response = await fetch(`${process.env.NEXT_PUBLIC_ENDPOINT}/search?term=${deferredQuery}`);
      const data = await response.json();
      setSearchResults(data);
    })();
  }, [deferredQuery]);

  return (
    <div className="relative ">
      <IoSearch
        className="text-main absolute start-2 top-1/2 -translate-y-1/2"
        size={22}
      />
      <input
        type="search"
        placeholder={t('search')}
        className="form-control px-8 placeholder:text-sm placeholder:!text-main focus:ring-2 focus:ring-main focus:border-[#F0E9E9]"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />

      {query && (
        <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>{t('search-notfound-result', { query })}</li>
            }
          </ul>
        </div>
      )}
    </div>
  );
}