"use client";

import { useEffect, useState } from "react";
import { envConfig } from "@/app/lib/config";
import axios from "axios";
import Swal from "sweetalert2";
import Cookies from "js-cookie";

interface Mesa {
  id_mesa: number;
  activo: number;
}

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

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

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

  const obtenerMesas = async () => {
    try {
      const response = await axios.get(`${envConfig.apiUrl}/mesa`,{ headers });
      setMesas(response.data);
    } catch (error) {
      console.error("Error al obtener mesas:", error);
    } finally {
      setLoading(false);
    }
  };

  const toggleEquipo = async (id_mesa: number) => {
    try {

      await axios.patch(
        `${envConfig.apiUrl}/mesa/${id_mesa}/activo`,
        {},
        { headers },
      );

      setMesas((prev) =>
        prev
          ? prev.map((e) =>
            e.id_mesa === id_mesa
              ? {
                ...e,
                activo: e.activo === 1 ? 0 : 1,
              }
              : e
          )
          : prev
      );
    } catch (error: any) {
      Swal.fire({
        title: "Error al cambiar estado",
        text: error.response?.data?.message || error.message,
        icon: "error",
      });
    }
  };

  return (
    <section className="containerSection">
      <div
        style={{
          overflow: "auto",
          height: "430px",
          width: "100%",
          scrollbarColor: "#2563eb white",
        }}
      >
        {loading ? (
          <p>Cargando mesas...</p>
        ) : (
          <table>
            <thead>
              <tr style={{ fontSize: "15px" }}>
                <th>Mesa</th>
                <th>Activo</th>
              </tr>
            </thead>
            <tbody>
              {mesas &&
                mesas.map((mesa) => {
                  const isActivo = mesa.activo === 1;

                  return (
                    <tr key={mesa.id_mesa}>
                      <td>Mesa {mesa.id_mesa}</td>

                      <td
                        style={{
                          display: "flex",
                          alignItems: "center",
                          gap: "8px",
                          justifyContent: "center",
                        }}
                      >
                        <span>{isActivo ? "Sí" : "No"}</span>
                        <input
                          type="checkbox"
                          checked={isActivo}
                          style={{ height: "2.5rem", maxWidth: "50px" }}
                          onChange={() => toggleEquipo(mesa.id_mesa)}
                        />
                      </td>
                    </tr>
                  );
                })}
            </tbody>
          </table>
        )}
      </div>
    </section>
  );
}