import { memo, useEffect, useState } from 'react'

import LoaderPortal from '../../components/LoaderPortal'
import { PermissionView } from '../../components/Views'
import { invokeWebApiWrapperAsync } from '../../components/factory'
import { EditableTable, makeActionHandler, makeColumn, makeSelectColumn, makeTagColumn } from '../../components/Table'
import { AdminPermissionService, AdminUserRoleService } from '../../services/api'
import { arrayOrDefault } from '../../utils'
import { min1 } from '../../utils/validationRules'

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

    const loadRoles = async () => {
        const roles = await AdminUserRoleService.getAll()
        setRoles(Array.isArray(roles) ? roles : [])
    }

    useEffect(() => {
        const options = roles?.map((r) => ({ value: r.id, label: r.caption })) ?? []
        setColumns([
            makeColumn('Название', 'caption', { width: 200, editable: true, formItemRules: min1 }),
            makeSelectColumn('Роль-родитель', 'idParent', options, options[0], {
                width: 200,
                editable: true
            }, { allowClear: true }),
            makeTagColumn('Разрешения', 'permissions', permissions, 'id', 'name', {
                width: 200,
                editable: true,
                render: (permission) => <PermissionView info={permission} />,
            }),
        ])
    }, [roles, permissions])

    useEffect(() => invokeWebApiWrapperAsync(
        async () => {
            const permissions = await AdminPermissionService.getAll()
            setPermissions(arrayOrDefault(permissions))
            await loadRoles()
        },
        setShowLoader,
        `Не удалось загрузить список прав`
    ), [])

    const handlerProps = {
        service: AdminUserRoleService,
        setLoader: setShowLoader,
        errorMsg: `Не удалось выполнить операцию`,
        onComplete: async () => invokeWebApiWrapperAsync(
            loadRoles,
            setShowLoader,
            `Не удалось загрузить список прав`
        )
    }

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

export default RoleController
