import {useGetAllUsersQuery, useSetIsBlockedMutation} from "../../../../../Api/usersApi.js";
import {useGetRolesQuery} from "../../../../../Api/rolesApi.js";
import {Grid, notification} from "antd";
import {useDispatch} from "react-redux";
import {setIsCurrentUser, setSelectedUser} from "../../../../../Redux/Slices/usersSlice.js";
import {openModal} from "../../../../../Redux/Slices/adminSlice.js";
import {useMemo, useState} from "react";

const {useBreakpoint} = Grid;

const useUsersManageTab = () => {
    const dispatch = useDispatch();
    const screens = useBreakpoint();

    const [searchString, setSearchString] = useState("");

    const {
        data: users = [], isLoading, isError,
    } = useGetAllUsersQuery(undefined, {
        pollingInterval: 10000,
    });

    const {data: roles = [], isLoading: isLoadingRoles, isError: isErrorRoles} = useGetRolesQuery(undefined, {
        pollingInterval: 60000,
    });
    const [setIsBlocked, {isLoading: isBlocking, isError: isBlockError}] = useSetIsBlockedMutation();

    const containerStyle = {padding: screens.xs ? 16 : 24};

    const openEditModal = (user) => {
        dispatch(setSelectedUser(user));
        dispatch(setIsCurrentUser(true));
    };

    const openCreateModal = () => {
        dispatch(openModal());
    };

    const handleSearch = (e) => {
        setSearchString(e.target.value);
    };

    const setIsBlockUser = async (user, isBlock) => {
        try {
            await setIsBlocked({userId: user, isBlocked: isBlock}).unwrap();

            notification.success({
                message: "Успех",
                description: isBlock
                    ? "Пользователь успешно заблокирован"
                    : "Пользователь успешно разблокирован",
                placement: "topRight",
            })
        } catch (error) {
            notification.error({
                message: "Ошибка",
                description: error?.data?.detail ? error?.data?.detail : isBlock
                    ? "Не удалось заблокировать пользователя"
                    : "Не удалось разблокировать пользователя",
                placement: "topRight",
            })
        }
    };

    const filteredUsers = useMemo(() => {
        return users.filter((user) => {
            return Object.entries(user).some(([key, value]) => {
                if (typeof value === "string") {
                    return value.toString().toLowerCase().includes(searchString.toLowerCase());
                }
            });
        });
    }, [users, searchString]);

    return {
        roles,
        isBlocking,
        filteredUsers,
        isLoading: isLoading || isLoadingRoles,
        isError: isError || isErrorRoles,
        isUpdating: false,
        isUpdateError: false,
        isCreating: false,
        isCreateError: false,
        containerStyle,
        openEditModal,
        openCreateModal,
        setIsBlockUser,
        handleSearch,
    };
};

export default useUsersManageTab;