import Module from "@Front/Config/Module";
import { OfficeFolder } from "le-coffre-resources/dist/Notary";
import { EDocumentStatus } from "le-coffre-resources/dist/Notary/Document";
import { useRouter } from "next/router";
import React, { useCallback, useEffect } from "react";

import classes from "./classes.module.scss";
import { IBlock } from "../SearchBlockList/BlockList/Block";
import SearchBlockList from "../SearchBlockList";

type IProps = {
	folders: OfficeFolder[];
	isArchived: boolean;
	onSelectedFolder?: (folder: OfficeFolder) => void;
	onCloseLeftSide?: () => void;
};

export default function FolderListContainer(props: IProps) {
	const router = useRouter();
	const { folderUid } = router.query;
	const { folders, isArchived } = props;

	const redirectPath: string = isArchived
		? Module.getInstance().get().modules.pages.Folder.pages.FolderArchived.pages.FolderInformation.props.path
		: Module.getInstance().get().modules.pages.Folder.pages.FolderInformation.props.path;

	const getBlocks = useCallback(
		(folders: OfficeFolder[]): IBlock[] => {
			const pendingFolders = folders
				.filter((folder) => {
					const pendingDocuments = (folder.documents ?? []).filter(
						(document) => document.document_status === EDocumentStatus.DEPOSITED,
					);
					return pendingDocuments.length >= 1;
				})
				.sort((folder1, folder2) => {
					return folder1.created_at! > folder2.created_at! ? -1 : 1;
				});

			const otherFolders = folders
				.filter((folder) => {
					const pendingDocuments = (folder.documents ?? []).filter(
						(document) => document.document_status === EDocumentStatus.DEPOSITED,
					);
					return pendingDocuments.length === 0;
				})
				.sort((folder1, folder2) => {
					return folder1.created_at! > folder2.created_at! ? -1 : 1;
				});

			return [...pendingFolders, ...otherFolders].map((folder) => {
				return {
					id: folder.uid!,
					primaryText: folder.name,
					secondaryText: folder.folder_number,
					isActive: folderUid === folder.uid,
					showAlert: folder.documents?.some((document) => document.document_status === EDocumentStatus.DEPOSITED),
				};
			});
		},
		[folderUid],
	);

	const [blocks, setBlocks] = React.useState<IBlock[]>(getBlocks(folders));

	const onSelectedFolder = (block: IBlock) => {
		props.onCloseLeftSide && props.onCloseLeftSide();
		const folder = folders.find((folder) => folder.uid === block.id);
		if (!folder) return;
		props.onSelectedFolder && props.onSelectedFolder(folder);
		const path = redirectPath.replace("[folderUid]", folder.uid ?? "");
		router.push(path);
	};

	useEffect(() => {
		setBlocks(getBlocks(folders));
	}, [folders, getBlocks]);

	return (
		<div className={classes["root"]}>
			<SearchBlockList
				blocks={blocks}
				onSelectedBlock={onSelectedFolder}
				bottomButton={{
					link: Module.getInstance().get().modules.pages.Folder.pages.CreateFolder.props.path,
					text: "Créer un dossier",
				}}
			/>
		</div>
	);
}
