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 RoleService from "src/common/Api/LeCoffreApi/sdk/RoleService";

type IProps = IPropsDashboardWithList;

export default function DefaultRoleDashboard(props: IProps) {
	const [roles, setRoles] = React.useState<any[] | null>(null);

	const router = useRouter();
	const { roleUid } = router.query;

	useEffect(() => {
		const user: any = UserStore.instance.getUser();
		if (!user) {
			return;
		}

		const office: any = user.office;
		if (!office) {
			return;
		}

		RoleService.getRoles().then(async (processes: any[]) => {
			if (processes.length > 0) {
				let roles: any[] = processes.map((process: any) => process.processData);

				// FilterBy office.uid
				roles = roles.filter((role: any) => role.office.uid === office.uid);

				// OrderBy label
				roles = roles.sort((a: any, b: any) => a.label.localeCompare(b.label));

				setRoles(roles);
			}
		});
	}, []);

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

	return (
		<DefaultDashboardWithList
			{...props}
			onSelectedBlock={onSelectedBlock}
			blocks={
				roles
					? roles.map((role) => ({
						id: role.uid!,
						primaryText: role.label,
						isActive: role.uid === roleUid,
					}))
					: []
			}
			bottomButton={{
				link: Module.getInstance().get().modules.pages.Roles.pages.Create.props.path,
				text: "Créer un rôle",
			}}
		/>
	);
}
