import Layout from "@/components/High/Layout";
import Button from "@/components/Low/Button";
import Checkbox from "@/components/Low/Checkbox";
import Input from "@/components/Low/Input";
import ProgressBar from "@/components/Low/ProgressBar";
import Select from "@/components/Low/Select";
import Separator from "@/components/Low/Separator";
import useExams from "@/hooks/useExams";
import {useListSearch} from "@/hooks/useListSearch";
import usePagination from "@/hooks/usePagination";
import {Module} from "@/interfaces";
import {EntityWithRoles} from "@/interfaces/entity";
import {InstructorGender, Variant} from "@/interfaces/exam";
import {Assignment} from "@/interfaces/results";
import {Group, User} from "@/interfaces/user";
import {sessionOptions} from "@/lib/session";
import {mapBy, serialize} from "@/utils";
import {getAssignment} from "@/utils/assignments.be";
import {getEntitiesWithRoles} from "@/utils/entities.be";
import {getGroups, getGroupsByEntities} from "@/utils/groups.be";
import {checkAccess} from "@/utils/permissions";
import {calculateAverageLevel} from "@/utils/score";
import {getEntitiesUsers, getUsers} from "@/utils/users.be";
import axios from "axios";
import clsx from "clsx";
import {withIronSessionSsr} from "iron-session/next";
import {capitalize} from "lodash";
import moment from "moment";
import Head from "next/head";
import Link from "next/link";
import {useRouter} from "next/router";
import {generate} from "random-words";
import {useEffect, useMemo, useState} from "react";
import ReactDatePicker from "react-datepicker";
import {BsBook, BsCheckCircle, BsChevronLeft, BsClipboard, BsHeadphones, BsMegaphone, BsPen, BsXCircle} from "react-icons/bs";
import {toast} from "react-toastify";

