import { ContextModalProps } from "@mantine/modals";
import { Button, Stack, TextInput } from "@mantine/core";
import { BaseProjectSchema, ProjectService } from "../../../../../../../client";
import { useForm } from "@mantine/form";
import { notifications } from "../../../../../../../shared/lib/notifications.ts";


type Props = {
    refetchProjects: () => void;
};

const CreateProjectModal = ({
                                context,
                                id,
                                innerProps,
                            }: ContextModalProps<Props>) => {
    const closeModal = () => context.closeContextModal(id);

    const form = useForm<BaseProjectSchema>({
        initialValues: { name: "" },
        validate: {
            name: name => !name && "Название не заполнено",
        },
    });

    const onSubmit = (project: BaseProjectSchema) => {
        ProjectService.createProject({
            requestBody: { project },
        })
            .then(({ ok, message }) => {
                if (!ok) {
                    notifications.error({ message });
                    return;
                }
                innerProps.refetchProjects();
                closeModal();
            })
            .catch(err => console.log(err));
    };

    return (
        <form onSubmit={form.onSubmit(values => onSubmit(values))}>
            <Stack gap={"md"}>
                <TextInput
                    label={"Название"}
                    {...form.getInputProps("name")}
                />
                <Button
                    variant={"default"}
                    type={"submit"}
                >
                    Сохранить
                </Button>
            </Stack>
        </form>
    );
};

export default CreateProjectModal;
