import { ReloadOutlined } from '@ant-design/icons'
import {
  Button,
  Card,
  Col,
  Collapse,
  Descriptions,
  Row,
  Space,
  Tooltip
} from 'antd'
import React from 'react'
import { Link } from 'react-router-dom'

import {
  useInvalidateTools,
  useListBackupExports,
  useListBackups,
  useListDMJobs,
  useListExports,
  useListImports,
  useListImportIntoTasks,
  useListInternalChangefeedsOverview,
  useListLogBackups,
  useListRestores,
  useGetCurrentRestoreProgress
} from './hooks'
import { strings } from './strings'
import { useToolsPage } from './ToolsPageContext'
import {
  getDeployTypeDisplayName,
  isDedicatedDeployType,
  isNextGenDeployType,
  supportsBackupRestoreDeployType
} from './types'
import { formatTs, statusBadge } from './utils'

function ClusterIdentity() {
  const { cluster, clusterId, deployType } = useToolsPage()

  return (
    <Card
      title={strings.overview.clusterIdentity}
      size="small"
      headStyle={{ backgroundColor: '#fafafa' }}
    >
      <Descriptions size="small" column={1}>
        <Descriptions.Item label="Cluster Name">
          {cluster.name || '—'}
        </Descriptions.Item>
        <Descriptions.Item label="Cluster ID">{clusterId}</Descriptions.Item>
        <Descriptions.Item label="Deploy Type">
          {getDeployTypeDisplayName(deployType, cluster.service_plan) || '—'}
        </Descriptions.Item>
        <Descriptions.Item label="Cloud Provider">
          {cluster.provider || '—'}
        </Descriptions.Item>
        <Descriptions.Item label="Region">
          {cluster.region || '—'}
        </Descriptions.Item>
        <Descriptions.Item label="Version">
          {cluster.version || '—'}
        </Descriptions.Item>
        <Descriptions.Item label="Status">
          {cluster.status ? cluster.status : '—'}
        </Descriptions.Item>
        <Descriptions.Item label="Created At">
          {formatTs(cluster.create_time)}
        </Descriptions.Item>
      </Descriptions>
    </Card>
  )
}

function HealthRow({
  label,
  total,
  latestStatus,
  isLoading,
  isError
}: {
  label: string
  total: number | undefined
  latestStatus?: string
  isLoading?: boolean
  isError?: boolean
}) {
  return (
    <div
      style={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: '4px 0',
        gap: 12
      }}
    >
      <span style={{ color: 'rgba(0,0,0,0.65)' }}>{label}</span>
      <span>
        {isLoading ? (
          '…'
        ) : isError || total === undefined ? (
          <span style={{ color: '#999' }}>{strings.overview.notAvailable}</span>
        ) : (
          <Space>
            <span>{total} total</span>
            {latestStatus && statusBadge(latestStatus)}
          </Space>
        )}
      </span>
    </div>
  )
}

