"use client";

import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";

interface urlProp {
  value: string | null;
}

export default function SearchMesa(props: urlProp) {
  const [inputValue, setInputValue] = useState("");
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

    useEffect(() => {
      if (props.value) {
        setInputValue(props.value);
      }
  
      if(props.value===null){
        setInputValue("")
      }
    }, [props.value]);

  const buscar = (e: React.FormEvent) => {
    e.preventDefault();
    const params = new URLSearchParams(searchParams.toString());
    if (inputValue) {
      params.set("table", `${inputValue}`);
      router.push(`${pathname}?${params.toString()}`);
    }
  };

  return (
    <>
      <form className="containerForm" onSubmit={buscar}>
        <label>Numero de mesa</label>

        <div className="groupInput">
          <input
            type="text"
            placeholder="Coloca el numero de mesa"
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
          />

          <button type="submit" className="button buttonSearch">
            Buscar
          </button>
        </div>
      </form>
    </>
  );
}
