import React from "react";
import { useMutation } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { Text } from "@mantine/core";
import { modals } from "@mantine/modals";
import {
    HttpValidationError,
    ProjectSchema,
    UpdateProjectSchema,
} from "@/lib/client";
import {
    createProjectMutation,
    deleteProjectMutation,
    updateProjectMutation,
} from "@/lib/client/@tanstack/react-query.gen";
import { notifications } from "@/lib/notifications";

type Props = {
    projects: ProjectSchema[];
    setProjects: React.Dispatch<React.SetStateAction<ProjectSchema[]>>;
    refetchProjects: () => void;
};

type ProjectsOperations = {
    onCreateProject: (name: string) => void;
    onUpdateProject: (projectId: number, project: UpdateProjectSchema) => void;
    onDeleteProject: (project: ProjectSchema) => void;
};

export const useProjectsOperations = ({
    projects,
    setProjects,
    refetchProjects,
}: Props): ProjectsOperations => {
    const onError = (error: AxiosError<HttpValidationError>) => {
        console.error(error);
        notifications.error({
            message: error.response?.data?.detail as string | undefined,
        });
        refetchProjects();
    };

    const createProject = useMutation({
        ...createProjectMutation(),
        onError,
        onSuccess: res => {
            setProjects([...projects, res.project]);
        },
    });

    const updateProject = useMutation({
        ...updateProjectMutation(),
        onError,
    });

    const deleteProject = useMutation({
        ...deleteProjectMutation(),
        onError,
    });

    const onCreateProject = (name: string) => {
        createProject.mutate({
            body: {
                project: {
                    name,
                },
            },
        });
    };

    const onUpdateProject = (
        projectId: number,
        project: UpdateProjectSchema
    ) => {
        updateProject.mutate({
            query: { projectId },
            body: { project },
        });

        setProjects(boards =>
            boards.map(oldProject =>
                oldProject.id !== projectId
                    ? oldProject
                    : {
                          id: oldProject.id,
                          name: project.name ? project.name : oldProject.name,
                      }
            )
        );
    };

    const onDeleteProject = (project: ProjectSchema) => {
        modals.openConfirmModal({
            title: "Удаление проекта",
            children: (
                <Text>
                    Вы уверены, что хотите удалить проект "{project.name}"?
                </Text>
            ),
            labels: { confirm: "Да", cancel: "Нет" },
            confirmProps: { color: "red" },
            onConfirm: () => {
                deleteProject.mutate({
                    query: { projectId: project.id },
                });
                setProjects(projects =>
                    projects.filter(p => p.id !== project.id)
                );
            },
        });
    };

    return {
        onCreateProject,
        onUpdateProject,
        onDeleteProject,
    };
};
