import { Button, Input, message, Popconfirm } from 'antd'
import Table, { ColumnsType } from 'antd/lib/table'
import { useState } from 'react'

import {
  useFeatureWhitelistControllerDeleteFeatureWhitelist,
  useFeatureWhitelistControllerListFeatureWhitelists
} from 'apiClient/services/devops'
import type { FeatureWlFeatureWhitelistInfo } from 'apiClient/services/devops/interface'
import ListToolBar from 'components/Table/ListToolBar'

import {
  FeatureWhitelistCreateForm,
  normalizeEmailSuffixes,
  normalizeOrgIds
} from './Edit'

export const FeatureWhitelist = () => {
  const [deletingName, setDeletingName] = useState<string>()
  const [searchName, setSearchName] = useState<string>()
  const { data, isLoading, refetch } =
    useFeatureWhitelistControllerListFeatureWhitelists(
      { name: searchName, page_size: 100 },
      {
        query: {
          refetchOnWindowFocus: false
        }
      }
    )
  const { mutateAsync: deleteFeatureWhitelist } =
    useFeatureWhitelistControllerDeleteFeatureWhitelist()

  const columns: ColumnsType<FeatureWlFeatureWhitelistInfo> = [
    {
      title: 'Feature',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: 'Description',
      dataIndex: 'description',
      key: 'description'
    },
    {
      title: 'By Org ID',
      dataIndex: 'org_ids',
      key: 'org_ids',
      render: (orgIds?: unknown[]) => normalizeOrgIds(orgIds)?.join(', ') || '-'
    },
    {
      title: 'By Email Suffix',
      dataIndex: 'email_suffixes',
      key: 'email_suffixes',
      render: (emailSuffixes?: string[]) =>
        normalizeEmailSuffixes(emailSuffixes)?.join(', ') || '-'
    },
    {
      title: 'Actions',
      dataIndex: 'actions',
      key: 'actions',
      render: (_, record) => {
        return (
          <>
            <FeatureWhitelistCreateForm
              action="update"
              record={record}
              onSuccess={async () => {
                await refetch()
              }}
            />
            <Popconfirm
              title="Are you sure delete this feature whitelist?"
              okText="Yes"
              cancelText="No"
              onConfirm={async () => {
                try {
                  setDeletingName(record.name)
                  await deleteFeatureWhitelist({ name: record.name! })
                  await refetch()
                  message.success('Deleted successfully.')
                } finally {
                  setDeletingName(undefined)
                }
              }}
            >
              <Button type="link" danger loading={deletingName === record.name}>
                Delete
              </Button>
            </Popconfirm>
          </>
        )
      }
    }
  ]

  return (
    <div>
      <ListToolBar
        actions={[
          <Input.Search
            key="search-feature-whitelist"
            allowClear
            placeholder="Search by feature name"
            style={{ width: 260 }}
            onChange={(event) => {
              if (!event.target.value) {
                setSearchName(undefined)
              }
            }}
            onSearch={(value) => {
              setSearchName(value.trim() || undefined)
            }}
          />,
          <FeatureWhitelistCreateForm
            key="add-feature-whitelist"
            action="add"
            onSuccess={async () => {
              await refetch()
            }}
          />
        ]}
      />
      <Table
        columns={columns}
        dataSource={data?.data?.items || []}
        loading={isLoading}
        rowKey="name"
      />
    </div>
  )
}

export default FeatureWhitelist
