import BlockList, { IBlock } from "@Front/Components/DesignSystem/BlockList";
import SearchBar from "@Front/Components/DesignSystem/SearchBar";
import Module from "@Front/Config/Module";
import { OfficeRole } from "le-coffre-resources/dist/Admin";
import { useRouter } from "next/router";
import React, { useCallback, useState } from "react";

import classes from "./classes.module.scss";
import Link from "next/link";
import Button from "@Front/Components/DesignSystem/Button";

type IProps = {
	roles: OfficeRole[];
	onSelectedRole?: (role: OfficeRole) => void;
	onCloseLeftSide?: () => void;
};

export default function RoleListContainer(props: IProps) {
	const [filteredRoles, setFilteredRoles] = useState<OfficeRole[]>(props.roles);
	const router = useRouter();

	const { roleUid } = router.query;

	const filterRoles = useCallback(
		(input: string) => {
			const filteredRoles = props.roles.filter((role) => {
				return role.name?.toLowerCase().includes(input.toLowerCase());
			});
			setFilteredRoles(filteredRoles);
		},
		[props.roles],
	);

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

	return (
		<div className={classes["root"]}>
			<div className={classes["header"]}>
				<div className={classes["searchbar"]}>
					<SearchBar onChange={filterRoles} placeholder="Chercher un rôle" />
				</div>
				<div className={classes["folderlist-container"]}>
					<BlockList
						blocks={filteredRoles
							.filter((role) => {
								if (role.name === "admin") return false;
								return true;
							})
							.map((role) => {
								return {
									name: role.name,
									id: role.uid!,
									selected: role.uid === roleUid,
								};
							})}
						onSelectedBlock={onSelectedBlock}
					/>
				</div>
			</div>
			<div>
				<Link href={Module.getInstance().get().modules.pages.Roles.pages.Create.props.path}>
					<Button fullwidth={true}>Créer un rôle</Button>
				</Link>
			</div>
		</div>
	);
}
