import AsignacionMesas from "@/app/Components/AsignacionMesas";
import CheckBoxMesa from "@/app/Components/CheckBoxMesa";
import Information from "@/app/Components/Global/Information/information";
import SearchUser from "@/app/Components/Global/SearchUser/searchUser";
import ShowError from "@/app/Components/Global/ShowError";
import Toggle from "@/app/Components/Global/Toggle/Toggle";

import { GetRegisterStudent } from "@/app/lib/getRegisterStudent";
import { GetRegisterStudentSancion } from "@/app/lib/GetRegisterStudentSancion";
import TableTable from "../Monitor/TableTable";

import './asignacion.css'

export default async function Page(props: {
  searchParams?: Promise<{
    key?: string;
    numAcount?: string;
    table?: number
  }>;
}) {
  const params = await props.searchParams;
  const key = params?.key;
  const numAcount = params?.numAcount ?? null;
  const table = params?.table ?? null;

  let student: any = null;
  let platica: any = null;
  let inscripcion: any[] = [];
  let errorMessage = "";

  if (numAcount) {
    const idCuenta = parseInt(numAcount);

    const result = await GetRegisterStudentSancion(idCuenta);
    if (result.error) {
      errorMessage = `${result.error}`;
    } else {
      student = result[0]?.alumno as Student;
      const rawPlatica = result[0]?.platica;
      platica =
        rawPlatica?.type === "Buffer"
          ? Boolean(rawPlatica.data[0])
          : Boolean(rawPlatica);
    }


    const inscResult = await GetRegisterStudent(idCuenta);
    if (!inscResult.error && Array.isArray(inscResult)) {
      inscripcion = inscResult;
    } else {
      inscripcion = [];
    }
  }

  return (
    <section className="containerSection">
      {errorMessage && <ShowError key={Date.now()} message={errorMessage} />}

      <h2 className="title"> ASIGNACIÓN DE MESAS </h2>

      <div className="asignacion">
        <Toggle
          defaultView={key}
          options={[
            {
              key: "Asignar",
              label: "Asignar mesa",
              content: (
                <>
                  <SearchUser value={numAcount} />

                  {student && (
                    <>
                      <div>
                        <Information
                          NoCuenta={student.id_cuenta}
                          nombre={student.nombre}
                        />
                      </div>

                      <AsignacionMesas
                        idCuenta={student.id_cuenta}
                        inscripcion={inscripcion}
                      />
                    </>
                  )}
                </>
              ),
            },
            {
              key: "Liberar",
              label: "Cancelar mesa",
              content: <CheckBoxMesa numAcount={numAcount} table={table} />,
            },
          ]}
        />
        <div className="tableTable">
          <TableTable />
        </div>
      </div>
    </section>
  );
}
