import { Table, Tag, Typography } from 'antd'
import type { ColumnsType } from 'antd/lib/table'
import React, { useCallback, useMemo } from 'react'
import { Link } from 'react-router-dom'

import type { ClusterSummaryRow } from './types'
import type { UpgradeCrEntry } from './utils'
import {
  estimateStepDurationMs,
  formatDurationMs,
  formatUpgradeStepDescription,
  getTidbNodesMultiRestartMark,
  parseUpgradeOperationCr
} from './utils'

type StepRow = {
  key: number
  step: number
  target?: string
  version?: string
  clusterId?: string
  multiRestartMark?: string
  durationMs: number
  durationLabel: string
  description: string
}

type Props = {
  row: ClusterSummaryRow
}

export const ExpandedRowDetail: React.FC<Props> = ({ row }) => {
  const renderClusterIdLink = useCallback(
    (clusterId?: string) => {
      if (!clusterId) return '-'
      if (!row.tenantId) {
        return (
          <Typography.Text ellipsis={{ tooltip: clusterId }}>
            {clusterId}
          </Typography.Text>
        )
      }
      return (
        <Link
          to={`/orgs/${encodeURIComponent(
            row.tenantId
          )}/clusters/${encodeURIComponent(clusterId)}`}
          target="_blank"
          rel="noopener noreferrer"
          title={clusterId}
        >
          <Typography.Text
            style={{ color: '#1890ff', maxWidth: 180 }}
            ellipsis={{ tooltip: clusterId }}
          >
            {clusterId}
          </Typography.Text>
        </Link>
      )
    },
    [row.tenantId]
  )

  const steps = useMemo((): StepRow[] => {
    const { entries } = parseUpgradeOperationCr(row.upgradeOperationCr)
    return entries.map((entry: UpgradeCrEntry, index) => {
      const durationMs = estimateStepDurationMs(
        entry,
        row.k8sSnapshot,
        row.cloudProvider
      )
      return {
        key: index,
        step: index + 1,
        target: entry.target,
        version: entry.version,
        clusterId: entry.cluster_id,
        multiRestartMark: getTidbNodesMultiRestartMark(entries, index),
        durationMs,
        durationLabel: formatDurationMs(durationMs),
        description: formatUpgradeStepDescription(entry)
      }
    })
  }, [row.cloudProvider, row.k8sSnapshot, row.upgradeOperationCr])

  const columns = useMemo(
    (): ColumnsType<StepRow> => [
      {
        title: 'Step',
        dataIndex: 'step',
        width: 64
      },
      {
        title: 'Target',
        dataIndex: 'target',
        width: 140,
        render: (v?: string) => v || '-'
      },
      {
        title: 'Version',
        dataIndex: 'version',
        width: 100,
        render: (v?: string) => v || '-'
      },
      {
        title: 'ClusterID',
        dataIndex: 'clusterId',
        width: 200,
        render: (id?: string) => renderClusterIdLink(id)
      },
      {
        title: 'Multi Restart',
        dataIndex: 'multiRestartMark',
        width: 110,
        render: (mark?: string) =>
          mark ? <Tag color="orange">{mark}</Tag> : '-'
      },
      {
        title: 'Duration',
        dataIndex: 'durationLabel',
        width: 100,
        render: (v: string) => v || '-'
      },
      {
        title: 'Describtion',
        dataIndex: 'description',
        render: (text: string) => text
      }
    ],
    [renderClusterIdLink]
  )

  if (steps.length === 0) {
    return (
      <div style={{ padding: '8px 16px' }}>
        <Typography.Text type="secondary">
          No upgrade operation steps
        </Typography.Text>
      </div>
    )
  }

  return (
    <div style={{ padding: '8px 16px 12px' }}>
      <Typography.Text strong>Upgrade Operations</Typography.Text>
      <Table<StepRow>
        size="small"
        style={{ marginTop: 8 }}
        columns={columns}
        dataSource={steps}
        pagination={false}
        rowKey="key"
        scroll={{ x: 1100 }}
      />
    </div>
  )
}
