import { Assignment } from "@/interfaces/results";
import { CorporateUser, Group, User } from "@/interfaces/user";
import { getUserCompanyName } from "@/resources/user";
import {
  activeAssignmentFilter,
  archivedAssignmentFilter,
  futureAssignmentFilter,
  pastAssignmentFilter,
  startHasExpiredAssignmentFilter,
} from "@/utils/assignments";
import clsx from "clsx";
import { groupBy } from "lodash";
import { useState } from "react";
import { BsArrowLeft, BsArrowRepeat, BsPlus } from "react-icons/bs";
import AssignmentCard from "../AssignmentCard";
import AssignmentCreator from "../AssignmentCreator";
import AssignmentView from "../AssignmentView";

interface Props {
  assignments: Assignment[];
  corporateAssignments?: ({ corporate?: CorporateUser } & Assignment)[];
  groups: Group[];
  users: User[];
  isLoading: boolean;
  user: User;
  onBack: () => void;
  reloadAssignments: () => void;
}

export default function AssignmentsPage({
  assignments,
  corporateAssignments,
  user,
  groups,
  users,
  isLoading,
  onBack,
  reloadAssignments,
}: Props) {
  const [selectedAssignment, setSelectedAssignment] = useState<Assignment>();
  const [isCreatingAssignment, setIsCreatingAssignment] = useState(false);

  const displayAssignmentView = !!selectedAssignment && !isCreatingAssignment;

  const assignmentsPastExpiredStart = assignments.filter(startHasExpiredAssignmentFilter);

  return (
    <>
      {displayAssignmentView && (
        <AssignmentView
          isOpen={displayAssignmentView}
          onClose={() => {
            setSelectedAssignment(undefined);
            setIsCreatingAssignment(false);
            reloadAssignments();
          }}
          assignment={selectedAssignment}
        />
      )}
      {/** I'll be using this is creating assingment as a workaround for a key to trigger a new rendering */}
      {isCreatingAssignment && (
        <AssignmentCreator
          assignment={selectedAssignment}
          groups={groups}
          users={users}
          user={user}
          isCreating={isCreatingAssignment}
          cancelCreation={() => {
            setIsCreatingAssignment(false);
            setSelectedAssignment(undefined);
            reloadAssignments();
          }}
        />
      )}
      <div className="w-full flex justify-between items-center">
        <div
          onClick={onBack}
          className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
        >
          <BsArrowLeft className="text-xl" />
          <span>Back</span>
        </div>
        <div
          onClick={reloadAssignments}
          className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
        >
          <span>Reload</span>
          <BsArrowRepeat
            className={clsx("text-xl", isLoading && "animate-spin")}
          />
        </div>
      </div>
      <div className="flex flex-col gap-2">
        <span className="text-lg font-bold">Active Assignments Status</span>
        <div className="flex items-center gap-4">
          <span>
            <b>Total:</b>{" "}
            {assignments
              .filter(activeAssignmentFilter)
              .reduce((acc, curr) => acc + curr.results.length, 0)}
            /
            {assignments
              .filter(activeAssignmentFilter)
              .reduce((acc, curr) => curr.exams.length + acc, 0)}
          </span>
          {Object.keys(
            groupBy(corporateAssignments, (x) => x.corporate?.id)
          ).map((x) => (
            <div key={x}>
              <span className="font-semibold">
                {getUserCompanyName(
                  users.find((u) => u.id === x)!,
                  users,
                  groups
                )}
                :{" "}
              </span>
              <span>
                {groupBy(corporateAssignments, (x) => x.corporate?.id)[
                  x
                ].reduce((acc, curr) => curr.results.length + acc, 0)}
                /
                {groupBy(corporateAssignments, (x) => x.corporate?.id)[
                  x
                ].reduce((acc, curr) => curr.exams.length + acc, 0)}
              </span>
            </div>
          ))}
        </div>
      </div>
      <section className="flex flex-col gap-4">
        <h2 className="text-2xl font-semibold">
          Active Assignments (
          {assignments.filter(activeAssignmentFilter).length})
        </h2>
        <div className="flex flex-wrap gap-2">
          {assignments.filter(activeAssignmentFilter).map((a) => (
            <AssignmentCard
              {...a}
              users={users}
              onClick={() => setSelectedAssignment(a)}
              key={a.id}
            />
          ))}
        </div>
      </section>
      <section className="flex flex-col gap-4">
        <h2 className="text-2xl font-semibold">
          Planned Assignments (
          {assignments.filter(futureAssignmentFilter).length})
        </h2>
        <div className="flex flex-wrap gap-2">
          <div
            onClick={() => setIsCreatingAssignment(true)}
            className="w-[250px] h-[200px] flex flex-col gap-2 items-center justify-center bg-white hover:bg-mti-purple-ultralight text-mti-purple-light hover:text-mti-purple-dark border border-mti-gray-platinum hover:drop-shadow p-4 cursor-pointer rounded-xl transition ease-in-out duration-300"
          >
            <BsPlus className="text-6xl" />
            <span className="text-lg">New Assignment</span>
          </div>
          {assignments.filter(futureAssignmentFilter).map((a) => (
            <AssignmentCard
              {...a}
              users={users}
              onClick={() => {
                setSelectedAssignment(a);
                setIsCreatingAssignment(true);
              }}
              key={a.id}
            />
          ))}
        </div>
      </section>
      <section className="flex flex-col gap-4">
        <h2 className="text-2xl font-semibold">
          Past Assignments ({assignments.filter(pastAssignmentFilter).length})
        </h2>
        <div className="flex flex-wrap gap-2">
          {assignments.filter(pastAssignmentFilter).map((a) => (
            <AssignmentCard
              {...a}
              users={users}
              onClick={() => setSelectedAssignment(a)}
              key={a.id}
              allowDownload
              reload={reloadAssignments}
              allowArchive
              allowExcelDownload
            />
          ))}
        </div>
      </section>
	  <section className="flex flex-col gap-4">
        <h2 className="text-2xl font-semibold">
          Assignments start expired ({assignmentsPastExpiredStart.length})
        </h2>
        <div className="flex flex-wrap gap-2">
          {assignments.filter(startHasExpiredAssignmentFilter).map((a) => (
            <AssignmentCard
              {...a}
              users={users}
              onClick={() => setSelectedAssignment(a)}
              key={a.id}
              allowDownload
              reload={reloadAssignments}
              allowArchive
              allowExcelDownload
            />
          ))}
        </div>
      </section>
      <section className="flex flex-col gap-4">
        <h2 className="text-2xl font-semibold">
          Archived Assignments (
          {assignments.filter(archivedAssignmentFilter).length})
        </h2>
        <div className="flex flex-wrap gap-2">
          {assignments.filter(archivedAssignmentFilter).map((a) => (
            <AssignmentCard
              {...a}
              users={users}
              onClick={() => setSelectedAssignment(a)}
              key={a.id}
              allowDownload
              reload={reloadAssignments}
              allowUnarchive
              allowExcelDownload
            />
          ))}
        </div>
      </section>
    </>
  );
}
