import { Button, Space, Table } from 'antd'
import { ColumnsType } from 'antd/lib/table'

import { FormsRbacRole } from 'apiClient/services/account/interface'
import { ListToolBar } from 'components/Table'

import { useFetchRBACRoles } from '../helpers'

import EditModal from './EditModal'
import { PrivilegesAssignModal } from './PermissionAssign'

const RolesPanel = () => {
  const { data, refetch, isLoading, isRefetching } = useFetchRBACRoles()

  const columns: ColumnsType<FormsRbacRole> = [
    {
      title: 'ID',
      dataIndex: 'id'
    },
    {
      title: 'Name',
      dataIndex: 'name'
    },
    {
      title: 'DisplayName',
      dataIndex: 'display_name'
    },
    {
      title: 'ScopeType',
      dataIndex: 'scope_type'
    },
    {
      title: 'Description',
      dataIndex: 'description'
    },
    {
      title: 'Action',
      dataIndex: 'action',
      render: (_: any, record: FormsRbacRole) => {
        return (
          <Space size="middle">
            <EditModal
              trigger={
                <Button style={{ padding: 0 }} type="link">
                  Edit
                </Button>
              }
              record={record}
              onComplete={refetch}
            />
            <PrivilegesAssignModal
              mode="view"
              title={`Privileges of ${record.display_name} Role`}
              roleId={record.id!}
              trigger={
                <Button type="link" style={{ padding: 0 }}>
                  View Privileges
                </Button>
              }
            />
          </Space>
        )
      }
    }
  ]
  return (
    <div>
      <ListToolBar
        reload={async () => {
          await refetch()
        }}
      />
      <Table
        columns={columns}
        loading={isLoading || isRefetching}
        dataSource={data}
        rowKey="id"
      />
    </div>
  )
}

export default RolesPanel
