import SearchUser from "@/app/Components/Global/SearchUser/searchUser";
import Toggle from "@/app/Components/Global/Toggle/Toggle";

import CheckBoxEquipo from "@/app/Components/CheckBoxEquipo";
import Information from "@/app/Components/Global/Information/information";
import ShowError from "@/app/Components/Global/ShowError";
import Table from "@/app/Components/Global/table";

import { envConfig } from "@/app/lib/config";
import { GetRegisterStudent } from "@/app/lib/getRegisterStudent";
import PlaticaGate from "./PlaticaGate";
import "@/app/globals.css";

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

    if (!res.ok) {
      throw new Error(`Error ${res.status}: ${res.statusText}`);
    }

    return await res.json();
  } catch (error: any) {
    return { error: error.message || "No se pudo cargar la inscripción" };
  }
}

const headers = ["Inscrito", "Tiempo", "Confirmó"];

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

  let student: any = null;
  let platica: any = null;
  let inscripcion: any = null;
  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 = [];
    }
  }

  const tableData = Array.isArray(inscripcion)
    ? inscripcion.map((ins) => ({
        Inscrito: ins.plataforma?.nombre || "—",
        Tiempo: ins.tiempo_disponible
          ? `${ins.tiempo_disponible} minutos`
          : "—",
        Confirmó: ins.platica.data?.[0] === 1 ? "sí" : "no",
      }))
    : [];

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

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

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

                {student && (
                  <>
                    <div>
                      <Information
                        NoCuenta={student.id_cuenta}
                        nombre={student.nombre}
                      />
                      <Table headers={headers} data={tableData} />
                    </div>

                    <PlaticaGate
                      inscripcion={inscripcion}
                      numAcount={student.id_cuenta}
                    />
                  </>
                )}
              </>
            ),
          },
          {
            key: "Liberar",
            label: "Cancelar tiempo",
            content: (
              <>
                <CheckBoxEquipo numAcount={params?.numAcount} machine={params?.machine} />
              </>
            ),
          },
        ]}
      />
    </section>
  );
}
//IO
