import { DepartmentSectionBriefSchema, DepartmentService } from "../../../../client";
import { useEffect, useState } from "react";
import { Anchor, Checkbox, Group, Stack, Text } from "@mantine/core";


type Props = {
    userSectionIsChiefMap: Map<number, boolean>;
}

const UserDepartmentInput = ({ userSectionIsChiefMap }: Props) => {
    const [allDepartmentSections, setAllDepartmentSections] = useState<DepartmentSectionBriefSchema[]>([]);

    useEffect(() => {
        DepartmentService.getSections()
            .then(res => {
                setAllDepartmentSections(res.departmentSections);
            })
            .catch(err => console.log(err));
    }, []);

    const getUserParticipationRole = (sectionId: number) => {
        if (!userSectionIsChiefMap.has(sectionId)) return;
        if (userSectionIsChiefMap.get(sectionId)) return "Руководитель";
        return "Сотрудник";
    };

    const toggleUserParticipationRole = (sectionId: number) => {
        if (!userSectionIsChiefMap.has(sectionId)) return;
        userSectionIsChiefMap.set(sectionId, !userSectionIsChiefMap.get(sectionId));
    };

    const onSectionChoice = (sectionId: number) => {
        if (!userSectionIsChiefMap.has(sectionId)) {
            userSectionIsChiefMap.set(sectionId, false);
        } else {
            userSectionIsChiefMap.delete(sectionId);
        }
    };

    const userParticipationRoleButton = (sectionId: number) => {
        const role = getUserParticipationRole(sectionId);
        if (!role) return;
        return (
            <Anchor onClick={() => toggleUserParticipationRole(sectionId)}>
                <Text size={"sm"}>{role}</Text>
            </Anchor>
        );
    };

    const departmentSectionChoice = (section: DepartmentSectionBriefSchema) => {
        return (
            <Group
                key={section.id}
                wrap={"nowrap"}
                justify={"space-between"}
                gap={0}
            >
                <Group wrap={"nowrap"} w={"70%"}>
                    <Checkbox
                        variant={"default"}
                        checked={userSectionIsChiefMap.has(section.id)}
                        onChange={() => onSectionChoice(section.id)}
                    />
                    <Text size={"sm"}>{section.name}</Text>
                </Group>
                {userParticipationRoleButton(section.id)}
            </Group>
        );
    };

    return (
        <Stack>
            {allDepartmentSections.map((section) => departmentSectionChoice(section))}
        </Stack>
    );
};

export default UserDepartmentInput;
