import CoffreIcon from "@Assets/Icons/coffre.svg";
import franceConnectLogo from "./france-connect.svg";
import Button, { EButtonVariant } from "@Front/Components/DesignSystem/Button";
import Typography, { ITypo } from "@Front/Components/DesignSystem/Typography";
import DefaultDoubleSidePage from "@Front/Components/LayoutTemplates/DefaultDoubleSidePage";
import Image from "next/image";
import { useRouter } from "next/router";
import { useCallback, useEffect, useState } from "react";
import Customers from "@Front/Api/Auth/Id360/Customers/Customers";
import classes from "./classes.module.scss";
import LandingImage from "./landing-connect.jpeg";
import Link from "next/link";
import Confirm from "@Front/Components/DesignSystem/Modal/Confirm";

export default function Login() {
	const router = useRouter();
	const error = router.query["error"];

	const [isErrorModalOpen, setIsErrorModalOpen] = useState(false);

	const redirectCustomerOnConnection = useCallback(() => {
		async function getCustomer() {
			try {
				const loginRes = await Customers.getInstance().login();
				router.push(loginRes.enrollment.franceConnectUrl);
			} catch (e) {
				console.error(e);
			}
		}
		getCustomer();
	}, [router]);

	const openErrorModal = useCallback(() => {
		setIsErrorModalOpen(true);
	}, []);

	const closeErrorModal = useCallback(() => {
		setIsErrorModalOpen(false);
	}, []);

	useEffect(() => {
		if (error === "1") openErrorModal();
	}, [error, openErrorModal]);

	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 client</div>
				</Typography>
				<Image alt="france-connect" src={franceConnectLogo} onClick={redirectCustomerOnConnection} className={classes["logo"]} />
				<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>
			<Confirm
				isOpen={isErrorModalOpen}
				onClose={closeErrorModal}
				showCancelButton={false}
				onAccept={closeErrorModal}
				closeBtn
				header={"Erreur"}
				confirmText={"OK"}>
				<div className={classes["modal-content"]}>
					<Typography typo={ITypo.P_16} className={classes["text"]}>
						Une erreur est survenue lors de la connexion. Veuillez réessayer.
					</Typography>
				</div>
			</Confirm>
		</DefaultDoubleSidePage>
	);
}
