import { useForm } from "@mantine/form";
import { ContextModalProps } from "@mantine/modals";
import { Button, Flex, rem } from "@mantine/core";
import { DealSchema } from "../../../../../client";
import AssignUserModalForm from "../types/AssignUserModalForm.tsx";
import AvailableEmployeesSelect from "../components/AvailableEmployeesSelect.tsx";

type Props = {
    deal: DealSchema;
    manageEmployee: (dealId: number, userId: number, isAssign: boolean) => void;
}

const AssignEmployeeModal = ({
                                 context,
                                 id,
                                 innerProps,
                             }: ContextModalProps<Props>) => {
    const {
        deal,
        manageEmployee,
    } = innerProps;

    const form = useForm<Partial<AssignUserModalForm>>({
        validate: {
            employee: employee => !employee && "Необходимо выбрать работника",
        },
    });

    const onSubmit = () => {
        if (!form.values.employee) return;
        manageEmployee(deal.id, form.values.employee.id, true);
        context.closeContextModal(id);
    };

    return (
        <form onSubmit={form.onSubmit(() => onSubmit())}>
            <Flex
                direction={"column"}
                gap={rem(10)}
            >
                <AvailableEmployeesSelect
                    label={"Работник"}
                    placeholder={"Выберите работника"}
                    {...form.getInputProps("employee")}
                    dealId={deal.id}
                />
                <Button
                    variant={"default"}
                    type={"submit"}
                >
                    Сохранить
                </Button>
            </Flex>
        </form>
    );
};

export default AssignEmployeeModal;
