"use client";

import { useEffect, useState } from "react";
import styles from "../Monitor/Page.module.css";
import axios from "axios";
import Cookies from "js-cookie";

type Mesa = {
  id_mesa: number;
  ocupado: number;
};

export default function TableMesas() {
  const [mesas, setMesas] = useState<Mesa[]>([]);
  const [loading, setLoading] = useState(true);
  const [refresh, setRefresh] = useState<boolean>(false)

  const token = Cookies.get("token");
  const headers = { Authorization: `Bearer ${token}` };

  const fetchMesas = async () => {
    setLoading(true);
    try {
      const res = await axios.get(
        `${process.env.NEXT_PUBLIC_API_URL}/mesa/usoWhitout`,
        { headers },
      );

      setMesas(res.data);
    } catch (error) {
      console.error("Error cargando mesas:", error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMesas();
    setRefresh(false)
  }, [refresh]);

  if (loading) {
    return (
      <div className={styles.tableContainer}>
        <table className={styles.machineTable}>
          <thead>
            <tr>
              <th>Cargando mesas...</th>
            </tr>
          </thead>
        </table>
      </div>
    )
  }

  return (
    <>
      <button className="button buttonCancel" onClick={() => { setRefresh(true) }}>Actualizar informacion</button>
      <div className={styles.tableContainer}>
        <table className={styles.machineTable}>
          <thead>
            <tr>
              <th>ID Mesa</th>
            </tr>
          </thead>

          <tbody>
            {mesas.map((mesa) => (
              <tr key={mesa.id_mesa} className={!mesa.ocupado ? '' : styles.ocupado}>
                <td>{mesa.id_mesa}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}