import React, { createContext, FC, useContext } from "react";
import { UserSchema, UserService } from "../../../../../client";
import useUsersList from "../../../hooks/useUsersList.tsx";
import { notifications } from "../../../../../shared/lib/notifications.ts";
import { CRUDTableProps } from "../../../../../types/CRUDTable.tsx";

type UsersTabContextState = {
    refetch: () => void;
    usersCrud: CRUDTableProps<UserSchema>;
};

const UsersTabContext = createContext<UsersTabContextState | undefined>(
    undefined,
);

const useUsersTabContextState = () => {
    const { objects: users, refetch } = useUsersList();

    const onChange = (user: UserSchema) => {
        UserService.updateUser({
            requestBody: {
                data: {
                    ...user,
                    positionKey: user.position?.key,
                    roleKey: user.role.key,
                },
            },
        }).then(async ({ ok, message }) => {
            notifications.guess(ok, { message });
            if (!ok) return;
            await refetch();
        });
    };
    const onDelete = async (user: UserSchema) => {
        onChange({ ...user, isDeleted: true });
    };
    const onCreate = (user: UserSchema) => {
        UserService.createUser({
            requestBody: {
                data: {
                    ...user,
                    telegramId: -1,
                },
            },
        }).then(async ({ ok, message }) => {
            notifications.guess(ok, { message });
            if (!ok) return;
            await refetch();
        });
    };

    const usersCrud: CRUDTableProps<UserSchema> = {
        items: users,
        onCreate,
        onDelete,
        onChange,
    }

    return {
        usersCrud,
        refetch,
    };
};

type UsersTabContextProviderProps = {
    children: React.ReactNode;
};

export const UsersTabContextProvider: FC<UsersTabContextProviderProps> = ({ children }) => {
    const state = useUsersTabContextState();
    return (
        <UsersTabContext.Provider value={state}>
            {children}
        </UsersTabContext.Provider>
    );
};

export const useUsersTabContext = () => {
    const context = useContext(UsersTabContext);
    if (!context) {
        throw new Error(
            "useUsersTabContext must be used within a UsersTabContextProvider",
        );
    }
    return context;
};
