import Input from "@/components/Low/Input";
import Modal from "@/components/Modal";
import {Module} from "@/interfaces";
import clsx from "clsx";
import {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 {uuidv4} from "@firebase/util";
import {Assignment} from "@/interfaces/results";
import Checkbox from "@/components/Low/Checkbox";

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

export default function AssignmentCreator({isCreating, assignment, assigner, groups, users, cancelCreation}: Props) {
	const [selectedModules, setSelectedModules] = useState<Module[]>(assignment?.exams.map((e) => e.module) || []);
	const [assignees, setAssignees] = useState<string[]>(assignment?.assignees || []);
	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().hours(0).minutes(0).add(1, "day").toDate(),
	);
	const [endDate, setEndDate] = useState<Date | null>(
		assignment ? moment(assignment.endDate).toDate() : moment().hours(23).minutes(59).add(8, "day").toDate(),
	);
	// creates a new exam for each assignee or just one exam for all assignees
	const [generateMultiple, setGenerateMultiple] = useState<boolean>(false);

	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 createAssignment = () => {
		setIsLoading(true);

		(assignment ? axios.patch : axios.post)(`/api/assignments${assignment ? `/${assignment.id}` : ""}`, {
			assignees,
			name,
			startDate,
			endDate,
			selectedModules,
			generateMultiple,
		})
			.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));
		}
	};

	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-2 place-items-center lg:grid-cols-6 -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",
							"lg:col-span-2",
							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",
							"lg:col-span-2",
							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") ? () => 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",
							"lg:col-span-2",
							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",
							"lg:col-span-3",
							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>
					<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",
							"lg:col-span-3",
							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>
				</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">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"
							filterDate={(date) => moment(date).isAfter(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"
							filterDate={(date) => moment(date).isAfter(startDate)}
							dateFormat="dd/MM/yyyy HH:mm"
							selected={endDate}
							showTimeSelect
							onChange={(date) => setEndDate(date)}
						/>
					</div>
				</div>

				<section className="w-full flex flex-col gap-3">
					<span className="font-semibold">Assignees ({assignees.length} selected)</span>
					<div className="flex gap-4 overflow-x-scroll scrollbar-hide">
						{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>
					<div className="flex flex-wrap -md:justify-center gap-4">
						{users.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>
				<div className="flex gap-4 w-full justify-end">
					<Checkbox isChecked={generateMultiple} onChange={() => setGenerateMultiple((d) => !d)}>
						Generate different exams
					</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="red"
							variant="outline"
							onClick={deleteAssignment}
							disabled={isLoading}
							isLoading={isLoading}>
							Delete
						</Button>
					)}
					<Button
						disabled={selectedModules.length === 0 || !name || !startDate || !endDate || assignees.length === 0}
						className="w-full max-w-[200px]"
						onClick={createAssignment}
						isLoading={isLoading}>
						{assignment ? "Update" : "Create"}
					</Button>
				</div>
			</div>
		</Modal>
	);
}
