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

import classes from "./classes.module.scss";
import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block";
import BlockList from "@Front/Components/DesignSystem/SearchBlockList/BlockList";

type IProps = {
	offices: Office[];
	onSelectedOffice?: (office: Office) => void;
	onCloseLeftSide?: () => void;
};

export default function OfficeListContainer(props: IProps) {
	const [filteredOffices, setFilteredOffices] = useState<Office[]>(props.offices);
	const router = useRouter();

	const { officeUid } = router.query;
	const filterOffices = useCallback(
		(input: string) => {
			const filteredOffices = props.offices.filter((office) => {
				return (
					office.name.toLowerCase().includes(input.toLowerCase()) || office.crpcen?.toLowerCase().includes(input.toLowerCase())
				);
			});
			setFilteredOffices(filteredOffices);
		},
		[props.offices],
	);

	const onSelectedBlock = useCallback(
		(block: IBlock) => {
			props.onCloseLeftSide && props.onCloseLeftSide();
			const redirectPath = Module.getInstance().get().modules.pages.Offices.pages.OfficesInformations.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={filterOffices} placeholder="Chercher un office" />
				</div>
				<div className={classes["folderlist-container"]}>
					<BlockList
						blocks={filteredOffices.map((office) => {
							return {
								primaryText: office.crpcen + " - " + office.name,
								id: office.uid!,
								selected: office.uid === officeUid,
							};
						})}
						onSelectedBlock={onSelectedBlock}
					/>
				</div>
			</div>
		</div>
	);
}
