import Button from "@/components/Low/Button";
import {User} from "@/interfaces/user";
import {sendEmailVerification} from "@/utils/email";
import axios from "axios";
import {useRouter} from "next/router";
import {Divider} from "primereact/divider";
import {toast} from "react-toastify";

interface Props {
	user: User;
	isLoading: boolean;
	setIsLoading: (isLoading: boolean) => void;
}

export default function EmailVerification({user, isLoading, setIsLoading}: Props) {
	const router = useRouter();

	const onSuccess = () => toast.success("An e-mail has been sent, please make sure to check your spam folder!");

	const onError = (e: Error) => {
		console.error(e);
		toast.error("Something went wrong, please logout and re-login.", {toastId: "send-verify-error"});
	};

	const logout = async () => {
		axios.post("/api/logout").finally(() => {
			setTimeout(() => router.reload(), 500);
		});
	};

	return (
		<>
			<div className="flex flex-col items-center gap-6 w-full -lg:px-8 lg:w-1/2 relative">
				<h4 className="font-semibold text-2xl text-mti-purple-light">Please confirm your account!</h4>
				<span className="text-center">
					An e-mail has been sent to <span className="italic text-mti-purple-light">{user?.email}</span>, please click the link in it to
					confirm your account to be able to use the application. <br /> <br />
					Please refresh this page once it has been verified.
				</span>
				<Button
					className="mt-8 w-full"
					color="purple"
					disabled={isLoading}
					onClick={() => sendEmailVerification(setIsLoading, onSuccess, onError)}>
					Resend e-mail
				</Button>
			</div>
			<Divider className="max-w-xs lg:max-w-md" />
			<span className="text-mti-gray-cool text-sm font-normal">
				<button className="text-mti-purple-light" onClick={logout}>
					Log out instead
				</button>
			</span>
		</>
	);
}
