import { ReloadOutlined } from '@ant-design/icons'
import {
  Alert,
  Button,
  Card,
  Col,
  Descriptions,
  Empty,
  PageHeader,
  Row,
  Spin,
  Statistic,
  Table,
  Tabs,
  Tag,
  Typography
} from 'antd'
import type { ColumnsType } from 'antd/lib/table'
import { useHistory, useParams } from 'react-router-dom'

import { useGetDedicatedToPremiumPrecheck } from 'apiClient/services/devops'
import type {
  ClusterDedicatedToPremiumPrecheckItem,
  ClusterDedicatedToPremiumPrecheckReport
} from 'apiClient/services/devops/interface'
import { ClusterDetailLinkPopover } from 'components/DetailLinkPopover/ClusterDetailLinkPopover'
import { ClusterDescription } from 'components/ResourceDescription/ClusterDescription'

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

import './index.less'

const { Paragraph, Text } = Typography

const REPORT_DESCRIPTIONS: Record<string, string> = {
  FEATURE_GAP:
    'Identifies feature gaps between Dedicated and Premium that may require attention before migration.',
  MIGRATION_READINESS:
    'Identifies configuration, schema, and compatibility risks that may affect migration.'
}

const getReportItemColumns = (
  category?: string
): ColumnsType<ClusterDedicatedToPremiumPrecheckItem> => [
  {
    title: category === 'FEATURE_GAP' ? 'Features' : 'Check Items',
    dataIndex: 'title',
    width: 260,
    render: (title: string, item) => (
      <div className="cluster-migration__check-title">
        <Text strong>{title || '-'}</Text>
        <Text type="secondary" code>
          {item.check_key || '-'}
        </Text>
      </div>
    )
  },
  {
    title: 'Status',
    dataIndex: 'status',
    width: 150,
    render: renderReportItemStatus
  },
  {
    title: 'Why it matters?',
    dataIndex: 'why',
    width: 300,
    render: (value: string) => <Paragraph>{value || '-'}</Paragraph>
  },
  {
    title: 'Evidence',
    dataIndex: 'evidence',
    width: 340,
    render: (value: string) => <Paragraph>{value || '-'}</Paragraph>
  },
  {
    title: 'Action',
    dataIndex: 'action',
    width: 300,
    render: (value: string) => <Paragraph>{value || '-'}</Paragraph>
  }
]

function PrecheckReport({
  report,
  index
}: {
  report: ClusterDedicatedToPremiumPrecheckReport
  index: number
}) {
  const summary = report.summary

  return (
    <Card
      className="cluster-migration__report"
      title={
        <div>
          <div>{`${categoryLabel(report.category)} Report`}</div>
          <Typography.Text type="secondary">
            {REPORT_DESCRIPTIONS[report.category || '']}
          </Typography.Text>
        </div>
      }
      extra={
        <Tag color={report.complete ? 'success' : 'default'}>
          {report.complete ? 'Complete' : 'Incomplete'}
        </Tag>
      }
    >
      <Row gutter={[16, 16]} className="cluster-migration__report-summary">
        <Col xs={12} md={6}>
          <Statistic title="Total" value={summary?.total_count || 0} />
        </Col>
        <Col xs={12} md={6}>
          <Statistic
            title="Risk Found"
            value={summary?.risk_found_count || 0}
            valueStyle={{ color: '#cf1322' }}
          />
        </Col>
        <Col xs={12} md={6}>
          <Statistic
            title="No Risk Found"
            value={summary?.no_risk_found_count || 0}
            valueStyle={{ color: '#3f8600' }}
          />
        </Col>
        <Col xs={12} md={6}>
          <Statistic
            title="Needs Input"
            value={summary?.needs_input_count || 0}
            valueStyle={{ color: '#d48806' }}
          />
        </Col>
      </Row>

      {report.execution_error && (
        <Alert
          className="cluster-migration__report-error"
          type="error"
          showIcon
          message="Report execution failed"
          description={report.execution_error}
        />
      )}

      {report.items?.length ? (
        <Table<ClusterDedicatedToPremiumPrecheckItem>
          rowKey={(item, itemIndex) =>
            item.check_key || `${report.category || index}-${itemIndex}`
          }
          columns={getReportItemColumns(report.category)}
          dataSource={report.items}
          pagination={false}
          scroll={{ x: 1350 }}
        />
      ) : (
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description="No report items"
        />
      )}
    </Card>
  )
}

