import React, { useState, useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { IoSearch } from "react-icons/io5";
import { useLocation, useNavigate } from "react-router-dom";

interface Props {
  placeholder: string;
  searchBy: string;
}

const SearchField: React.FC<Props> = ({ placeholder, searchBy }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState<string>("");
  const location = useLocation();
  const navigate = useNavigate();
  const inputRef = useRef<HTMLInputElement>(null);
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);

  const DEBOUNCE_DELAY = 500; // Adjust the debounce delay as needed

  useEffect(() => {
    const searchParams = new URLSearchParams(location.search);
    setSearchQuery(searchParams.get(searchBy) || "");
  }, [location.search, searchBy]);

  const handleInputChange = (value: string) => {
    setSearchQuery(value);

    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }

    timeoutRef.current = setTimeout(() => {
      if (value.trim() !== "") {
        navigate(`${location.pathname}?${searchBy}=${value.trim()}`);
      } else {
        const params = new URLSearchParams(location.search);
        params.delete(searchBy);
        navigate(`${location.pathname}`);
      }
    }, DEBOUNCE_DELAY);
  };

  const handleToggleDropdown = () => {
    setIsOpen(!isOpen);
  };

  const handleClickOutside = (event: MouseEvent) => {
    if (inputRef.current && !inputRef.current.contains(event.target as Node)) {
      setIsOpen(false);
    }
  };

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

  const [t] = useTranslation();
  return (
    <div className={`search-field ${isOpen ? "open" : ""}`}>
      <div className="search-header" onClick={handleToggleDropdown}>
        <IoSearch className="search__icon" />
        <input
          ref={inputRef}
          type="text"
          className="search__input"
          placeholder={t(placeholder)}
          value={searchQuery}
          onChange={(e) => handleInputChange(e.target.value)}
        />
      </div>
    </div>
  );
};

export default SearchField;
