import useFilterRecordsByUser from "@/hooks/useFilterRecordsByUser";
import { Group, Stat, StudentUser, User } from "@/interfaces/user";
import { useRouter } from "next/router";
import { BsChevronLeft } from "react-icons/bs";
import { mapBy, serialize } from "@/utils";
import { withIronSessionSsr } from "iron-session/next";
import { getUsersWithStats } from "@/utils/users.be";
import { sessionOptions } from "@/lib/session";
import { checkAccess, findAllowedEntities } from "@/utils/permissions";
import { getEntitiesWithRoles } from "@/utils/entities.be";
import { Entity } from "@/interfaces/entity";
import { getParticipantsGroups } from "@/utils/groups.be";
import StudentPerformanceList from "../(admin)/Lists/StudentPerformanceList";
import Head from "next/head";
import { ToastContainer } from "react-toastify";
import { requestUser } from "@/utils/api";
import { redirect } from "@/utils";

export const getServerSideProps = withIronSessionSsr(async ({ req, res }) => {
  const user = await requestUser(req, res);
  if (!user) return redirect("/login");

  const entityIDs = mapBy(user.entities, "id");

  const entities = await getEntitiesWithRoles(
    checkAccess(user, ["admin", "developer"]) ? undefined : entityIDs
  );
  const allowedEntities = findAllowedEntities(
    user,
    entities,
    "view_student_performance"
  );
  if (allowedEntities.length === 0) return redirect("/");

  const students = await (checkAccess(user, ["admin", "developer"])
    ? getUsersWithStats(
        { type: "student" },
        {
          id: 1,
          entities: 1,
          focus: 1,
          email: 1,
          name: 1,
          levels: 1,
          userStats: 1,
          studentID: 1,
        }
      )
    : getUsersWithStats(
        { type: "student", "entities.id": { in: mapBy(entities, "id") } },
        {
          id: 1,
          entities: 1,
          focus: 1,
          email: 1,
          name: 1,
          levels: 1,
          userStats: 1,
          studentID: 1,
        }
      ));
  const groups = await getParticipantsGroups(mapBy(students, "id"));

  return {
    props: serialize({ user, students, entities, groups }),
  };
}, sessionOptions);

interface Props {
  user: User;
  students: (StudentUser & { userStats: Stat[] })[];
  entities: Entity[];
  groups: Group[];
}

const StudentPerformance = ({ students, entities, groups }: Props) => {
  const router = useRouter();

  const performanceStudents = students.map((u) => ({
    ...u,
    group: groups.find((x) => x.participants.includes(u.id))?.name || "N/A",
    entitiesLabel: (u.entities || []).reduce((acc, curr, idx) => {
      const entity = entities.find((e) => e.id === curr.id);
      if (idx === 0) return entity ? entity.label : "";
      return acc + (entity ? `${entity.label}` : "");
    }, ""),
  }));

  return (
    <>
      <Head>
        <title>EnCoach</title>
        <meta
          name="description"
          content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
        />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <ToastContainer />
      <>
        <div className="flex items-center gap-2">
          <button
            onClick={() => {
              router.back();
            }}
            className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl"
          >
            <BsChevronLeft />
          </button>
          <h2 className="font-bold text-2xl">
            Student Performance ({students.length})
          </h2>
        </div>
        <StudentPerformanceList items={performanceStudents} />
      </>
    </>
  );
};

export default StudentPerformance;
