import Checkbox from "@/components/Low/Checkbox";
import Separator from "@/components/Low/Separator";
import {useEntityPermission} from "@/hooks/useEntityPermissions";
import {EntityWithRoles, Role} from "@/interfaces/entity";
import {User} from "@/interfaces/user";
import {sessionOptions} from "@/lib/session";
import {RolePermission} from "@/resources/entityPermissions";
import {findBy, mapBy, redirect, serialize} from "@/utils";
import {requestUser} from "@/utils/api";
import {getEntityWithRoles} from "@/utils/entities.be";
import {shouldRedirectHome} from "@/utils/navigation.disabled";
import {doesEntityAllow} from "@/utils/permissions";
import {isAdmin} from "@/utils/users";
import {countEntityUsers} from "@/utils/users.be";
import axios from "axios";
import {withIronSessionSsr} from "iron-session/next";
import Head from "next/head";
import Link from "next/link";
import {useRouter} from "next/router";
import {Divider} from "primereact/divider";
import {useState} from "react";
import {BsCheck, BsChevronLeft, BsTag, BsTrash} from "react-icons/bs";
import {toast} from "react-toastify";

type PermissionLayout = {label: string; key: RolePermission};

const USER_MANAGEMENT: PermissionLayout[] = [
	{label: "View Students", key: "view_students"},
	{label: "View Teachers", key: "view_teachers"},
	{label: "View Corporate Accounts", key: "view_corporates"},
	{label: "View Master Corporate Accounts", key: "view_mastercorporates"},
	{label: "Edit Students", key: "edit_students"},
	{label: "Edit Teachers", key: "edit_teachers"},
	{label: "Edit Corporate Accounts", key: "edit_corporates"},
	{label: "Edit Master Corporate Accounts", key: "edit_mastercorporates"},
	{label: "Delete Students", key: "delete_students"},
	{label: "Delete Teachers", key: "delete_teachers"},
	{label: "Delete Corporate Accounts", key: "delete_corporates"},
	{label: "Delete Master Corporate Accounts", key: "delete_mastercorporates"},
	{label: "Create a Single User", key: "create_user"},
	{label: "Create Users in Batch", key: "create_user_batch"},
	{label: "Create a Single Code", key: "create_code"},
	{label: "Create Codes in Batch", key: "create_code_batch"},
	{label: "Download User List", key: "download_user_list"},
	{label: "View Code List", key: "view_code_list"},
	{label: "Delete Code", key: "delete_code"},
];

const EXAM_MANAGEMENT: PermissionLayout[] = [
	{label: "View Reading", key: "view_reading"},
	{label: "Generate Reading", key: "generate_reading"},
	{label: "Delete Reading", key: "delete_reading"},
	{label: "View Listening", key: "view_listening"},
	{label: "Generate Listening", key: "generate_listening"},
	{label: "Delete Listening", key: "delete_listening"},
	{label: "View Writing", key: "view_writing"},
	{label: "Generate Writing", key: "generate_writing"},
	{label: "Delete Writing", key: "delete_writing"},
	{label: "View Speaking", key: "view_speaking"},
	{label: "Generate Speaking", key: "generate_speaking"},
	{label: "Delete Speaking", key: "delete_speaking"},
	{label: "View Level", key: "view_level"},
	{label: "Generate Level", key: "generate_level"},
	{label: "Delete Level", key: "delete_level"},
	{label: "Set as Private/Public", key: "update_exam_privacy"},
	{label: "View Confidential Exams", key: "view_confidential_exams"},
	{label: "Create Confidential Exams", key: "create_confidential_exams"},
	{label: "Create Public Exams", key: "create_public_exams"},
	{label: "View Statistics", key: "view_statistics"},
];

const CLASSROOM_MANAGEMENT: PermissionLayout[] = [
	{label: "View Classrooms", key: "view_classrooms"},
	{label: "Create Classrooms", key: "create_classroom"},
	{label: "Rename Classrooms", key: "rename_classrooms"},
	{label: "Add to Classroom", key: "add_to_classroom"},
	{label: "Upload to Classroom", key: "upload_classroom"},
	{label: "Remove from Classroom", key: "remove_from_classroom"},
	{label: "Delete Classroom", key: "delete_classroom"},
	{label: "View Student Record", key: "view_student_record"},
	{label: "Download Student Report", key: "download_student_record"},
];

