import LandingImage from "../Login/landing-connect.jpeg";
import Image from "next/image";
import CoffreIcon from "@Assets/Icons/coffre.svg";
import { useRouter } from "next/router";
import React, { useEffect } from "react";
import classes from "./classes.module.scss";
import Module from "@Front/Config/Module";
import Auth from "@Front/Api/Auth/IdNot";
import DefaultDoubleSidePage from "@Front/Components/LayoutTemplates/DefaultDoubleSidePage";
import Typography, { ITypo } from "@Front/Components/DesignSystem/Typography";
import Button, { EButtonVariant } from "@Front/Components/DesignSystem/Button";
import Loader from "@Front/Components/DesignSystem/Loader";
import UserStore from "@Front/Stores/UserStore";
import Link from "next/link";
import JwtService from "@Front/Services/JwtService/JwtService";
import CookieService from "@Front/Services/CookieService/CookieService";

export default function LoginCallBack() {
	const router = useRouter();

	useEffect(() => {
		async function getUser() {
			const code = router.query["code"];
			if (code) {
				try {
					const token = await Auth.getInstance().getIdnotJwt(code as string);
					if (!token) return router.push(Module.getInstance().get().modules.pages.Login.props.path);
					await UserStore.instance.connect(token.accessToken, token.refreshToken);
					return router.push(Module.getInstance().get().modules.pages.Folder.props.path);
				} catch (e) {
					router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=1");
					return;
				}
			}
			const refreshToken = CookieService.getInstance().getCookie("leCoffreRefreshToken");
			if(!refreshToken) return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=1");
			const isTokenRefreshed = await JwtService.getInstance().refreshToken(refreshToken);
			if (isTokenRefreshed) {
				return router.push(Module.getInstance().get().modules.pages.Folder.props.path);
			}
			return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=2");
		}
		getUser();
	}),
		[router];

	return (
		<DefaultDoubleSidePage title={"Login"} image={LandingImage}>
			<div className={classes["root"]}>
				<Image alt="coffre" src={CoffreIcon} />
				<Typography typo={ITypo.H1}>
					<div className={classes["title"]}>Connexion espace professionnel</div>
				</Typography>
				<div className={classes["loader"]}>
					<Loader />
				</div>
				<Typography typo={ITypo.P_18}>
					<div className={classes["forget-password"]}>Vous n'arrivez pas à vous connecter ?</div>
				</Typography>
				<Link href="mailto:g.texier@notaires.fr">
					<Button variant={EButtonVariant.LINE}>Contacter l'administrateur</Button>
				</Link>
			</div>
		</DefaultDoubleSidePage>
	);
}
