import { QuestionCircleOutlined } from '@ant-design/icons'
import { Button, Popconfirm, Space, Table, message } from 'antd'
import { ColumnsType } from 'antd/lib/table'
import { useState } from 'react'
import { Link, useHistory } from 'react-router-dom'

import {
  useDeleteNotificationWorkflow,
  useDuplicateWorkflow,
  useGetNotificationWorkflow
} from 'apiClient/services/notification'
import { FormsWorkflow } from 'apiClient/services/notification/interface'
import { format } from 'utils/time'

const pageSize = 10

export default function NotificationList() {
  const [page, setPage] = useState<number>(1)

  const history = useHistory()

  const {
    data,
    isFetching,
    refetch: refetchList
  } = useGetNotificationWorkflow((page - 1).toString(), pageSize.toString(), {
    query: {
      enabled: !!page,
      refetchOnWindowFocus: false,
      refetchInterval: false,
      refetchIntervalInBackground: false,
      retry: false
    }
  })

  const { mutateAsync: deleteNotification, isLoading: deleteLoding } =
    useDeleteNotificationWorkflow()

  const { mutateAsync: duplicateNotification, isLoading: duplicateLoding } =
    useDuplicateWorkflow()

  const handleDelete = async (record: FormsWorkflow) => {
    try {
      await deleteNotification({
        data: {
          worker_flow_id: record.worker_flow_id
        } as FormsWorkflow
      })
      message.success('Successfully deleted')
      refetchList()
    } catch (e) {
      message.success('Failed to delete')
    }
  }

  const handleDuplicate = async (record: FormsWorkflow) => {
    try {
      await duplicateNotification({ workflowId: record.worker_flow_id || '' })
      message.success('Successfully duplicated')
      refetchList()
    } catch (e) {
      message.success('Failed to duplicate')
    }
  }

  const columns: ColumnsType<FormsWorkflow> = [
    {
      title: 'Notification Subject',
      dataIndex: 'worker_flow_name',
      key: 'name',
      render: (text, record) => (
        <Link to={`/notification/detail/${record.worker_flow_id}`}>{text}</Link>
      )
    },
    {
      title: 'create time',
      dataIndex: 'created_at',
      key: 'time',
      render: (text) => `${format(text, undefined, 'YYYY-MM-DD HH:mm:ss', 0)}`
    },
    {
      title: 'action',
      width: 200,
      dataIndex: 'action',
      key: 'action',
      render: (_, record) => {
        return (
          <Space size="middle">
            <Popconfirm
              title="Are you sure to duplicate this template?"
              onConfirm={() => handleDuplicate(record)}
              okText="Yes"
              cancelText="No"
            >
              <Button type="primary" loading={duplicateLoding}>
                Duplicate
              </Button>
            </Popconfirm>
            <Button
              type="primary"
              onClick={() =>
                history.push(`notification/${record.worker_flow_id}/statistics`)
              }
            >
              Statistics
            </Button>
            <Popconfirm
              icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
              title="Are you sure to delete this template?"
              onConfirm={() => handleDelete(record)}
              okText="Yes"
              cancelText="No"
            >
              <Button type="primary" loading={deleteLoding}>
                Delete
              </Button>
            </Popconfirm>
          </Space>
        )
      }
    }
  ]

  return (
    <Table
      rowKey="worker_flow_id"
      loading={isFetching}
      dataSource={data?.data.work_flows}
      pagination={{
        current: data?.data.page_query?.page,
        pageSize: data?.data.page_query?.page_size,
        total: data?.data.count,
        onChange: setPage
      }}
      columns={columns}
    />
  )
}
