"use client";

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

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

export default function TableTable() {
  const [mesas, setMesas] = useState<Mesa[]>([]);
  const [loading, setLoading] = useState(true);

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

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

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

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

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

  return (
    <div className={styles.tableContainer}>
      <table className={styles.machineTable}>
        <thead>
          <tr>
            <th>ID Mesa</th>
            <th>Disponible</th>
          </tr>
        </thead>

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