function ToolHealthSnapshot() {
  const { cluster, clusterId, deployType } = useToolsPage()
  const canDM =
    isDedicatedDeployType(deployType) || isNextGenDeployType(deployType)
  const canImport = canDM
  const canBackup = supportsBackupRestoreDeployType(
    deployType,
    cluster.service_plan
  )
  const canRestore = canBackup

  const pageArg = { page: 1, page_size: 1 }
  const isDedicated = isDedicatedDeployType(deployType)
  const dm = useListDMJobs(clusterId, pageArg, canDM)
  const imp = useListImports(clusterId, pageArg, isDedicated)
  const impPrem = useListImportIntoTasks(
    clusterId,
    pageArg,
    !isDedicated && canImport
  )
  const bk = useListBackups(clusterId, pageArg, canBackup)
  const logbk = useListLogBackups(clusterId, pageArg, isDedicated)
  const backupExports = useListBackupExports(clusterId, pageArg, isDedicated)
  const nextGenExports = useListExports(
    clusterId,
    pageArg,
    canBackup && !isDedicated
  )
  const exports = isDedicated ? backupExports : nextGenExports
  const rs = useListRestores(clusterId, pageArg, isDedicated && canRestore)
  const nextGenRestore = useGetCurrentRestoreProgress(
    clusterId,
    !isDedicated && canRestore
  )
  const canChangefeed =
    isDedicatedDeployType(deployType) || isNextGenDeployType(deployType)
  const cf = useListInternalChangefeedsOverview(clusterId, canChangefeed)

  return (
    <Card
      title={strings.overview.toolHealth}
      size="small"
      headStyle={{ backgroundColor: '#fafafa' }}
    >
      <div>
        <HealthRow
          label="Changefeeds"
          total={cf.data?.total}
          latestStatus={cf.data?.items?.[0]?.status}
          isLoading={cf.isLoading}
          isError={cf.isError}
        />
        {canDM && (
          <HealthRow
            label="DM Jobs"
            total={dm.data?.total}
            latestStatus={dm.data?.items?.[0]?.status}
            isLoading={dm.isLoading}
            isError={dm.isError}
          />
        )}
        {canImport && (
          <HealthRow
            label="Imports"
            total={isDedicated ? imp.data?.total : impPrem.data?.total}
            latestStatus={
              isDedicated
                ? imp.data?.items?.[0]?.status
                : impPrem.data?.items?.[0]?.status
            }
            isLoading={isDedicated ? imp.isLoading : impPrem.isLoading}
            isError={isDedicated ? imp.isError : impPrem.isError}
          />
        )}
        {canBackup && (
          <>
            <HealthRow
              label="Snapshot Backups"
              total={bk.data?.total}
              latestStatus={bk.data?.items?.[0]?.status}
              isLoading={bk.isLoading}
              isError={bk.isError}
            />
            {isDedicated && (
              <HealthRow
                label="Log Backups"
                total={logbk.data?.total}
                latestStatus={logbk.data?.items?.[0]?.status}
                isLoading={logbk.isLoading}
                isError={logbk.isError}
              />
            )}
            <HealthRow
              label={isDedicated ? 'Backup Exports' : 'Exports'}
              total={exports.data?.total}
              latestStatus={exports.data?.items?.[0]?.status}
              isLoading={exports.isLoading}
              isError={exports.isError}
            />
          </>
        )}
        {canRestore && (
          <HealthRow
            label="Restores"
            total={
              isDedicated
                ? rs.data?.total
                : nextGenRestore.data?.not_found
                ? 0
                : nextGenRestore.data
                ? 1
                : undefined
            }
            latestStatus={
              isDedicated
                ? rs.data?.items?.[0]?.status
                : nextGenRestore.data?.status
            }
            isLoading={isDedicated ? rs.isLoading : nextGenRestore.isLoading}
            isError={isDedicated ? rs.isError : nextGenRestore.isError}
          />
        )}
      </div>
    </Card>
  )
}

function QuickLinks() {
  const { orgId, clusterId } = useToolsPage()
  const detail = `/orgs/${orgId}/clusters/${clusterId}`
  return (
    <Card
      title={strings.overview.quickLinks}
      size="small"
      headStyle={{ backgroundColor: '#fafafa' }}
    >
      <Space direction="vertical" size="small">
        <Link
          target="_blank"
          rel="noopener noreferrer"
          to={`${detail}?activeKey=alerts`}
        >
          {strings.overview.alerts}
        </Link>
        <Link
          target="_blank"
          rel="noopener noreferrer"
          to={`${detail}?activeKey=operations`}
        >
          {strings.overview.recentOperations}
        </Link>
        <Link
          target="_blank"
          rel="noopener noreferrer"
          to={`${detail}?activeKey=jira_tickets`}
        >
          {strings.overview.jiraTickets}
        </Link>
      </Space>
    </Card>
  )
}

export default function ToolsOverview() {
  const { clusterId } = useToolsPage()
  const invalidate = useInvalidateTools(clusterId)

  const refreshButton = (
    <Tooltip title={strings.page.refresh}>
      <Button
        size="small"
        icon={<ReloadOutlined />}
        onClick={(e) => {
          e.stopPropagation()
          invalidate()
        }}
        aria-label={strings.page.refresh}
      >
        Refresh
      </Button>
    </Tooltip>
  )

  return (
    <Collapse defaultActiveKey={['overview']} style={{ marginBottom: 16 }}>
      <Collapse.Panel key="overview" header="Overview" extra={refreshButton}>
        <Row gutter={16}>
          <Col xs={24} xl={8}>
            <ClusterIdentity />
          </Col>
          <Col xs={24} xl={8}>
            <ToolHealthSnapshot />
          </Col>
          <Col xs={24} xl={8}>
            <QuickLinks />
          </Col>
        </Row>
      </Collapse.Panel>
    </Collapse>
  )
}
