"use client";
import Image from "next/image";
import { useRouter } from "next/navigation";
import React, { useState } from "react";
import RoundedInput from "@/components/elements/RoundedInput";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

function SearchFilter() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const [searchText, setSearchText] = useState<string>("");

  const handleFilterChange = () => {
    if (!searchText) {
      toast.error(t("searchPage.emptyQuery"));
    } else {
      const currentQuery = new URLSearchParams(window.location.search);
      currentQuery.set("search", searchText);
      currentQuery.set("type", "user");
      router.push(`/search?${currentQuery.toString()}`);
    }
  };

  return (
    <div className="px-4">
      <div className="flex items-center justify-between relative text-sm gap-3 max-w-md mx-auto">
        <div className="w-full relative">
          <RoundedInput
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter") {
                e.preventDefault();
                handleFilterChange();
              }
            }}
            placeholder={t("searchPage.placeholder")}
            className="w-full"
          />
          <Image
            onClick={() => handleFilterChange()}
            width={25}
            height={25}
            alt={t("searchPage.searchAria")}
            src="/images/icons/search-normal.svg"
            className="min-w-[25px] absolute left-3 top-[7px] cursor-pointer"
          />
        </div>
      </div>
    </div>
  );
}

export default SearchFilter;