export const getServerSideProps = withIronSessionSsr(async ({req, res, params}) => {
	const user = req.session.user as User | undefined;

	if (!user) {
		return {
			redirect: {
				destination: "/login",
				permanent: false,
			},
		};
	}

	if (!checkAccess(user, ["admin", "developer", "corporate", "teacher", "mastercorporate"]))
		return {
			redirect: {
				destination: "/dashboard",
				permanent: false,
			},
		};

	res.setHeader("Cache-Control", "public, s-maxage=10, stale-while-revalidate=59");

	const {id} = params as {id: string};
	const entityIDS = mapBy(user.entities, "id") || [];

	const assignment = await getAssignment(id);
	if (!assignment)
		return {
			redirect: {
				destination: "/assignments",
				permanent: false,
			},
		};

	const users = await (checkAccess(user, ["developer", "admin"]) ? getUsers() : getEntitiesUsers(entityIDS));
	const entities = await (checkAccess(user, ["developer", "admin"]) ? getEntitiesWithRoles() : getEntitiesWithRoles(entityIDS));
	const groups = await (checkAccess(user, ["developer", "admin"]) ? getGroups() : getGroupsByEntities(entityIDS));

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

interface Props {
	assignment: Assignment;
	groups: Group[];
	user: User;
	users: User[];
	entities: EntityWithRoles[];
}

const SIZE = 9;

export default function AssignmentsPage({assignment, user, users, entities, groups}: Props) {
	const [selectedModules, setSelectedModules] = useState<Module[]>(assignment.exams.map((e) => e.module));
	const [assignees, setAssignees] = useState<string[]>(assignment.assignees);
	const [teachers, setTeachers] = useState<string[]>(assignment.teachers || []);
	const [entity, setEntity] = useState<string | undefined>(entities[0]?.id);
	const [name, setName] = useState(assignment.name);
	const [isLoading, setIsLoading] = useState(false);

	const [startDate, setStartDate] = useState<Date | null>(moment(assignment.startDate).toDate());
	const [endDate, setEndDate] = useState<Date | null>(moment(assignment.endDate).toDate());

	const [variant, setVariant] = useState<Variant>("full");
	const [instructorGender, setInstructorGender] = useState<InstructorGender>(assignment?.instructorGender || "varied");

	const [generateMultiple, setGenerateMultiple] = useState<boolean>(false);
	const [released, setReleased] = useState<boolean>(assignment.released || false);

	const [autoStart, setAutostart] = useState<boolean>(assignment.autoStart || false);
	const [autoStartDate, setAutoStartDate] = useState<Date | null>(moment(assignment.autoStartDate).toDate());

	const [useRandomExams, setUseRandomExams] = useState(true);
	const [examIDs, setExamIDs] = useState<{id: string; module: Module}[]>([]);

	const {exams} = useExams();
	const router = useRouter();

	const classrooms = useMemo(() => groups.filter((e) => e.entity === entity), [entity, groups]);

	const userStudents = useMemo(() => users.filter((x) => x.type === "student"), [users]);
	const userTeachers = useMemo(() => users.filter((x) => x.type === "teacher"), [users]);

	const {rows: filteredStudentsRows, renderSearch: renderStudentSearch} = useListSearch([["name"], ["email"]], userStudents);
	const {rows: filteredTeachersRows, renderSearch: renderTeacherSearch} = useListSearch([["name"], ["email"]], userTeachers);

	const {items: studentRows, renderMinimal: renderStudentPagination} = usePagination(filteredStudentsRows, SIZE);
	const {items: teacherRows, renderMinimal: renderTeacherPagination} = usePagination(filteredTeachersRows, SIZE);

	useEffect(() => {
		setExamIDs((prev) => prev.filter((x) => selectedModules.includes(x.module)));
	}, [selectedModules]);

	useEffect(() => {
		setAssignees([]);
		setTeachers([]);
	}, [entity]);

	const toggleModule = (module: Module) => {
		const modules = selectedModules.filter((x) => x !== module);
		setSelectedModules((prev) => (prev.includes(module) ? modules : [...modules, module]));
	};

	const toggleAssignee = (user: User) => {
		setAssignees((prev) => (prev.includes(user.id) ? prev.filter((a) => a !== user.id) : [...prev, user.id]));
	};

	const toggleTeacher = (user: User) => {
		setTeachers((prev) => (prev.includes(user.id) ? prev.filter((a) => a !== user.id) : [...prev, user.id]));
	};

	const createAssignment = () => {
		setIsLoading(true);

		(assignment ? axios.patch : axios.post)(`/api/assignments${assignment.id}`, {
			assignees,
			name,
			startDate,
			examIDs: !useRandomExams ? examIDs : undefined,
			endDate,
			selectedModules,
			generateMultiple,
			entity,
			teachers,
			variant,
			instructorGender,
			released,
			autoStart,
			autoStartDate,
		})
			.then(() => {
				toast.success(`The assignment "${name}" has been updated successfully!`);
				router.push(`/assignments/${assignment.id}`);
			})
			.catch((e) => {
				console.log(e);
				toast.error("Something went wrong, please try again later!");
			})
			.finally(() => setIsLoading(false));
	};

	const deleteAssignment = () => {
		if (!confirm(`Are you sure you want to delete the "${assignment.name}" assignment?`)) return;
		console.log("GOT HERE");
		setIsLoading(true);

		axios
			.delete(`/api/assignments/${assignment.id}`)
			.then(() => {
				toast.success(`The assignment "${name}" has been deleted successfully!`);
				router.push("/assignments");
			})
			.catch((e) => {
				console.log(e);
				toast.error("Something went wrong, please try again later!");
			})
			.finally(() => setIsLoading(false));
	};

	const startAssignment = () => {
		if (assignment) {
			setIsLoading(true);

			axios
				.post(`/api/assignments/${assignment.id}/start`)
				.then(() => {
					toast.success(`The assignment "${name}" has been started successfully!`);
					router.push(`/assignments/${assignment.id}`);
				})
				.catch((e) => {
					console.log(e);
					toast.error("Something went wrong, please try again later!");
				})
				.finally(() => setIsLoading(false));
		}
	};

	return (
		<>
			<Head>
				<title>Edit {assignment.name} | 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>
			<Layout user={user}>
				<div className="flex flex-col gap-4">
					<div className="flex items-center gap-2">
						<Link href="/assignments" className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
							<BsChevronLeft />
						</Link>
						<h2 className="font-bold text-2xl">Edit {assignment.name}</h2>
					</div>
					<Separator />
				</div>
				<div className="w-full flex flex-col gap-4">
					<section className="w-full grid -md:grid-cols-1 md:grid-cols-3 place-items-center -md:flex-col -md:items-center -md:gap-12 justify-between gap-8 mt-8 px-8">
						<div
							onClick={!selectedModules.includes("level") ? () => toggleModule("reading") : undefined}
							className={clsx(
								"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
								selectedModules.includes("reading") ? "border-mti-purple-light" : "border-mti-gray-platinum",
							)}>
							<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-reading top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
								<BsBook className="text-white w-7 h-7" />
							</div>
							<span className="ml-8 font-semibold">Reading</span>
							{!selectedModules.includes("reading") && !selectedModules.includes("level") && (
								<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
							)}
							{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />}
							{selectedModules.includes("reading") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
						</div>
						<div
							onClick={!selectedModules.includes("level") ? () => toggleModule("listening") : undefined}
							className={clsx(
								"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
								selectedModules.includes("listening") ? "border-mti-purple-light" : "border-mti-gray-platinum",
							)}>
							<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-listening top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
								<BsHeadphones className="text-white w-7 h-7" />
							</div>
							<span className="ml-8 font-semibold">Listening</span>
							{!selectedModules.includes("listening") && !selectedModules.includes("level") && (
								<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
							)}
							{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />}
							{selectedModules.includes("listening") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
						</div>
						<div
							onClick={
								(!selectedModules.includes("level") && selectedModules.length === 0) || selectedModules.includes("level")
									? () => toggleModule("level")
									: undefined
							}
							className={clsx(
								"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
								selectedModules.includes("level") ? "border-mti-purple-light" : "border-mti-gray-platinum",
							)}>
							<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-level top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
								<BsClipboard className="text-white w-7 h-7" />
							</div>
							<span className="ml-8 font-semibold">Level</span>
							{!selectedModules.includes("level") && selectedModules.length === 0 && (
								<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
							)}
							{!selectedModules.includes("level") && selectedModules.length > 0 && <BsXCircle className="text-mti-red-light w-8 h-8" />}
							{selectedModules.includes("level") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
						</div>
						<div
							onClick={!selectedModules.includes("level") ? () => toggleModule("writing") : undefined}
							className={clsx(
								"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
								selectedModules.includes("writing") ? "border-mti-purple-light" : "border-mti-gray-platinum",
							)}>
							<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-writing top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
								<BsPen className="text-white w-7 h-7" />
							</div>
							<span className="ml-8 font-semibold">Writing</span>
							{!selectedModules.includes("writing") && !selectedModules.includes("level") && (
								<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
							)}
							{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />}
							{selectedModules.includes("writing") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
						</div>
						<div
							onClick={!selectedModules.includes("level") ? () => toggleModule("speaking") : undefined}
							className={clsx(
								"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
								selectedModules.includes("speaking") ? "border-mti-purple-light" : "border-mti-gray-platinum",
							)}>
							<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-speaking top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
								<BsMegaphone className="text-white w-7 h-7" />
							</div>
							<span className="ml-8 font-semibold">Speaking</span>
							{!selectedModules.includes("speaking") && !selectedModules.includes("level") && (
								<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
							)}
							{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />}
							{selectedModules.includes("speaking") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
						</div>
					</section>

					<div className="w-full grid -md:grid-cols-1 md:grid-cols-2 gap-8">
						<Input type="text" name="name" onChange={(e) => setName(e)} defaultValue={name} label="Assignment Name" required />
						<Select
							label="Entity"
							options={entities.map((e) => ({value: e.id, label: e.label}))}
							onChange={(v) => setEntity(v ? v.value! : undefined)}
							defaultValue={{value: entities[0]?.id, label: entities[0]?.label}}
						/>
					</div>

					<div className="w-full grid -md:grid-cols-1 md:grid-cols-2 gap-8">
						<div className="flex flex-col gap-2">
							<label className="font-normal text-base text-mti-gray-dim">Limit Start Date *</label>
							<ReactDatePicker
								className={clsx(
									"p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
									"hover:border-mti-purple tooltip z-10",
									"transition duration-300 ease-in-out",
								)}
								popperClassName="!z-20"
								filterTime={(date) => moment(date).isSameOrAfter(new Date())}
								dateFormat="dd/MM/yyyy HH:mm"
								selected={startDate}
								showTimeSelect
								onChange={(date) => setStartDate(date)}
							/>
						</div>
						<div className="flex flex-col gap-2">
							<label className="font-normal text-base text-mti-gray-dim">End Date *</label>
							<ReactDatePicker
								className={clsx(
									"p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
									"hover:border-mti-purple tooltip z-10",
									"transition duration-300 ease-in-out",
								)}
								popperClassName="!z-20"
								filterTime={(date) => moment(date).isAfter(startDate)}
								dateFormat="dd/MM/yyyy HH:mm"
								selected={endDate}
								showTimeSelect
								onChange={(date) => setEndDate(date)}
							/>
						</div>
						{autoStart && (
							<div className="flex flex-col gap-2">
								<label className="font-normal text-base text-mti-gray-dim">Automatic Start Date *</label>
								<ReactDatePicker
									className={clsx(
										"p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
										"hover:border-mti-purple tooltip z-10",
										"transition duration-300 ease-in-out",
									)}
									popperClassName="!z-20"
									filterTime={(date) => moment(date).isSameOrAfter(new Date())}
									dateFormat="dd/MM/yyyy HH:mm"
									selected={autoStartDate}
									showTimeSelect
									onChange={(date) => setAutoStartDate(date)}
								/>
							</div>
						)}
					</div>

					{selectedModules.includes("speaking") && (
						<div className="flex flex-col gap-3 w-full">
							<label className="font-normal text-base text-mti-gray-dim">Speaking Instructor&apos;s Gender</label>
							<Select
								value={{
									value: instructorGender,
									label: capitalize(instructorGender),
								}}
								onChange={(value) => (value ? setInstructorGender(value.value as InstructorGender) : null)}
								disabled={!selectedModules.includes("speaking") || !!assignment}
								options={[
									{value: "male", label: "Male"},
									{value: "female", label: "Female"},
									{value: "varied", label: "Varied"},
								]}
							/>
						</div>
					)}

					{selectedModules.length > 0 && (
						<div className="flex flex-col gap-3 w-full">
							<Checkbox isChecked={useRandomExams} onChange={setUseRandomExams}>
								Random Exams
							</Checkbox>
							{!useRandomExams && (
								<div className="grid md:grid-cols-2 w-full gap-4">
									{selectedModules.map((module) => (
										<div key={module} className="flex flex-col gap-3 w-full">
											<label className="font-normal text-base text-mti-gray-dim">{capitalize(module)} Exam</label>
											<Select
												value={{
													value: examIDs.find((e) => e.module === module)?.id || null,
													label: examIDs.find((e) => e.module === module)?.id || "",
												}}
												onChange={(value) =>
													value
														? setExamIDs((prev) => [
																...prev.filter((x) => x.module !== module),
																{id: value.value!, module},
														  ])
														: setExamIDs((prev) => prev.filter((x) => x.module !== module))
												}
												options={exams
													.filter((x) => !x.isDiagnostic && x.module === module)
													.map((x) => ({value: x.id, label: x.id}))}
											/>
										</div>
									))}
								</div>
							)}
						</div>
					)}

					<section className="w-full flex flex-col gap-4">
						<span className="font-semibold">Assignees ({assignees.length} selected)</span>
						<div className="grid grid-cols-5 gap-4">
							{classrooms.map((g) => (
								<button
									key={g.id}
									onClick={() => {
										const groupStudentIds = users.filter((u) => g.participants.includes(u.id)).map((u) => u.id);
										if (groupStudentIds.every((u) => assignees.includes(u))) {
											setAssignees((prev) => prev.filter((a) => !groupStudentIds.includes(a)));
										} else {
											setAssignees((prev) => [...prev.filter((a) => !groupStudentIds.includes(a)), ...groupStudentIds]);
										}
									}}
									className={clsx(
										"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
										"transition duration-300 ease-in-out",
										users.filter((u) => g.participants.includes(u.id)).every((u) => assignees.includes(u.id)) &&
											"!bg-mti-purple-light !text-white",
									)}>
									{g.name}
								</button>
							))}
						</div>

						<div className="w-full flex items-center gap-4">
							{renderStudentSearch()}
							{renderStudentPagination()}
						</div>

						<div className="flex flex-wrap -md:justify-center gap-4">
							{studentRows.map((user) => (
								<div
									onClick={() => toggleAssignee(user)}
									className={clsx(
										"p-4 flex flex-col gap-2 rounded-xl border cursor-pointer w-72",
										"transition ease-in-out duration-300",
										assignees.includes(user.id) ? "border-mti-purple" : "border-mti-gray-platinum",
									)}
									key={user.id}>
									<span className="flex flex-col gap-0 justify-center">
										<span className="font-semibold">{user.name}</span>
										<span className="text-sm opacity-80">{user.email}</span>
									</span>
									<ProgressBar
										color="purple"
										textClassName="!text-mti-black/80"
										label={`Level ${calculateAverageLevel(user.levels)}`}
										percentage={(calculateAverageLevel(user.levels) / 9) * 100}
										className="h-6"
									/>
									<span className="text-mti-black/80 text-sm whitespace-pre-wrap mt-2">
										Groups:{" "}
										{groups
											.filter((g) => g.participants.includes(user.id))
											.map((g) => g.name)
											.join(", ")}
									</span>
								</div>
							))}
						</div>
					</section>

					{user.type !== "teacher" && (
						<section className="w-full flex flex-col gap-3">
							<span className="font-semibold">Teachers ({teachers.length} selected)</span>
							<div className="grid grid-cols-5 gap-4">
								{classrooms.map((g) => (
									<button
										key={g.id}
										onClick={() => {
											const groupStudentIds = users.filter((u) => g.participants.includes(u.id)).map((u) => u.id);
											if (groupStudentIds.every((u) => teachers.includes(u))) {
												setTeachers((prev) => prev.filter((a) => !groupStudentIds.includes(a)));
											} else {
												setTeachers((prev) => [...prev.filter((a) => !groupStudentIds.includes(a)), ...groupStudentIds]);
											}
										}}
										className={clsx(
											"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
											"transition duration-300 ease-in-out",
											users.filter((u) => g.participants.includes(u.id)).every((u) => teachers.includes(u.id)) &&
												"!bg-mti-purple-light !text-white",
										)}>
										{g.name}
									</button>
								))}
							</div>

							<div className="w-full flex items-center gap-4">
								{renderTeacherSearch()}
								{renderTeacherPagination()}
							</div>

							<div className="flex flex-wrap -md:justify-center gap-4">
								{teacherRows.map((user) => (
									<div
										onClick={() => toggleTeacher(user)}
										className={clsx(
											"p-4 flex flex-col gap-2 rounded-xl border cursor-pointer w-72",
											"transition ease-in-out duration-300",
											teachers.includes(user.id) ? "border-mti-purple" : "border-mti-gray-platinum",
										)}
										key={user.id}>
										<span className="flex flex-col gap-0 justify-center">
											<span className="font-semibold">{user.name}</span>
											<span className="text-sm opacity-80">{user.email}</span>
										</span>
										<span className="text-mti-black/80 text-sm whitespace-pre-wrap mt-2">
											Groups:{" "}
											{groups
												.filter((g) => g.participants.includes(user.id))
												.map((g) => g.name)
												.join(", ")}
										</span>
									</div>
								))}
							</div>
						</section>
					)}

					<div className="flex gap-4 w-full items-end">
						<Checkbox isChecked={variant === "full"} onChange={() => setVariant((prev) => (prev === "full" ? "partial" : "full"))}>
							Full length exams
						</Checkbox>
						<Checkbox isChecked={generateMultiple} onChange={() => setGenerateMultiple((d) => !d)}>
							Generate different exams
						</Checkbox>
						<Checkbox isChecked={released} onChange={() => setReleased((d) => !d)}>
							Auto release results
						</Checkbox>
						<Checkbox isChecked={autoStart} onChange={() => setAutostart((d) => !d)}>
							Auto start exam
						</Checkbox>
					</div>
					<div className="flex gap-4 w-full justify-end">
						<Button
							className="w-full max-w-[200px]"
							variant="outline"
							onClick={() => router.push("/assignments")}
							disabled={isLoading}
							isLoading={isLoading}>
							Cancel
						</Button>
						<Button
							className="w-full max-w-[200px]"
							color="green"
							variant="outline"
							onClick={startAssignment}
							disabled={isLoading || moment().isAfter(startDate)}
							isLoading={isLoading}>
							Start
						</Button>
						<Button
							className="w-full max-w-[200px]"
							color="red"
							variant="outline"
							onClick={deleteAssignment}
							disabled={isLoading}
							isLoading={isLoading}>
							Delete
						</Button>
						<Button
							disabled={
								selectedModules.length === 0 ||
								!name ||
								!startDate ||
								!endDate ||
								assignees.length === 0 ||
								(!useRandomExams && examIDs.length < selectedModules.length)
							}
							className="w-full max-w-[200px]"
							onClick={createAssignment}
							isLoading={isLoading}>
							Update
						</Button>
					</div>
				</div>
			</Layout>
		</>
	);
}
