import SearchUser from "@/app/Components/Global/SearchUser/searchUser";
import Information from "@/app/Components/Global/Information/information";
import ShowError from "@/app/Components/Global/ShowError";
import Table from "@/app/Components/Global/table";
import Inscripcion from "@/app/Components/Receipt/Inscripcion";

import Link from "next/link";
import { GetRegisterStudent } from "@/app/lib/getRegisterStudent";
import { GetStudentWhitoutSancion } from "@/app/lib/getStudentWhitoutSancion";

import "./inscripcion.css";

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

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

  let student: any = null;
  let inscripcion: any = null;
  let errorMessage = "";
  let isSancionado = false;

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

    const studentResult = await GetStudentWhitoutSancion(idCuenta);
    if (studentResult.error) {
      errorMessage = `${studentResult.error}`;

      if (studentResult.status === 403) {
        isSancionado = true;
      }

    } else {
      student = studentResult;
    }

    const inscResult = await GetRegisterStudent(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",
    }))
    : [];

  const plataformasInscritas = Array.isArray(inscripcion)
    ? inscripcion.map((ins) => ins.plataforma?.nombre)
    : [];

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

      <h2 className="title"> INSCRIPCIÓN </h2>

      <div className="containeInformation">
        <div className="firstPartInformation">
          <SearchUser value={numAcount} />

          {student && (
            <>
              <Information
                NoCuenta={student.id_cuenta}
                Nombre={student.nombre}
                Carrera={student.carrera.carrera}
                Credito={student.credito}
              />
            </>
          )}
          {!student && numAcount && !isSancionado && (
            <Link href={`/Alta?numAcount=${numAcount}`}>
              <button
                className="button buttonSearch"
                style={{ marginTop: "1rem" }}
              >
                Alta Usuario
              </button>
            </Link>
          )}
        </div>

        {student && (
          <>
            <Table headers={headers} data={tableData} />
            <button className="button buttonSearch restarPass">
              Restablecer contraseña
            </button>
          </>
        )}
      </div>

      {student && (
        <section className="inscripcion">
          <Inscripcion
            numAcount={student.id_cuenta}
            plataformasInscritas={plataformasInscritas}
          />
        </section>
      )}
    </section>
  );
}
