import UserDepartmentInput from "../../../../components/UserDepartmentInput/UserDepartmentInput.tsx";
import { Button, Fieldset, Stack } from "@mantine/core";
import { useMap } from "@mantine/hooks";
import { UserSchema, UserService } from "../../../../../../client";
import { notifications } from "../../../../../../shared/lib/notifications.ts";

type Props = {
    user: UserSchema;
    closeModal: () => void;
    refetch: () => void;
}

const DepartmentSectionsTab = ({ user, closeModal, refetch }: Props) => {
    const userSectionIsChiefMap = useMap<number, boolean>(
        user.departmentSections?.map(s => [s.sectionId, s.isChief]),
    );

    const onSubmit = () => {
        const departmentSections = userSectionIsChiefMap
            .entries()
            .toArray()
            .map(([sectionId, isChief]) => ({
                sectionId,
                isChief,
            }));

        UserService.updateUserDepartmentSections({
            userId: user.id,
            requestBody: {
                departmentSections,
            },
        })
            .then(({ ok, message }) => {
                refetch();
                notifications.guess(ok, { message });
                closeModal();
            })
            .catch(err => console.log(err));
    };

    return (
        <Stack>
            <Fieldset legend={"Отделы"}>
                <UserDepartmentInput
                    userSectionIsChiefMap={userSectionIsChiefMap}
                />
            </Fieldset>
            <Button
                variant={"default"}
                onClick={onSubmit}
            >
                Сохранить отделы
            </Button>
        </Stack>
    );
};

export default DepartmentSectionsTab;
