import React, { useEffect } from "react";

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

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

type IProps = IPropsDashboardWithList;

export default function DefaultUserDashboard(props: IProps) {
	const [users, setUsers] = React.useState<any[] | null>(null);
	const router = useRouter();
	const { userUid } = router.query;
	useEffect(() => {
		const user: any = UserStore.instance.getUser();
		if (!user) return;
		const officeId: string = user.office.uid;

		CollaboratorService.getCollaborators((processes: any[]) => {
			if (processes.length > 0) {
				let collaborators: any[] = processes.map((process: any) => process.processData);

				// FilterBy office.uid
				collaborators = collaborators.filter((collaborator: any) => collaborator.office.uid === officeId);

				setUsers(collaborators);
			}
		});
	}, []);

	const onSelectedBlock = (block: IBlock) => {
		router.push(Module.getInstance().get().modules.pages.Users.pages.UsersInformations.props.path.replace("[uid]", block.id));
	};

	return (
		<DefaultDashboardWithList
			{...props}
			onSelectedBlock={onSelectedBlock}
			blocks={
				users
					? users.map((user) => ({
						id: user.uid!,
						primaryText: user.contact?.first_name + " " + user.contact?.last_name,
						isActive: user.uid === userUid,
						secondaryText: user.office?.crpcen + " - " + user.office?.name,
					}))
					: []
			}
		/>
	);
}
