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

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;
		}

		OfficeRoleService.getOfficeRoles().then(async (processes: any[]) => {
			if (processes.length > 0) {
				let officeRoles: any[] = processes.map((process: any) => process.processData);

				// FilterBy office.uid
				officeRoles = officeRoles.filter((officeRole: any) => officeRole.office.uid === office.uid);

				// OrderBy name
				officeRoles = officeRoles.sort((a: any, b: any) => a.name.localeCompare(b.name));

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

	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.name,
						isActive: role.uid === roleUid,
					}))
					: []
			}
			bottomButton={{
				link: Module.getInstance().get().modules.pages.Roles.pages.Create.props.path,
				text: "Créer un rôle",
			}}
		/>
	);
}