const ENTITY_MANAGEMENT: PermissionLayout[] = [
	{label: "View Entities", key: "view_entities"},
	{label: "View Entity Statistics", key: "view_entity_statistics"},
	{label: "Rename Entity", key: "rename_entity"},
	{label: "Add to Entity", key: "add_to_entity"},
	{label: "Remove from Entity", key: "remove_from_entity"},
	{label: "Delete Entity", key: "delete_entity"},
	{label: "View Entity Roles", key: "view_entity_roles"},
	{label: "Create Entity Role", key: "create_entity_role"},
	{label: "Rename Entity Role", key: "rename_entity_role"},
	{label: "Edit Role Permissions", key: "edit_role_permissions"},
	{label: "Assign Role to User", key: "assign_to_role"},
	{label: "Delete Entity Role", key: "delete_entity_role"},
	{label: "Download Statistics Report", key: "download_statistics_report"},
	{label: "Edit Grading System", key: "edit_grading_system"},
	{label: "View Student Performance", key: "view_student_performance"},
	{label: "Pay for Entity", key: "pay_entity"},
	{label: "View Payment Record", key: "view_payment_record"},
];

const ASSIGNMENT_MANAGEMENT: PermissionLayout[] = [
	{label: "View Assignments", key: "view_assignments"},
	{label: "Create Assignments", key: "create_assignment"},
	{label: "Start Assignments", key: "start_assignment"},
	{label: "Edit Assignments", key: "edit_assignment"},
	{label: "Delete Assignments", key: "delete_assignment"},
	{label: "Archive Assignments", key: "archive_assignment"},
];

const WORKFLOW_MANAGEMENT: PermissionLayout[] = [
	{label: "View Workflows", key: "view_workflows"},
	{label: "Configure Workflows", key: "configure_workflows"},
	{label: "Edit Workflow", key: "edit_workflow"},
	{label: "Delete Workflow", key: "delete_workflow"},
];

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

	if (shouldRedirectHome(user)) return redirect("/");

	const {id, role} = params as {id: string; role: string};

	if (!mapBy(user.entities, "id").includes(id) && !["admin", "developer"].includes(user.type)) return redirect("/entities");

	const entity = await getEntityWithRoles(id);
	if (!entity) return redirect("/entities");

	const entityRole = findBy(entity.roles, "id", role);
	if (!entityRole) return redirect(`/entities/${id}/roles`);

	if (!doesEntityAllow(user, entity, "view_entity_roles")) return redirect(`/entities/${id}`);
	const disableEdit = !isAdmin(user) && findBy(user.entities, "id", entity.id)?.role === entityRole.id;

	const userCount = await countEntityUsers(id, {"entities.role": role});

	return {
		props: serialize({
			user,
			entity,
			role: entityRole,
			userCount,
			disableEdit,
		}),
	};
}, sessionOptions);

interface Props {
	user: User;
	entity: EntityWithRoles;
	role: Role;
	userCount: number;
	disableEdit?: boolean;
}

