import { memo } from 'react'
import { Tag, Tooltip } from 'antd'

import { UserRoleDto } from '../../services/api'
import { Grid, GridItem } from '../Grid'
import PermissionView from './PermissionView'

export type RoleViewProps = {
    role?: UserRoleDto
}

export const RoleView = memo<RoleViewProps>(({ role }) => {
    const hasIncludedRoles = (role?.roles?.length && role.roles.length > 0) ? 1 : 0
    const hasPermissions = (role?.permissions?.length && role.permissions.length > 0) ? 1 : 0

    return role ? (
        <Tooltip
            overlayInnerStyle={{ width: '400px' }}
            title={
                <Grid>
                    <GridItem row={1} col={1}>Название:</GridItem>
                    <GridItem row={1} col={2}>{role.caption}</GridItem>

                    <GridItem row={2} col={1}>Включённые роли:</GridItem>
                    {hasIncludedRoles ? (
                        <GridItem row={3} col={1} colSpan={3}>
                            {role.roles?.map((role, i) => (
                                <Tag key={i} color={'blue'}>
                                    <RoleView role={role} />
                                </Tag>
                            ))}
                        </GridItem>
                    ) : (
                        <GridItem row={2} col={2}>Отсутствуют</GridItem>
                    )}

                    <GridItem row={3 + hasIncludedRoles} col={1}>Тип:</GridItem>
                    <GridItem row={3 + hasIncludedRoles} col={2}>{role.idType}</GridItem>

                    <GridItem row={4 + hasIncludedRoles} col={1}>Разрешения:</GridItem>
                    {hasPermissions ? (
                        <GridItem row={5 + hasIncludedRoles} col={1} colSpan={3}>
                            {role.permissions?.map((permission, i) => (
                                <Tag key={i} color={'blue'}>
                                    <PermissionView info={permission} />
                                </Tag>
                            ))}
                        </GridItem>
                    ) : (
                        <GridItem row={4 + hasIncludedRoles} col={2}>Отсутствуют</GridItem>
                    )}
                </Grid>
            }
        >
            {role.caption}
        </Tooltip>
    ) : (
        <Tooltip title={'нет данных'}>-</Tooltip>
    )
})
