import { useForm } from "@mantine/form";
import { StatusSchema, StatusService } from "../../../../../client";
import { notifications } from "../../../../../shared/lib/notifications.ts";

type StatusForm = {
    name: string;
}

type Props = {
    boardId?: number;
    status?: StatusSchema;
    refetch: () => void;
    closeModal: () => void;
};

const useStatusModal = ({
                            boardId,
                            status,
                            refetch,
                            closeModal,
                        }: Props) => {
    const form = useForm<StatusForm>({
        initialValues: {
            name: status ? status.name : "",
        },
        validate: {
            name: name => !name && "Необходимо ввести название статуса",
        },
    });

    const createBoard = (values: StatusForm) => {
        if (!boardId) return;
        StatusService.createStatus({
            requestBody: {
                status: {
                    boardId,
                    name: values.name,
                },
            },
        })
            .then(({ ok, message }) => {
                if (!ok) {
                    notifications.error({ message });
                    return;
                }
                refetch();
                closeModal();
            })
            .catch(err => console.log(err));
    };

    const updateBoard = (values: StatusForm) => {
        if (!status) return;

        StatusService.updateStatus({
            requestBody: {
                status: {
                    ...status,
                    name: values.name,
                },
            },
        })
            .then(({ ok, message }) => {
                if (!ok) {
                    notifications.error({ message });
                    return;
                }
                refetch();
                closeModal();
            })
            .catch(err => console.log(err));
    };

    const onSubmit = (values: StatusForm) => {
        if (status) {
            updateBoard(values);
            return;
        }
        createBoard(values);
    };

    return {
        form,
        onSubmit,
    };
};

export default useStatusModal;
