import Button from "@/components/Low/Button";
import Checkbox from "@/components/Low/Checkbox";
import {PERMISSIONS} from "@/constants/userPermissions";
import {Type, User} from "@/interfaces/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";

export default function CodeGenerator({user}: {user: User}) {
	const [generatedCode, setGeneratedCode] = useState<string>();
	const [expiryDate, setExpiryDate] = useState<Date | null>(null);
	const [isExpiryDateEnabled, setIsExpiryDateEnabled] = useState(true);

	useEffect(() => {
		if (user.type === "admin" || user.type === "teacher") {
			setExpiryDate(user.subscriptionExpirationDate || null);
		}
	}, [user]);

	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(`You do not have permission to generate a ${capitalize(type)} code!`, {toastId: "forbidden"});
				}
			})
			.catch(({response: {status}}) => {
				if (status === 403) {
					toast.error(`You do not have permission to generate a ${capitalize(type)} code!`, {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>
			<div className="grid grid-cols-2 gap-4">
				<Button
					className="w-48"
					variant="outline"
					onClick={() => generateCode("student")}
					disabled={!PERMISSIONS.generateCode.student.includes(user.type) || (isExpiryDateEnabled && expiryDate === null)}>
					Student
				</Button>
				<Button
					className="w-48"
					variant="outline"
					onClick={() => generateCode("teacher")}
					disabled={!PERMISSIONS.generateCode.teacher.includes(user.type) || (isExpiryDateEnabled && expiryDate === null)}>
					Teacher
				</Button>
				<Button
					className="w-48"
					variant="outline"
					onClick={() => generateCode("admin")}
					disabled={!PERMISSIONS.generateCode.admin.includes(user.type) || (isExpiryDateEnabled && expiryDate === null)}>
					Admin
				</Button>
				<Button
					className="w-48"
					variant="outline"
					onClick={() => generateCode("owner")}
					disabled={!PERMISSIONS.generateCode.owner.includes(user.type) || (isExpiryDateEnabled && expiryDate === null)}>
					Owner
				</Button>
			</div>
			{(user.type === "developer" || user.type === "owner") && (
				<>
					<div className="flex items-center justify-between">
						<label className="font-normal text-base text-mti-gray-dim">Expiry Date</label>
						<Checkbox isChecked={isExpiryDateEnabled} onChange={setIsExpiryDateEnabled}>
							Enabled
						</Checkbox>
					</div>
					{isExpiryDateEnabled && (
						<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",
								"transition duration-300 ease-in-out",
							)}
							filterDate={(date) => moment(date).isAfter(new Date())}
							dateFormat="dd/MM/yyyy"
							selected={expiryDate}
							onChange={(date) => setExpiryDate(date)}
						/>
					)}
				</>
			)}
			<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>
	);
}
