import { Box, Button, Typography } from "@mui/material"
import { useState } from "react"
import { userApi } from "../../../api/user/requests"
import { enqueueSnackbar } from "notistack"

export const UserPrivilegeDecrement = ({ userId }: { userId: string }) => {

    const [disabled, setDisabled] = useState(false)
    const [readyDecrement, setReadyDecrement] = useState(false)
    const [info, setInfo] = useState("")

    const handleClick = () => {
        if (readyDecrement) {
            readyHC()
        } else {
            notReadyHC()
        }
    }
    const readyHC = async () => {
        setDisabled(true)
        // await userApi.privilegeDecrement(userId)
        const [response] = await userApi.privilegeDecrement(userId)
        // await userApi.privilegeDecrement("656fa783f827770622bb8774")
        console.log(response)
        if (response !== null) {
        setReadyDecrement(false)
        setDisabled(false)
        setInfo("Привилегия была успешно уменьшена :)")
        setInterval(() => {
            setInfo("")
        }, 5000)
        } else {
            enqueueSnackbar("произошла ошибка")

        }
    }
    const notReadyHC = () => {
        setDisabled(true)
        setInfo("Подтвердите действие через 5 секунд")
        setReadyDecrement(true)
        setInterval(() => {
            setDisabled(false)
            setInfo("")
        }, 5000)
    }

    return (
        <Box>
            <Typography variant="h6">Удалить единичку привилегии:</Typography>
            <Button
                onClick={handleClick}
                disabled={disabled}
            >
                {
                    readyDecrement ? 
                    "уменьшить"
                    :
                    "начать"
                }
            </Button>
            <Typography
                color="red"
            >{info}</Typography>

        </Box>
    )
}
