import backgroundImage from "@Assets/images/background_refonte.svg";
import LogoIcon from "@Assets/logo_small_blue.svg";
import Folders from "@Front/Api/LeCoffreApi/Customer/Folders/Folders";
import SearchBlockList from "@Front/Components/DesignSystem/SearchBlockList";
import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block";
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
import DefaultDoubleSidePage from "@Front/Components/LayoutTemplates/DefaultDoubleSidePage";
import JwtService from "@Front/Services/JwtService/JwtService";
import { OfficeFolder } from "le-coffre-resources/dist/Customer";
import Image from "next/image";
import { useRouter } from "next/router";
import { useCallback, useEffect, useState } from "react";

import classes from "./classes.module.scss";
import Module from "@Front/Config/Module";

export default function SelectFolder() {
	const router = useRouter();
	const [folders, setFolders] = useState<OfficeFolder[]>([]);

	useEffect(() => {
		const jwt = JwtService.getInstance().decodeCustomerJwt();
		if (!jwt) return;

		Folders.getInstance()
			.get({
				q: {
					where: {
						customers: {
							some: {
								contact: {
									email: jwt.email,
								},
							},
						},
					},
					orderBy: [
						{
							created_at: "desc",
						},
					],
					include: {
						customers: true,
					},
				},
			})
			.then((folders) => setFolders(folders));
	}, []);

	const handleSelectBlock = useCallback(
		(folder: IBlock) => {
			router.push(
				Module.getInstance()
					.get()
					.modules.pages.ClientDashboard.props.path.replace("[folderUid]", folder.id ?? ""),
			);
		},
		[router],
	);

	return (
		<DefaultDoubleSidePage title="Sélectionner un dossier" image={backgroundImage}>
			<div className={classes["root"]}>
				<div className={classes["title-container"]}>
					<Image src={LogoIcon} alt="logo" width={56} />
					<Typography typo={ETypo.TITLE_H1} color={ETypoColor.TEXT_ACCENT}>
						Vos dossiers en cours
					</Typography>

					<Typography typo={ETypo.TITLE_H5} color={ETypoColor.TEXT_PRIMARY}>
						Veuillez sélectionner le dossier pour lequel vous souhaitez déposer ou consulter des documents.
					</Typography>
				</div>

				<Typography typo={ETypo.TITLE_H6} color={ETypoColor.TEXT_ACCENT}>
					Liste des dossiers disponibles :
				</Typography>

				<SearchBlockList blocks={getBlocks(folders)} onSelectedBlock={handleSelectBlock} fullwidth />
			</div>
		</DefaultDoubleSidePage>
	);
}

function getBlocks(folders: OfficeFolder[]): IBlock[] {
	return folders.map((folder) => {
		return {
			id: folder.uid!,
			primaryText: folder.name!,
			secondaryText: folder.folder_number!,
		};
	});
}
