import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block";
import Module from "@Front/Config/Module";
import JwtService from "@Front/Services/JwtService/JwtService";
import { OfficeFolder } from "le-coffre-resources/dist/Customer";
import { useRouter } from "next/router";
import React, { useEffect, useState } from "react";

import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList";

import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";

type IProps = IPropsDashboardWithList & {
	isReady: boolean;
};

export default function DefaultCustomerDashboard(props: IProps) {
	const router = useRouter();
	const { folderUid, profileUid } = router.query;
	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));
			*/

		if (props.isReady) {
			FolderService.getFolders().then((processes: any[]) => {
				if (processes.length > 0) {
					let folders: any[] = processes.map((process: any) => process.processData);
					
					// Filter By customer.uid
					folders = folders.filter((folder: any) => folder.customers.some((customer: any) => customer.uid === profileUid));

					setFolders(folders);
				}
			});
		}
	}, [props.isReady]);

	const onSelectedBlock = (block: IBlock) => {
		const folder = folders.find((folder) => folder.uid === block.id);
		if (!folder) return;
		router.push(
			Module.getInstance()
				.get()
				.modules.pages.ClientDashboard.props.path
				.replace("[folderUid]", folder.uid ?? "")
				.replace("[profileUid]", profileUid as string ?? ""),
		);
	};
	return <DefaultDashboardWithList {...props} onSelectedBlock={onSelectedBlock} blocks={getBlocks(folders)} headerConnected={false} isCustomer={true} />;

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