import React from "react";
import { redirect } from "next/navigation";
import { useMutation } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { Text } from "@mantine/core";
import { modals } from "@mantine/modals";
import { HttpValidationError, ModuleSchemaOutput } from "@/lib/client";
import {
    createModuleMutation,
    deleteModuleMutation,
} from "@/lib/client/@tanstack/react-query.gen";
import { notifications } from "@/lib/notifications";

export type ModulesActions = {
    onCreate: () => void;
    onUpdate: (module: ModuleSchemaOutput) => void;
    onDelete: (module: ModuleSchemaOutput) => void;
};

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

const useModulesActions = ({ refetchModules }: Props): ModulesActions => {
    const onError = (error: AxiosError<HttpValidationError>, _: any) => {
        console.error(error);
        notifications.error({
            message: error.response?.data?.detail as string | undefined,
        });
    };

    const createMutation = useMutation({
        ...createModuleMutation(),
        onError,
    });

    const onCreate = () => {
        modals.openContextModal({
            modal: "moduleCreatorModal",
            title: "Создание модуля",
            innerProps: {
                onCreate: (data, onSuccess) =>
                    createMutation.mutate(
                        { body: { entity: data } },
                        {
                            onSuccess: () => {
                                refetchModules();
                                onSuccess && onSuccess();
                            },
                        }
                    ),
            },
        });
    };

    const onUpdate = (module: ModuleSchemaOutput) => {
        redirect(`/module-editor/${module.id}`);
    };

    const deleteMutation = useMutation({
        ...deleteModuleMutation(),
        onError,
        onSuccess: refetchModules,
    });

    const onDelete = (module: ModuleSchemaOutput) => {
        modals.openConfirmModal({
            title: "Удаление модуля",
            children: (
                <Text>
                    Вы уверены, что хотите удалить модуль "{module.label}"?
                </Text>
            ),
            confirmProps: { color: "red" },
            onConfirm: () => deleteMutation.mutate({ path: { pk: module.id } }),
        });
    };

    return {
        onCreate,
        onUpdate,
        onDelete,
    };
};

export default useModulesActions;
