import { Select, Tag } from 'antd'
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 } from '../../components/Table'
import { AdminPermissionService, AdminUserRoleService } from '../../services/api'
import { arrayOrDefault } from '../../utils'

const PermissionTag = memo(({ permissions, value, onChange }) => {
    const [options, setOptions] = useState([])

    useEffect(() => {
        setOptions(permissions.map((elm) => ({ key: Date.now(), value: `${elm.id}`, label: elm.name })))
    }, [permissions])

    console.log({ permissions, value })

    const onSelectChange = (values) => {
        const arr = values.map((id) => permissions.find((elm) => `${elm.id}` === id))
        onChange?.(arr)
    }

    const selectValue = value?.map((val) => `${val.id}`)

    return (
        <Select
            showSearch
            mode={'tags'}
            options={options}
            value={selectValue}
            onChange={onSelectChange}
        />
    )
})

export const RoleController = () => {
    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 }),
            makeSelectColumn('Роль-родитель', 'idParent', options, options[0], {
                width: 200,
                editable: true
            }, { allowClear: true }),
            makeColumn('Права доступа', 'permissions', {
                width: 200,
                editable: true,
                input: <PermissionTag permissions={permissions} />,
                render: (item) => item?.map((elm) => (
                    <Tag key={elm.name} color={'blue'}>
                        <PermissionView info={elm} />
                    </Tag>
                )) ?? '-',
            }),
        ])
    }, [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('update', handlerProps)}
                onRowDelete={makeActionHandler('delete', handlerProps)}
            />
        </LoaderPortal>
    )
}

export default RoleController
