import { PlusOutlined, ReloadOutlined } from '@ant-design/icons'
import { Alert, Button, Table, Tabs, Typography } from 'antd'
import type { ColumnsType } from 'antd/lib/table'
import { useCallback, useMemo, useState } from 'react'
import { Link, useHistory } from 'react-router-dom'

import { listDedicatedToPremiumPrechecks } from 'apiClient/services/devops'
import type { ClusterDedicatedToPremiumPrecheck } from 'apiClient/services/devops/interface'
import { ListToolBar, useTable } from 'components/Table'

import CreatePrecheckModal from './CreatePrecheckModal'
import { formatDateTime, getErrorMessage, renderPrecheckState } from './utils'

import './index.less'

const ClusterMigration = () => {
  const history = useHistory()
  const [createVisible, setCreateVisible] = useState(false)
  const [requestError, setRequestError] = useState('')

  const getData = useCallback((pageInfo?: Partial<PageInfo>) => {
    setRequestError('')

    return listDedicatedToPremiumPrechecks(
      {
        page: pageInfo?.page,
        per_page: pageInfo?.pageSize
      },
      { isShowMessage: true }
    )
  }, [])

  const { dataSource, loading, onTableChange, paginationProps, reload } =
    useTable<ListData<ClusterDedicatedToPremiumPrecheck>>(getData, [], {
      pagination: true,
      defaultPageSize: 20,
      onRequestError: (error) => {
        setRequestError(
          getErrorMessage(error, 'Failed to load migration prechecks')
        )
      }
    })

  const columns = useMemo<ColumnsType<ClusterDedicatedToPremiumPrecheck>>(
    () => [
      {
        title: 'ID',
        dataIndex: 'id',
        fixed: 'left',
        width: 180
      },
      {
        title: 'Source Cluster',
        dataIndex: 'source_cluster_id',
        width: 180
      },
      {
        title: 'Target Premium Project',
        dataIndex: 'target_premium_project_id',
        width: 210
      },
      {
        title: 'Migration Account',
        dataIndex: 'migration_account_email',
        width: 240,
        ellipsis: true
      },
      {
        title: 'State',
        dataIndex: 'state',
        width: 130,
        render: renderPrecheckState
      },
      {
        title: 'Applicant',
        dataIndex: 'applicant',
        width: 220,
        ellipsis: true
      },
      {
        title: 'Created At',
        dataIndex: 'create_time',
        width: 180,
        render: formatDateTime
      },
      {
        title: 'Action',
        key: 'action',
        fixed: 'right',
        width: 90,
        render: (_, precheck) => (
          <Link
            to={`/cluster-migration/precheck/${precheck.id}`}
            data-mp-event="cluster-migration-precheck-detail"
          >
            Detail
          </Link>
        )
      }
    ],
    []
  )

  const handleRefresh = async () => {
    setRequestError('')
    await reload()
  }

  const handleCreated = (precheckId: string) => {
    setCreateVisible(false)
    history.push(`/cluster-migration/precheck/${precheckId}`)
  }

  return (
    <div className="cluster-migration-page">
      <Tabs activeKey="precheck">
        <Tabs.TabPane tab="Precheck" key="precheck">
          <div className="cluster-migration__intro">
            <Typography.Title level={4}>
              Migration Readiness Precheck
            </Typography.Title>
            <Typography.Text type="secondary">
              Assess migration readiness by identifying feature gaps and
              compatibility risks before starting the migration from Dedicated
              to Premium/Essential v2.
            </Typography.Text>
          </div>

          <ListToolBar
            actions={[
              <Button
                key="refresh"
                icon={<ReloadOutlined />}
                loading={loading}
                data-mp-event="cluster-migration-precheck-list-refresh"
                onClick={handleRefresh}
              >
                Refresh
              </Button>,
              <Button
                key="create"
                type="primary"
                icon={<PlusOutlined />}
                data-mp-event="cluster-migration-precheck-create"
                onClick={() => setCreateVisible(true)}
              >
                Create
              </Button>
            ]}
          />

          {requestError && (
            <Alert
              className="cluster-migration__request-error"
              type="error"
              showIcon
              message="Unable to load migration prechecks"
              description={requestError}
            />
          )}

          <Table<ClusterDedicatedToPremiumPrecheck>
            rowKey="id"
            columns={columns}
            dataSource={dataSource}
            loading={loading}
            size="small"
            pagination={{
              ...paginationProps,
              showSizeChanger: true,
              showTotal: (total) => `${total} prechecks`
            }}
            scroll={{ x: 1430 }}
            onChange={onTableChange}
          />
        </Tabs.TabPane>
      </Tabs>

      <CreatePrecheckModal
        visible={createVisible}
        onCancel={() => setCreateVisible(false)}
        onCreated={handleCreated}
      />
    </div>
  )
}

export default ClusterMigration
