import DangerMessage from "@/components/message/DangerMessage";
import SuccessMessage from "@/components/message/SuccessMessage";
import { useConfirm } from "@/hooks/AuthHooks";
import { useTimedModal } from "@/providers/TimedModalProvider";
import { useEffect } from "react";
import { useNavigate, useParams } from "react-router";


export default function ConfirmPage(){
	const { confirmToken } = useParams();
	const navigate = useNavigate();
	const { addErrorMessage, addSuccessMessage } = useTimedModal();


	const { mutate: confirmQueryMutate, status: confirmQueryStatus, error: confirmQueryError, reset: confirmQueryReset } = useConfirm();

	useEffect(() => {
		if(confirmQueryStatus === "idle"){
			confirmQueryMutate(confirmToken ?? "");
		}
		else if(confirmQueryStatus === "error"){
			addErrorMessage(confirmQueryError.message);
			confirmQueryReset();
		}
		else if(confirmQueryStatus === "success"){
			addSuccessMessage("Email confirmed. Please Login.");
			confirmQueryReset();
			navigate("/login");
		}
	}, [ confirmToken, confirmQueryMutate, confirmQueryStatus, confirmQueryError, confirmQueryReset, navigate, addSuccessMessage, addErrorMessage ]);


	if(confirmQueryStatus === "pending"){
		return <main>Confirming...</main>;
	}
	else if(confirmQueryStatus === "error"){
		return <main><DangerMessage>Error: {confirmQueryError.message}</DangerMessage></main>;
	}
	else if(confirmQueryStatus === "success"){
		return <main><SuccessMessage>Confirmed</SuccessMessage></main>;
	}
}
