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";
import {useFilePicker} from "use-file-picker";

export default function BatchCodeGenerator({user}: {user: User}) {
	const [emails, setEmails] = useState<string[]>([]);
	const [isLoading, setIsLoading] = useState(false);
	const [expiryDate, setExpiryDate] = useState<Date | null>(null);
	const [isExpiryDateEnabled, setIsExpiryDateEnabled] = useState(true);

	const {openFilePicker, filesContent} = useFilePicker({
		accept: ".txt",
		multiple: false,
	});

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

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

	useEffect(() => {
		if (filesContent.length > 0) {
			const file = filesContent[0];
			const emails = file.content
				.split("\n")
				.filter((x) => new RegExp(/^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$/).test(x));

			if (emails.length === 0) {
				toast.error("Please upload a .txt file containing e-mails, one per line!");
				return;
			}

			setEmails([...new Set(emails)]);
		}
	}, [filesContent]);

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

		setIsLoading(true);
		axios
			.post("/api/code", {type, codes, emails, expiryDate})
			.then(({data, status}) => {
				if (data.ok) {
					toast.success(`Successfully generated ${capitalize(type)} codes and they have been notified by e-mail!`, {toastId: "success"});
					return;
				}

				if (status === 403) {
					toast.error(`You do not have permission to generate ${capitalize(type)} codes!`, {toastId: "forbidden"});
				}
			})
			.catch(({response: {status}}) => {
				if (status === 403) {
					toast.error(`You do not have permission to generate ${capitalize(type)} codes!`, {toastId: "forbidden"});
					return;
				}

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

	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">Choose a .txt file containing e-mails</label>
			<Button onClick={openFilePicker} isLoading={isLoading} disabled={isLoading}>
				{filesContent.length > 0 ? filesContent[0].name : "Choose a file"}
			</Button>
			{user && (user.type === "developer" || user.type === "owner") && (
				<>
					<div className="flex -md:flex-row md:flex-col -md:items-center 2xl:flex-row 2xl:items-center justify-between gap-2">
						<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">Select the type of user they should be</label>
			{user && (
				<div className="grid -md:grid-cols-2 md:grid-cols-1 xl:grid-cols-2 gap-4 place-items-center">
					<Button
						className="w-44 2xl:w-48"
						variant="outline"
						onClick={() => generateCode("student")}
						disabled={emails.length === 0 || isLoading || !PERMISSIONS.generateCode.student.includes(user.type)}>
						Student
					</Button>
					<Button
						className="w-44 2xl:w-48"
						variant="outline"
						onClick={() => generateCode("teacher")}
						disabled={emails.length === 0 || isLoading || !PERMISSIONS.generateCode.teacher.includes(user.type)}>
						Teacher
					</Button>
					<Button
						className="w-44 2xl:w-48"
						variant="outline"
						onClick={() => generateCode("corporate")}
						disabled={emails.length === 0 || isLoading || !PERMISSIONS.generateCode.corporate.includes(user.type)}>
						Admin
					</Button>
					<Button
						className="w-44 2xl:w-48"
						variant="outline"
						onClick={() => generateCode("owner")}
						disabled={emails.length === 0 || isLoading || !PERMISSIONS.generateCode.owner.includes(user.type)}>
						Owner
					</Button>
				</div>
			)}
		</div>
	);
}