export default function EntityRole({user, entity, role, userCount, disableEdit}: Props) {
	const [permissions, setPermissions] = useState(role.permissions);
	const [isLoading, setIsLoading] = useState(false);

	const router = useRouter();

	const canEditPermissions = useEntityPermission(user, entity, "edit_role_permissions");
	const canRenameRole = useEntityPermission(user, entity, "rename_entity_role");
	const canDeleteRole = useEntityPermission(user, entity, "delete_entity_role");

	const renameRole = () => {
		if (!canRenameRole || disableEdit) return;

		const label = prompt("Rename this role:", role.label);
		if (!label) return;

		setIsLoading(true);
		axios
			.patch(`/api/roles/${role.id}`, {label})
			.then(() => {
				toast.success("The role has been updated successfully!");
				router.replace(router.asPath);
			})
			.catch((e) => {
				console.error(e);
				toast.error("Something went wrong!");
			})
			.finally(() => setIsLoading(false));
	};

	const deleteRole = () => {
		if (!canDeleteRole || role.isDefault || disableEdit) return;
		if (!confirm("Are you sure you want to delete this role?")) return;

		setIsLoading(true);

		axios
			.delete(`/api/roles/${role.id}`)
			.then(() => {
				toast.success("This role has been successfully deleted!");
				router.replace(`/entities/${entity.id}/roles`);
			})
			.catch((e) => {
				console.error(e);
				toast.error("Something went wrong!");
			})
			.finally(() => setIsLoading(false));
	};

	const editPermissions = () => {
		if (!canEditPermissions || disableEdit) return;

		setIsLoading(true);

		axios
			.patch(`/api/roles/${role.id}`, {permissions})
			.then(() => {
				toast.success("This role has been successfully updated!");
				router.replace(router.asPath);
			})
			.catch((e) => {
				console.error(e);
				toast.error("Something went wrong!");
			})
			.finally(() => setIsLoading(false));
	};

	const enableCheckbox = (permission: RolePermission) => {
		if (!canEditPermissions || disableEdit) return false;
		return doesEntityAllow(user, entity, permission);
	};

	const togglePermissions = (p: RolePermission) => setPermissions((prev) => (prev.includes(p) ? prev.filter((x) => x !== p) : [...prev, p]));
	const toggleMultiplePermissions = (p: RolePermission[]) =>
		setPermissions((prev) => [...prev.filter((x) => !p.includes(x)), ...(p.every((x) => prev.includes(x)) ? [] : p)]);

	return (
		<>
			<Head>
				<title>
					{role.label} | {entity.label} | 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>
			<>
				<section className="flex flex-col gap-0">
					<div className="flex flex-col gap-3">
						<div className="flex items-end justify-between">
							<div className="flex items-center gap-2">
								<Link
									href={`/entities/${entity.id}/roles`}
									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">
									{role.label} Role ({userCount} users)
								</h2>
							</div>
						</div>
						<div className="flex items-center justify-between w-full">
							<div className="flex items-center gap-2">
								<button
									onClick={renameRole}
									disabled={isLoading || !canRenameRole}
									className="flex items-center gap-1 px-2 py-2 border rounded-full hover:bg-neutral-100 disabled:hover:bg-transparent disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
									<BsTag />
									<span className="text-xs">Rename Role</span>
								</button>
								<button
									onClick={deleteRole}
									disabled={isLoading || !canDeleteRole || role.isDefault}
									className="flex items-center gap-1 px-2 py-2 border border-mti-rose rounded-full bg-mti-rose-light text-white hover:bg-mti-rose-dark disabled:hover:bg-mti-rose-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
									<BsTrash />
									<span className="text-xs">Delete Role</span>
								</button>
							</div>
							<button
								onClick={editPermissions}
								disabled={isLoading || !canEditPermissions}
								className="flex items-center gap-1 px-2 py-2 border rounded-full border-mti-green bg-mti-green-light text-white hover:bg-mti-green-dark disabled:hover:bg-mti-green-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
								<BsCheck />
								<span className="text-xs">Save Changes</span>
							</button>
						</div>
					</div>
					<Divider />

					<section className="grid grid-cols-2 gap-16">
						<div className="flex flex-col gap-4">
							<div className="w-full flex items-center justify-between">
								<b>User Management</b>
								<Checkbox
									disabled={!canEditPermissions || disableEdit}
									isChecked={mapBy(USER_MANAGEMENT, "key").every((k) => permissions.includes(k))}
									onChange={() => toggleMultiplePermissions(mapBy(USER_MANAGEMENT, "key").filter(enableCheckbox))}>
									Select all
								</Checkbox>
							</div>
							<Separator />
							<div className="grid grid-cols-2 gap-4">
								{USER_MANAGEMENT.map(({label, key}) => (
									<Checkbox
										disabled={!enableCheckbox(key)}
										key={key}
										isChecked={permissions.includes(key)}
										onChange={() => togglePermissions(key)}>
										{label}
									</Checkbox>
								))}
							</div>
						</div>

						<div className="flex flex-col gap-4">
							<div className="w-full flex items-center justify-between">
								<b>Exam Management</b>
								<Checkbox
									disabled={!canEditPermissions || disableEdit}
									isChecked={mapBy(EXAM_MANAGEMENT, "key").every((k) => permissions.includes(k))}
									onChange={() => toggleMultiplePermissions(mapBy(EXAM_MANAGEMENT, "key").filter(enableCheckbox))}>
									Select all
								</Checkbox>
							</div>
							<Separator />
							<div className="grid grid-cols-3 gap-4">
								{EXAM_MANAGEMENT.map(({label, key}) => (
									<Checkbox
										disabled={!enableCheckbox(key)}
										key={key}
										isChecked={permissions.includes(key)}
										onChange={() => togglePermissions(key)}>
										{label}
									</Checkbox>
								))}
							</div>
						</div>

						<div className="flex flex-col gap-4">
							<div className="w-full flex items-center justify-between">
								<b>Clasroom Management</b>
								<Checkbox
									disabled={!canEditPermissions || disableEdit}
									isChecked={mapBy(CLASSROOM_MANAGEMENT, "key").every((k) => permissions.includes(k))}
									onChange={() => toggleMultiplePermissions(mapBy(CLASSROOM_MANAGEMENT, "key").filter(enableCheckbox))}>
									Select all
								</Checkbox>
							</div>
							<Separator />
							<div className="grid grid-cols-2 gap-4">
								{CLASSROOM_MANAGEMENT.map(({label, key}) => (
									<Checkbox
										disabled={!enableCheckbox(key)}
										key={key}
										isChecked={permissions.includes(key)}
										onChange={() => togglePermissions(key)}>
										{label}
									</Checkbox>
								))}
							</div>
						</div>

						<div className="flex flex-col gap-4">
							<div className="w-full flex items-center justify-between">
								<b>Entity Management</b>
								<Checkbox
									disabled={!canEditPermissions || disableEdit}
									isChecked={mapBy(ENTITY_MANAGEMENT, "key").every((k) => permissions.includes(k))}
									onChange={() => toggleMultiplePermissions(mapBy(ENTITY_MANAGEMENT, "key").filter(enableCheckbox))}>
									Select all
								</Checkbox>
							</div>
							<Separator />
							<div className="grid grid-cols-2 gap-4">
								{ENTITY_MANAGEMENT.map(({label, key}) => (
									<Checkbox
										disabled={!enableCheckbox(key)}
										key={key}
										isChecked={permissions.includes(key)}
										onChange={() => togglePermissions(key)}>
										{label}
									</Checkbox>
								))}
							</div>
						</div>

						<div className="flex flex-col gap-4">
							<div className="w-full flex items-center justify-between">
								<b>Assignment Management</b>
								<Checkbox
									disabled={!canEditPermissions || disableEdit}
									isChecked={mapBy(ASSIGNMENT_MANAGEMENT, "key").every((k) => permissions.includes(k))}
									onChange={() => toggleMultiplePermissions(mapBy(ASSIGNMENT_MANAGEMENT, "key").filter(enableCheckbox))}>
									Select all
								</Checkbox>
							</div>
							<Separator />
							<div className="grid grid-cols-2 gap-4">
								{ASSIGNMENT_MANAGEMENT.map(({label, key}) => (
									<Checkbox
										disabled={!enableCheckbox(key)}
										key={key}
										isChecked={permissions.includes(key)}
										onChange={() => togglePermissions(key)}>
										{label}
									</Checkbox>
								))}
							</div>
						</div>

						<div className="flex flex-col gap-4">
							<div className="w-full flex items-center justify-between">
								<b>Workflow Management</b>
								<Checkbox
									disabled={!canEditPermissions || disableEdit}
									isChecked={mapBy(WORKFLOW_MANAGEMENT, "key").every((k) => permissions.includes(k))}
									onChange={() => toggleMultiplePermissions(mapBy(WORKFLOW_MANAGEMENT, "key").filter(enableCheckbox))}>
									Select all
								</Checkbox>
							</div>
							<Separator />
							<div className="grid grid-cols-2 gap-4">
								{WORKFLOW_MANAGEMENT.map(({label, key}) => (
									<Checkbox
										disabled={!enableCheckbox(key)}
										key={key}
										isChecked={permissions.includes(key)}
										onChange={() => togglePermissions(key)}>
										{label}
									</Checkbox>
								))}
							</div>
						</div>
					</section>
				</section>
			</>
		</>
	);
}
