import Input from "@/components/Low/Input";
import Modal from "@/components/Modal";
import {Module} from "@/interfaces";
import clsx from "clsx";
import {useEffect, useMemo, useState} from "react";
import {BsBook, BsCheckCircle, BsClipboard, BsHeadphones, BsMegaphone, BsPen, BsXCircle} from "react-icons/bs";
import {generate} from "random-words";
import {capitalize} from "lodash";
import useUsers from "@/hooks/useUsers";
import {Group, User} from "@/interfaces/user";
import ProgressBar from "@/components/Low/ProgressBar";
import {calculateAverageLevel} from "@/utils/score";
import Button from "@/components/Low/Button";
import ReactDatePicker from "react-datepicker";
import moment from "moment";
import axios from "axios";
import {getExam} from "@/utils/exams";
import {toast} from "react-toastify";
import {Assignment} from "@/interfaces/results";
import Checkbox from "@/components/Low/Checkbox";
import {InstructorGender, Variant} from "@/interfaces/exam";
import Select from "@/components/Low/Select";
import useExams from "@/hooks/useExams";
import {useListSearch} from "@/hooks/useListSearch";

interface Props {
	isCreating: boolean;
	users: User[];
	user: User;
	groups: Group[];
	assignment?: Assignment;
	cancelCreation: () => void;
}

const SIZE = 12;

export default function AssignmentCreator({isCreating, assignment, user, groups, users, cancelCreation}: Props) {
	const [studentsPage, setStudentsPage] = useState(0);
	const [teachersPage, setTeachersPage] = useState(0);

	const [selectedModules, setSelectedModules] = useState<Module[]>(assignment?.exams.map((e) => e.module) || []);
	const [assignees, setAssignees] = useState<string[]>(assignment?.assignees || []);
	const [teachers, setTeachers] = useState<string[]>(!!assignment ? assignment.teachers || [] : [...(user.type === "teacher" ? [user.id] : [])]);
	const [name, setName] = useState(
		assignment?.name ||
			generate({
				minLength: 6,
				maxLength: 8,
				min: 2,
				max: 3,
				join: " ",
				formatter: capitalize,
			}),
	);
	const [isLoading, setIsLoading] = useState(false);
	const [startDate, setStartDate] = useState<Date | null>(assignment ? moment(assignment.startDate).toDate() : moment().add(1, "hour").toDate());

	const [endDate, setEndDate] = useState<Date | null>(
		assignment ? moment(assignment.endDate).toDate() : moment().hours(23).minutes(59).add(8, "day").toDate(),
	);
	const [variant, setVariant] = useState<Variant>("full");
	const [instructorGender, setInstructorGender] = useState<InstructorGender>(assignment?.instructorGender || "varied");
	// creates a new exam for each assignee or just one exam for all assignees
	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>(assignment ? moment(assignment.autoStartDate).toDate() : new Date());

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

	const {exams} = useExams();

	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, text: studentText} = useListSearch([["name"], ["email"]], userStudents);
	const {rows: filteredTeachersRows, renderSearch: renderTeacherSearch, text: teacherText} = useListSearch([["name"], ["email"]], userTeachers);

	useEffect(() => setStudentsPage(0), [studentText]);
	const studentRows = useMemo(
		() =>
			filteredStudentsRows.slice(
				studentsPage * SIZE,
				(studentsPage + 1) * SIZE > filteredStudentsRows.length ? filteredStudentsRows.length : (studentsPage + 1) * SIZE,
			),
		[filteredStudentsRows, studentsPage],
	);

	useEffect(() => setTeachersPage(0), [teacherText]);
	const teacherRows = useMemo(
		() =>
			filteredTeachersRows.slice(
				teachersPage * SIZE,
				(teachersPage + 1) * SIZE > filteredTeachersRows.length ? filteredTeachersRows.length : (teachersPage + 1) * SIZE,
			),
		[filteredTeachersRows, teachersPage],
	);

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

	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 ? `/${assignment.id}` : ""}`, {
			assignees,
			name,
			startDate,
			examIDs: !useRandomExams ? examIDs : undefined,
			endDate,
			selectedModules,
			generateMultiple,
			teachers,
			variant,
			instructorGender,
			released,
			autoStart,
			autoStartDate,
		})
			.then(() => {
				toast.success(`The assignment "${name}" has been ${assignment ? "updated" : "created"} successfully!`);
				cancelCreation();
			})
			.catch((e) => {
				console.log(e);
				toast.error("Something went wrong, please try again later!");
			})
			.finally(() => setIsLoading(false));
	};

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

			if (!confirm(`Are you sure you want to delete the "${assignment.name}" assignment?`)) return;
			axios
				.delete(`api/assignments/${assignment.id}`)
				.then(() => {
					toast.success(`The assignment "${name}" has been deleted successfully!`);
					cancelCreation();
				})
				.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!`);
					cancelCreation();
				})
				.catch((e) => {
					console.log(e);
					toast.error("Something went wrong, please try again later!");
				})
				.finally(() => setIsLoading(false));
		}
	};

	return (
		<Modal isOpen={isCreating} onClose={cancelCreation} title="New Assignment">
			<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>

				<Input type="text" name="name" onChange={(e) => setName(e)} defaultValue={name} label="Assignment Name" required />

				<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">
						{groups.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>

					{renderStudentSearch()}

					<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>
					<div className="w-full flex gap-2 justify-between items-center">
						<div className="flex items-center gap-4 w-fit">
							<Button className="w-[200px] h-fit" disabled={studentsPage === 0} onClick={() => setStudentsPage((prev) => prev - 1)}>
								Previous Page
							</Button>
						</div>
						<div className="flex items-center gap-4 w-fit">
							<span className="opacity-80">
								{studentsPage * SIZE + 1} -{" "}
								{(studentsPage + 1) * SIZE > filteredStudentsRows.length ? filteredStudentsRows.length : (studentsPage + 1) * SIZE} /{" "}
								{filteredStudentsRows.length}
							</span>
							<Button
								className="w-[200px]"
								disabled={(studentsPage + 1) * SIZE >= filteredStudentsRows.length}
								onClick={() => setStudentsPage((prev) => prev + 1)}>
								Next Page
							</Button>
						</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">
							{groups.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>

						{renderTeacherSearch()}

						<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>

						<div className="w-full flex gap-2 justify-between items-center">
							<div className="flex items-center gap-4 w-fit">
								<Button className="w-[200px] h-fit" disabled={teachersPage === 0} onClick={() => setTeachersPage((prev) => prev - 1)}>
									Previous Page
								</Button>
							</div>
							<div className="flex items-center gap-4 w-fit">
								<span className="opacity-80">
									{teachersPage * SIZE + 1} -{" "}
									{(teachersPage + 1) * SIZE > filteredTeachersRows.length
										? filteredTeachersRows.length
										: (teachersPage + 1) * SIZE}{" "}
									/ {filteredTeachersRows.length}
								</span>
								<Button
									className="w-[200px]"
									disabled={(teachersPage + 1) * SIZE >= filteredTeachersRows.length}
									onClick={() => setTeachersPage((prev) => prev + 1)}>
									Next Page
								</Button>
							</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={cancelCreation} disabled={isLoading} isLoading={isLoading}>
						Cancel
					</Button>
					{assignment && (
						<>
							<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}>
						{assignment ? "Update" : "Create"}
					</Button>
				</div>
			</div>
		</Modal>
	);
}
