"use client";
import React from "react";
import {Field} from "./ui/field";
import {Input} from "./ui/input";
import {useRouter, useSearchParams} from "next/navigation";
import {Label} from "./ui/label";

export default function SearchBox({
  placeholder,
  label,
  hasLabel=false,
  queryName,
  inputName,
  route,
}: {
  placeholder?: string;
  queryName?: string;
  inputName: string;
  label?:string,
  hasLabel?:boolean
  route: string;
}) {
  const router = useRouter();
  const urlSearchParams = useSearchParams();
  const searchParams = new URLSearchParams(urlSearchParams);
  const debounce = (onChange: (v: string) => void) => {
    let timeout: ReturnType<typeof setTimeout>;
    return (e: React.ChangeEvent<HTMLInputElement>) => {
      const form = e.currentTarget.value;
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        onChange(form);
      }, 1000);
    };
  };
  const handleSearch = async (value: string) => {
    try {
      searchParams.set(`${queryName ?? inputName}`, value);
      router.push(
        `/${route}${searchParams ? `?${searchParams.toString()}` : ""} `
      );
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  return (
    <>
      <Field className="w-[300px] flex flex-row justify-start items-center gap-x-3 ">
        {hasLabel && <Label htmlFor={inputName} className="!w-fit">{label}</Label>}
        <Input
        id={inputName}
          onChange={debounce((e) => {
            handleSearch(e);
          })}
          defaultValue={searchParams.get(`${queryName ?? inputName}`) ?? ""}
          name={inputName}
          className="bg-white w-[240px] flex-1"
        />
      </Field>
    </>
  );
}
