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

import Link from "next/link";
import "./inscripcion.css";

if (!envConfig.apiUrl) {
  console.error("API URL is not defined in envConfig");
}

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<{
    numAcount: string;
  }>;
}) {
  const params = await props.searchParams;
  const numAcount = params?.numAcount ? params.numAcount : null;

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

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

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

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

  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 && (
            <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>
  );
}
