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

import { GetRegisterStudent } from "@/app/lib/getRegisterStudent";

import "./addTime.css";
import AddTime from "./Addtime";
import Table from "@/app/Components/Global/table";

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

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

  let student = 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;
      inscripcion = result;
    }
  }

  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",
      }))
    : [];

  const plataformasInscritas = inscripcion.map((ins) => ins.plataforma?.nombre);

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

      <h2 className="title">AGREGAR TIEMPO</h2>

      <div className="containeInformationTime">
        <div className="firstPartInformationTime">
          <SearchUser value={numAcount} />
          {student && (
            <>
              <Information
                NoCuenta={student.id_cuenta}
                Nombre={student.nombre}
              />

              <AddTime
                numAcount={student.id_cuenta}
                plataformasInscritas={plataformasInscritas}
              />
            </>
          )}
        </div>

        {student && <Table headers={headers} data={tableData} />}
      </div>
    </section>
  );
}
//IO
