import { SyncOutlined } from '@ant-design/icons'
import { Button, Input, Modal, Table } from 'antd'
import { useCallback, useMemo, useState } from 'react'

import {
  userServiceListUsers,
  userServiceSyncUsersAsync
} from 'apiClient/services/core-server'
import { V1User } from 'apiClient/services/core-server/interface'
import { useTable, ListToolBar } from 'components/Table'
import { showErrorModal, toListDataResponse } from 'pages/IAM/utils'

export default function Users() {
  const [searchParams, setSearchParams] = useState<{
    userKeyword?: string
  }>({})

  const getData = async (params?: Partial<PageInfo>) => {
    const response = await userServiceListUsers({
      page: params?.page,
      perPage: params?.pageSize,
      userKeyword: searchParams.userKeyword
    })

    return toListDataResponse(response, (data) => data.users)
  }

  const {
    dataSource,
    loading,
    reload,
    resetPageIndex,
    paginationProps,
    onTableChange
  } = useTable<ListData<V1User>>(getData, [], {
    pagination: true
  })

  const handleSync = useCallback(async () => {
    try {
      await userServiceSyncUsersAsync({})
      Modal.success({
        title: 'Info',
        content: (
          <div>
            <p>User sync has been triggered successfully.</p>
          </div>
        ),
        onOk() {}
      })
      reload()
    } catch (error) {
      showErrorModal(error)
    }
  }, [reload])

  const columns = useMemo(() => {
    return [
      {
        title: 'Email',
        dataIndex: 'email',
        render: (type: string) => {
          return <a href={'/iam/entity/users/' + type}>{type}</a>
        }
      },
      {
        title: 'Name',
        dataIndex: 'larkUserName'
      },
      {
        title: 'Department',
        dataIndex: 'larkDepartmentName',
        render: (department: string, user: V1User) => {
          if (!department) {
            return '-'
          }
          if (!user.larkDepartmentId) {
            return department
          }
          return (
            <a href={'/iam/entity/usergroups/' + user.larkDepartmentId}>
              {department}
            </a>
          )
        }
      },
      {
        title: 'Lark Type',
        dataIndex: 'larkType',
        render: (type: string) => {
          return type.toUpperCase()
        }
      }
    ]
  }, [])

  const onSearch = (keyword: string) => {
    setSearchParams({
      userKeyword: keyword || undefined
    })
    resetPageIndex()
    return reload()
  }

  const actions = useMemo(
    () => [
      <Input.Search
        style={{ width: '24rem' }}
        placeholder="Search by Email or Name"
        onSearch={onSearch}
        onChange={(event) => {
          if (!event.target.value) {
            onSearch('')
          }
        }}
        allowClear
      />,

      <Button name="sync" icon={<SyncOutlined />} onClick={handleSync}>
        Sync
      </Button>
    ],
    // eslint-disable-next-line react-hooks/exhaustive-deps
    []
  )

  return (
    <>
      <ListToolBar reload={reload} actions={actions} />

      <Table<V1User>
        columns={columns}
        rowKey="email"
        dataSource={dataSource}
        loading={loading}
        pagination={paginationProps}
        onChange={onTableChange}
        size="small"
      />
    </>
  )
}
