import { useForm } from "@mantine/form";
import { ContextModalProps } from "@mantine/modals";
import { Button, Checkbox, Flex, rem } from "@mantine/core";
import { DepartmentSectionSchema, DepartmentService } from "../../../../../client";
import AddUserToDepartmentModalForm from "../types/AddUserToDepartmentModalForm.tsx";
import { notifications } from "../../../../../shared/lib/notifications.ts";
import UserForDepartmentSelect from "../components/UserForDepartmentSelect.tsx";

type Props = {
    departmentSection: DepartmentSectionSchema;
    fetchDepartments: () => void;
}

const AddUserToDepartmentModal = ({
                                      context,
                                      id,
                                      innerProps,
                                  }: ContextModalProps<Props>) => {
    const initialValues = {
        isChief: false,
    };
    const form = useForm<AddUserToDepartmentModalForm>({
        initialValues,
        validate: {
            user: user => !user && "Необходимо выбрать пользователя",
        },
    });

    const onSubmit = () => {
        if (!form.values.user) return;
        DepartmentService.addUser({
            requestBody: {
                userId: form.values.user.id,
                sectionId: innerProps.departmentSection.id,
                isChief: form.values.isChief,
            },
        })
            .then(({ ok, message }) => {
                notifications.guess(ok, { message });
                innerProps.fetchDepartments();
            })
            .catch(err => console.log(err));

        context.closeContextModal(id);
    };

    return (
        <form onSubmit={form.onSubmit(() => onSubmit())}>
            <Flex
                direction={"column"}
                gap={rem(10)}
            >
                <UserForDepartmentSelect
                    label={"Пользователь"}
                    {...form.getInputProps("user")}
                    sectionid={innerProps.departmentSection.id}
                />
                <Checkbox
                    label={"Является руководителем"}
                    {...form.getInputProps("isChief", { type: "checkbox" })}
                />
                <Button
                    variant={"default"}
                    type={"submit"}
                >
                    Сохранить
                </Button>
            </Flex>
        </form>
    );
};

export default AddUserToDepartmentModal;
