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 { envConfig } from "@/app/lib/config";
import { GetRegisterStudent } from "@/app/lib/getRegisterStudent";

async function getInscripcion(idCuenta: number) {
  try {
    const res = await fetch(`${envConfig.apiUrl}/alumno-inscrito/${idCuenta}`, {
      cache: "no-store",
    });

    if (!res.ok) throw new Error("Error al cargar inscripción");
    return await res.json();
  } catch (error: any) {
    return { error: error.message };
  }
}

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 GetRegisterStudent(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);
      console.log(result);
    }
    

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

  return (
    <section className="containerSection">
      {errorMessage && <ShowError message={errorMessage} />}

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

      <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} />,
          },
        ]}
      />
    </section>
  );
}
