import { Table, Input, Typography, Space } from 'antd'
import { ColumnsType, TableProps } from 'antd/lib/table'
import { useState } from 'react'
import { Link } from 'react-router-dom'

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

import { CreateCPPO } from './Create'

const CPPO = () => {
  const columns: ColumnsType<FormsTenant> = [
    {
      title: 'AWS CPPO Reseller',
      dataIndex: 'name',
      render(value, record, index) {
        return (
          <Space direction="vertical">
            {record.name}
            <Typography.Text type="secondary">{record.id}</Typography.Text>
          </Space>
        )
      }
    },
    {
      title: 'Status',
      dataIndex: 'status'
    },
    {
      title: 'Email',
      dataIndex: 'email'
    },
    {
      title: 'Actions',
      fixed: 'right',
      render: (value, record) => {
        return (
          <div>
            <Link to={`/cppo/${record.id}`}>Detail</Link>
          </div>
        )
      }
    }
  ]
  const [pageConfig, setPageConfig] = useState<{
    page: number
    pageSize?: number
    search?: string
  }>({
    page: 1,
    pageSize: 10,
    search: ''
  })
  const { data, isLoading } = useListTenants({
    org_tag: 'aws_cppo',
    page: pageConfig.page,
    per_page: pageConfig.pageSize,
    search: pageConfig.search
  })

  const onPaginationChange = (page: number, pageSize?: number) => {
    setPageConfig({ page, pageSize: pageSize || 10 })
  }

  const handleTableChange: TableProps<any>['onChange'] = (
    pagination,
    filters,
    sorter
  ) => {
    // return reload()
  }

  return (
    <div>
      <ListToolBar
        reload={async () => {}}
        actions={[
          <CreateCPPO
            action="add"
            onComplete={() => {
              setPageConfig({ page: 1, search: '' })
            }}
          />,
          <Input.Group compact className="list-search-bar-container">
            <Input.Search
              placeholder="Search by ID/Name/Email"
              style={{ width: '18rem' }}
              onSearch={(value: string) => {
                setPageConfig({
                  page: 1,
                  pageSize: 10,
                  search: value
                })
              }}
              allowClear
            />
          </Input.Group>
        ]}
      ></ListToolBar>
      <Table
        columns={columns}
        rowKey="id"
        dataSource={data?.data.items || []}
        loading={isLoading}
        size="small"
        // scroll={{ x: 1400 }}
        pagination={{
          current: pageConfig.page,
          pageSize: pageConfig.pageSize || 10,
          total: data?.data.total || 0,
          onChange: onPaginationChange
        }}
        onChange={handleTableChange}
      />
    </div>
  )
}

export default CPPO
