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

interface Mesa {
  id_mesa: number;
  nombre?: string;
}

interface Props {
  id_cuenta: number;
}

function Mesas({ id_cuenta }: Props) {
  const [mesas, setMesas] = useState<Mesa[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!id_cuenta) return;

    setLoading(true);

    axios
      .get(`/cuenta/${id_cuenta}`)
      .then((res) => {
        setMesas(res.data);
      })
      .catch((err) => console.error(err))
      .finally(() => setLoading(false));
  }, [id_cuenta]);

  if (loading) return <p>Cargando mesas...</p>;

  return (
    <div>
      <h3>Mesas asignadas</h3>

      {mesas.length === 0 ? (
        <p>No hay mesas</p>
      ) : (
        <ul>
          {mesas.map((mesa) => (
            <li key={mesa.id_mesa}>
              Mesa {mesa.id_mesa} {mesa.nombre && `- ${mesa.nombre}`}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

export default function SearchMesa() {
  const [inputValue, setInputValue] = useState("");
  const [idCuenta, setIdCuenta] = useState<number | null>(null);
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  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="number"
            placeholder="Coloca el numero de mesa"
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
          />

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