export default function ClusterMigrationPrecheckDetail() {
  const history = useHistory()
  const { id } = useParams<{ id: string }>()
  const detailQuery = useGetDedicatedToPremiumPrecheck(id, {
    query: { refetchOnWindowFocus: false },
    request: { isShowMessage: true }
  })
  const precheck = detailQuery.data?.data.precheck

  if (detailQuery.isLoading) {
    return (
      <div className="cluster-migration-page cluster-migration__detail-page">
        <PageHeader
          title="Migration Precheck"
          onBack={() => history.push('/cluster-migration')}
        />
        <Card className="cluster-migration__loading">
          <Spin size="large" tip="Loading migration precheck..." />
        </Card>
      </div>
    )
  }

  if (detailQuery.isError || !precheck) {
    return (
      <div className="cluster-migration-page cluster-migration__detail-page">
        <PageHeader
          title="Migration Precheck"
          onBack={() => history.push('/cluster-migration')}
        />
        <Alert
          type="error"
          showIcon
          message="Unable to load migration precheck"
          description={getErrorMessage(
            detailQuery.error,
            'Migration precheck was not found'
          )}
        />
      </div>
    )
  }

  return (
    <div className="cluster-migration-page cluster-migration__detail-page">
      <PageHeader
        title={`Migration Precheck #${precheck.id}`}
        tags={renderPrecheckState(precheck.state)}
        onBack={() => history.push('/cluster-migration')}
        extra={[
          <Button
            key="refresh"
            icon={<ReloadOutlined />}
            loading={detailQuery.isFetching}
            data-mp-event="cluster-migration-precheck-detail-refresh"
            onClick={() => detailQuery.refetch()}
          >
            Refresh
          </Button>
        ]}
      />

      {precheck.failure_message && (
        <Alert
          className="cluster-migration__failure"
          type="error"
          showIcon
          message="Precheck failed"
          description={precheck.failure_message}
        />
      )}

      <Card title="Summary" className="cluster-migration__summary">
        <Descriptions bordered size="small" column={{ xs: 1, md: 2 }}>
          <Descriptions.Item label="Precheck ID">
            {precheck.id}
          </Descriptions.Item>
          <Descriptions.Item label="State">
            {renderPrecheckState(precheck.state)}
          </Descriptions.Item>
          <Descriptions.Item label="Source Cluster ID">
            {precheck.source_cluster_id ? (
              <ClusterDetailLinkPopover
                clusterId={precheck.source_cluster_id}
                text={precheck.source_cluster_id}
              />
            ) : (
              '-'
            )}
          </Descriptions.Item>
          <Descriptions.Item label="Target Premium Project ID">
            {precheck.target_premium_project_id || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="Migration Account Email">
            {precheck.migration_account_email || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="Applicant">
            {precheck.applicant || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="Created At">
            {formatDateTime(precheck.create_time)}
          </Descriptions.Item>
          <Descriptions.Item label="Updated At">
            {formatDateTime(precheck.update_time)}
          </Descriptions.Item>
          <Descriptions.Item label="Started At">
            {formatDateTime(precheck.start_time)}
          </Descriptions.Item>
          <Descriptions.Item label="Finished At">
            {formatDateTime(precheck.finish_time)}
          </Descriptions.Item>
        </Descriptions>
      </Card>

      <Card
        title="Source Cluster"
        className="cluster-migration__source-cluster"
      >
        {precheck.source_cluster_id ? (
          <ClusterDescription
            clusterId={precheck.source_cluster_id}
            bordered
            column={2}
          />
        ) : (
          '-'
        )}
      </Card>

      <div className="cluster-migration__reports">
        {precheck.reports?.length ? (
          <Tabs defaultActiveKey="report-0">
            {precheck.reports.map((report, index) => (
              <Tabs.TabPane
                tab={categoryLabel(report.category)}
                key={`report-${index}`}
              >
                <PrecheckReport report={report} index={index} />
              </Tabs.TabPane>
            ))}
          </Tabs>
        ) : (
          <Card title="Reports">
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description="No reports available"
            />
          </Card>
        )}
      </div>
    </div>
  )
}
