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 DefaultDoubleSidePage from "@Front/Components/LayoutTemplates/DefaultDoubleSidePage";
import Typography, { ITypo } from "@Front/Components/DesignSystem/Typography";
import Button, { EButtonStyleType, EButtonVariant } from "@Front/Components/DesignSystem/Button";
import Loader from "@Front/Components/DesignSystem/Loader";
import Customers, { ICustomerTokens } from "@Front/Api/Auth/Id360/Customers/Customers";
import CustomerStore from "@Front/Stores/CustomerStore";
import Module from "@Front/Config/Module";
import Link from "next/link";
import JwtService from "@Front/Services/JwtService/JwtService";
import CookieService from "@Front/Services/CookieService/CookieService";

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

	useEffect(() => {
		const getReport = async () => {
			const tokenid360 = router.query["token"];
			if (tokenid360) {
				let token: ICustomerTokens | undefined;
				try {
					token = await Customers.getInstance().loginCallback(tokenid360);
				} catch (e) {
					console.error(e);
					router.push(Module.getInstance().get().modules.pages.CustomersLogin.props.path + "?error=1");
					return;
				}
				CustomerStore.instance.connect(token.accessToken, token.refreshToken);
				router.push(Module.getInstance().get().modules.pages.Folder.pages.Select.props.path);
			}
			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.pages.Select.props.path);
			}
			return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=2");
		};
		getReport();
	}),
		[router];

	return (
		<DefaultDoubleSidePage title={"Login"} image={LandingImage}>
			<div className={classes["root"]}>
				<Image alt="coffre" src={CoffreIcon} />
				<Typography typo={ITypo.DISPLAY_LARGE}>
					<div className={classes["title"]}>Connexion espace client</div>
				</Typography>
				<div className={classes["loader"]}>
					<Loader />
				</div>
				<Typography typo={ITypo.TEXT_LG_REGULAR}>
					<div className={classes["forget-password"]}>Vous n'arrivez pas à vous connecter ?</div>
				</Typography>
				<Link href="mailto:support@lecoffre.io">
					<Button variant={EButtonVariant.PRIMARY} styleType={EButtonStyleType.TEXT}>
						Contacter l'administrateur
					</Button>
				</Link>
			</div>
		</DefaultDoubleSidePage>
	);
}
