import Button from "@/components/Low/Button";
import Checkbox from "@/components/Low/Checkbox";
import {PERMISSIONS} from "@/constants/userPermissions";
import {Type, User} from "@/interfaces/user";
import {USER_TYPE_LABELS} from "@/resources/user";
import axios from "axios";
import clsx from "clsx";
import {capitalize} from "lodash";
import moment from "moment";
import {useEffect, useState} from "react";
import ReactDatePicker from "react-datepicker";
import {toast} from "react-toastify";
import ShortUniqueId from "short-unique-id";
import {checkAccess, getTypesOfUser} from "@/utils/permissions";
import {PermissionType} from "@/interfaces/permissions";
import usePermissions from "@/hooks/usePermissions";

const USER_TYPE_PERMISSIONS: {
	[key in Type]: {perm: PermissionType | undefined; list: Type[]};
} = {
	student: {
		perm: "createCodeStudent",
		list: [],
	},
	teacher: {
		perm: "createCodeTeacher",
		list: [],
	},
	agent: {
		perm: "createCodeCountryManager",
		list: ["student", "teacher", "corporate", "mastercorporate"],
	},
	corporate: {
		perm: "createCodeCorporate",
		list: ["student", "teacher"],
	},
	mastercorporate: {
		perm: undefined,
		list: ["student", "teacher", "corporate"],
	},
	admin: {
		perm: "createCodeAdmin",
		list: ["student", "teacher", "agent", "corporate", "admin", "mastercorporate"],
	},
	developer: {
		perm: undefined,
		list: ["student", "teacher", "agent", "corporate", "admin", "developer", "mastercorporate"],
	},
};

interface Props {
	user: User;
	permissions: PermissionType[];
	onFinish: () => void;
}

export default function CodeGenerator({user, permissions, onFinish}: Props) {
	const [generatedCode, setGeneratedCode] = useState<string>();
	const [expiryDate, setExpiryDate] = useState<Date | null>(
		user?.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).toDate() : null,
	);
	const [isExpiryDateEnabled, setIsExpiryDateEnabled] = useState(true);
	const [type, setType] = useState<Type>("student");

	useEffect(() => {
		if (!isExpiryDateEnabled) setExpiryDate(null);
	}, [isExpiryDateEnabled]);

	const generateCode = (type: Type) => {
		const uid = new ShortUniqueId();
		const code = uid.randomUUID(6);

		axios
			.post("/api/code", {type, codes: [code], expiryDate})
			.then(({data, status}) => {
				if (data.ok) {
					toast.success(`Successfully generated a ${capitalize(type)} code!`, {
						toastId: "success",
					});
					setGeneratedCode(code);
					return;
				}

				if (status === 403) {
					toast.error(data.reason, {toastId: "forbidden"});
				}
			})
			.catch(({response: {status, data}}) => {
				if (status === 403) {
					toast.error(data.reason, {toastId: "forbidden"});
					return;
				}

				toast.error(`Something went wrong, please try again later!`, {
					toastId: "error",
				});
			});
	};

	return (
		<div className="flex flex-col gap-4 border p-4 border-mti-gray-platinum rounded-xl">
			<label className="font-normal text-base text-mti-gray-dim">User Code Generator</label>
			{user && (
				<select
					defaultValue="student"
					onChange={(e) => setType(e.target.value as typeof user.type)}
					className="p-6 w-full min-w-[350px] min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer bg-white">
					{Object.keys(USER_TYPE_LABELS)
						.filter((x) => {
							const {list, perm} = USER_TYPE_PERMISSIONS[x as Type];
							return checkAccess(user, getTypesOfUser(list), permissions, perm);
						})
						.map((type) => (
							<option key={type} value={type}>
								{USER_TYPE_LABELS[type as keyof typeof USER_TYPE_LABELS]}
							</option>
						))}
				</select>
			)}
			{user && checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"]) && (
				<>
					<div className="-md:flex-row -md:items-center flex justify-between gap-2 md:flex-col 2xl:flex-row 2xl:items-center">
						<label className="text-mti-gray-dim text-base font-normal">Expiry Date</label>
						<Checkbox isChecked={isExpiryDateEnabled} onChange={setIsExpiryDateEnabled} disabled={!!user.subscriptionExpirationDate}>
							Enabled
						</Checkbox>
					</div>
					{isExpiryDateEnabled && (
						<ReactDatePicker
							className={clsx(
								"flex min-h-[70px] w-full cursor-pointer justify-center rounded-full border p-6 text-sm font-normal focus:outline-none",
								"hover:border-mti-purple tooltip",
								"transition duration-300 ease-in-out",
							)}
							filterDate={(date) =>
								moment(date).isAfter(new Date()) &&
								(user.subscriptionExpirationDate ? moment(date).isBefore(user.subscriptionExpirationDate) : true)
							}
							dateFormat="dd/MM/yyyy"
							selected={expiryDate}
							onChange={(date) => setExpiryDate(date)}
						/>
					)}
				</>
			)}
			{checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"], permissions, "createCodes") && (
				<Button onClick={() => generateCode(type)} disabled={isExpiryDateEnabled ? !expiryDate : false}>
					Generate
				</Button>
			)}
			<label className="font-normal text-base text-mti-gray-dim">Generated Code:</label>
			<div
				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",
					"transition duration-300 ease-in-out",
				)}
				data-tip="Click to copy"
				onClick={() => {
					if (generatedCode) navigator.clipboard.writeText(generatedCode);
				}}>
				{generatedCode}
			</div>
			{generatedCode && <span className="text-sm text-mti-gray-dim font-light">Give this code to the user to complete their registration</span>}
		</div>
	);
}
