import { Button, Modal } from 'antd'
import { useEffect, useState } from 'react'
import { AdminUserRoleService } from '../../services/api'
import LoaderPortal from '../../components/LoaderPortal'
import { invokeWebApiWrapperAsync } from '../../components/factory'
import { EditableTable, makeActionHandler, makeColumn, makeSelectColumn } from '../../components/Table'

export const toHexString = (num, size) => '0x' + ('0'.repeat(size) + num.toString(16).toUpperCase()).slice(-size)

const columns = [
    makeColumn('Имена прав', 'name', {
        width: 400,
        editable: true,
        formItemRules: [{
            required: true,
            message: 'Пожалуйста, введите имя права'
        }],
    }),
]

export const RolePermissions = ({ value, onChange }) => {
    const [isModalVisible, setIsModalVisible] = useState(false)
    const [list, setList] = useState([])

    const save = () => {
        const newValue = list.map((value) => value.name)
        if(!onChange(newValue))
            setIsModalVisible(false)
    }

    const add = (permission) => {
        permission.key = Date.now()
        setList((prevList) => {
            if (!prevList) prevList = []
            prevList.push(permission)
            return prevList
        })
    }

    const edit = (permission) => {
        if (!permission.key) return
        const idx = list.findIndex(v => v.key === permission.key)
        if (idx < 0) return
        setList((prevList) => {
            prevList[idx] = permission
            return prevList
        })
    }

    const remove = (permission) => {
        if (!permission.key) return
        const idx = list.findIndex(v => v.key === permission.key)
        if (idx < 0) return
        setList((prevList) => {
            prevList.splice(idx, 1)
            return prevList
        })
    }

    return (
        <>
            <Button type={'link'} onClick={() => setIsModalVisible(true)}>Редактировать</Button>
            <Modal
                title={'Права доступа'}
                centered
                visible={isModalVisible}
                width={750}
                onCancel={() => setIsModalVisible(false)}
                onOk={save}
                okText={'Сохранить'}
            >
                <EditableTable
                    size={'small'}
                    bordered
                    columns={columns}
                    dataSource={list}
                    onRowAdd={add}
                    onRowEdit={edit}
                    onRowDelete={remove}
                />
            </Modal>
        </>
    )
}

export const RoleController = () => {
    const [roles, setRoles] = useState([])
    const [showLoader, setShowLoader] = useState(false)
    const [columns, setColumns] = useState([])

    const updateTable = () => invokeWebApiWrapperAsync(
        async () => {
            const roles = await AdminUserRoleService.getAll()
            setRoles(roles)
        },
        setShowLoader,
        `Не удалось загрузить список прав`
    )

    useEffect(() => {
        const options = roles?.map((r) => ({ value: r.id, label: r.caption })) ?? []
        setColumns([
            makeColumn('Название', 'caption', { width: 200, editable: true }),
            makeSelectColumn('Роль-родитель', 'idParent', options, options[0], {
                width: 200,
                editable: true
            }),
            makeColumn('Права доступа', 'permissions', {
                width: 200,
                editable: true,
                input: <RolePermissions />,
                render: (permissions) => permissions?.join(', ') ?? '',
            })
        ])
    }, [roles])

    useEffect(updateTable, [])

    const handlerProps = {
        service: AdminUserRoleService,
        setLoader: setShowLoader,
        errorMsg: `Не удалось выполнить операцию`,
        onComplete: updateTable
    }

    return (
        <LoaderPortal show={showLoader}>
            <EditableTable
                size={'small'}
                bordered
                columns={columns}
                dataSource={roles}
                onRowAdd={makeActionHandler('insert', handlerProps)}
                onRowEdit={makeActionHandler('update', handlerProps)}
                onRowDelete={makeActionHandler('delete', handlerProps)}
            />
        </LoaderPortal>
    )
}

export default RoleController
