import EFolderStatus from "le-coffre-resources/dist/Customer/EFolderStatus";
import { OfficeFolder } from "le-coffre-resources/dist/Notary";
import React, { useCallback, useEffect } from "react";
import { EDocumentStatus } from "le-coffre-resources/dist/Notary/Document";

import Module from "@Front/Config/Module";
import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block";
import { useRouter } from "next/router";
import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList";

import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
import { idAsUrl } from "@Front/Utils/ProcessIdUtils";

type IProps = IPropsDashboardWithList & {
	isArchived?: boolean;
};

export default function DefaultNotaryDashboard(props: IProps) {
	const { isArchived = false } = props;
	const router = useRouter();
	const [folders, setFolders] = React.useState<OfficeFolder[]>([]);
	const { folderUid } = router.query;

	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: any[]): IBlock[] => {	
			const pendingFolders = folders
				.filter((folder) => {
					const pendingDocuments = (folder.documents ?? []).filter(
						(document: any) => 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: any) => document.document_status === EDocumentStatus.DEPOSITED,
					);
					return pendingDocuments.length === 0;
				})
				.sort((folder1, folder2) => {
					return folder1.created_at! > folder2.created_at! ? -1 : 1;
				});

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

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

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

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

	useEffect(() => {
		let targetedStatus: EFolderStatus = EFolderStatus["LIVE" as keyof typeof EFolderStatus];
		if (isArchived) targetedStatus = EFolderStatus.ARCHIVED;

		/* TODO: review
		const query: IGetFoldersParams = {
			q: {
				where: { status: targetedStatus },
				include: {
					deed: { include: { deed_type: true } },
					office: true,
					customers: {
						include: {
							contact: true,
							documents: {
								include: {
									folder: true,
									document_type: true,
									files: true,
								},
							},
						},
					},
					documents: {
						include: {
							depositor: {
								include: {
									contact: true,
								},
							},
						},
					},
				},
			},
		};

		Folders.getInstance()
			.get(query)
			.then((folders) => setFolders(folders));
			*/

		FolderService.getFolders((processes: Record<string, any>) => {	
			if (Object.keys(processes).length > 0) {
				let folders: any[] = Object.entries(processes).map(([processId, process]) => {
					const res = {
						...process,
						processId: processId
					};
					return res;
				});


				// FilterBy status
				folders = folders.filter((folder: any) => {
					const matches = folder.status === targetedStatus;
					return matches;
				});

				setFolders(folders);
			} else {
				console.debug('[DefaultNotaryDashboard] No processes found');
			}
		});
	}, [isArchived]);

	return (
		<DefaultDashboardWithList
			{...props}
			onSelectedBlock={onSelectedBlock}
			blocks={blocks}
			bottomButton={{
				link: Module.getInstance().get().modules.pages.Folder.pages.CreateFolder.props.path,
				text: "Créer un dossier",
			}}
		/>
	);
}
