import { Card, Col, Descriptions, Row, Tabs, Tag, Typography } from 'antd'
import React from 'react'

import {
  ClusterComponentInfo,
  ClusterComponentType
} from 'apiClient/services/devops/interface'

import { ComponentHeterogeneousDeploy } from './ComponentHeterogeneousDeploy'

type ClusterComponentInfoWithVersion = ClusterComponentInfo & {
  version?: string
}

interface ComponentTabsProps {
  tenantId: string
  clusterId: string
  pd: ClusterComponentInfo[]
  tikv: ClusterComponentInfo[]
  tidb: ClusterComponentInfo[]
  tiflash: ClusterComponentInfo[]
  tiproxy: ClusterComponentInfo[]
  cassandra: ClusterComponentInfo[]
  tikvStorageType?: string
  tiflashStorageType?: string
  provider?: string
  versionByComponent?: Record<string, string>
}

export const ComponentTabs: React.FC<
  React.PropsWithChildren<ComponentTabsProps>
> = ({
  tenantId,
  clusterId,
  tidb,
  tikv,
  pd,
  tiflash,
  tiproxy,
  cassandra,
  tikvStorageType,
  tiflashStorageType,
  provider,
  versionByComponent = {}
}) => {
  const emptyText = <span style={{ color: '#aaa' }}>-</span>
  const isGCPProvider = provider?.toLowerCase() === 'gcp'

  const renderText = (value?: React.ReactNode) => {
    if (
      value === undefined ||
      value === null ||
      value === '' ||
      (Array.isArray(value) && value.length === 0)
    ) {
      return emptyText
    }

    return value
  }

  const renderLongText = (value?: string) => {
    if (!value) {
      return emptyText
    }

    return (
      <Typography.Text style={{ wordBreak: 'break-all' }}>
        {value}
      </Typography.Text>
    )
  }

  // Render storage configuration card
  const renderStorageCard = (storage: any, storageType: string) => {
    if (!storage) return null

    return (
      <Card
        size="small"
        title={`${
          storageType.charAt(0).toUpperCase() + storageType.slice(1)
        } Storage`}
        style={{ marginBottom: 8 }}
        headStyle={{ backgroundColor: '#fafafa' }}
      >
        <Descriptions column={1} size="small">
          <Descriptions.Item label="Volume Size">
            {storage.size_gi} GiB
          </Descriptions.Item>
          <Descriptions.Item label="Volume IOPS">
            {storage.iops}
          </Descriptions.Item>
          <Descriptions.Item label="Volume Throughput">
            {storage.throughput_mibps} MiB/s
          </Descriptions.Item>
          <Descriptions.Item label="Volume Type">
            {storage.volume_type}
          </Descriptions.Item>
          {storage.additional_iops && (
            <Descriptions.Item label="Additional IOPS">
              {storage.additional_iops}
            </Descriptions.Item>
          )}
        </Descriptions>
      </Card>
    )
  }

  const getStorageType = (title: string) => {
    const componentType = title.toLowerCase()
    if (componentType.includes('tikv') && tikvStorageType) {
      return { label: 'TiKV Storage Type', value: tikvStorageType }
    }
    if (componentType.includes('tiflash') && tiflashStorageType) {
      return { label: 'TiFlash Storage Type', value: tiflashStorageType }
    }
    return null
  }

  // Render component card
  const renderComponentCard = (
    comp: ClusterComponentInfo,
    index: number,
    title: string,
    len: number
  ) => {
    const {
      count,
      spu_name,
      cpu_num,
      memory_size_gi,
      instance_type,
      instance_cpu_arch,
      tidb_group_display_name,
      tidb_group_id,
      is_default_tidb_group,
      spu_display_name,
      storages,
      phase,
      host_id,
      internal_endpoint,
      privatelink_dns_name,
      private_link_service
    } = comp
    const componentName = title.toLowerCase()
    const version =
      (comp as ClusterComponentInfoWithVersion).version ||
      versionByComponent[componentName]

    const storageType = getStorageType(title)
    const componentType = componentName
    const showTidbGroup = ![
      'pd',
      'tikv',
      'tiflash',
      'tiproxy',
      'cassandra'
    ].includes(componentType)
    const isCassandra = componentType === 'cassandra'

    return (
      <Card
        key={index}
        style={{ marginBottom: 16, border: '1px solid #d9d9d9' }}
        title={
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center'
            }}
          >
            <span>
              {title} Configuration {len > 1 ? `#${index + 1}` : ''}
            </span>
            {showTidbGroup && is_default_tidb_group && (
              <Tag color="blue">Default Group</Tag>
            )}
          </div>
        }
      >
        <Row gutter={[16, 16]}>
          {/* Basic Information */}
          <Col xs={24}>
            <Descriptions column={4} size="small" title="Basic Info">
              <Descriptions.Item label="Count">
                {count || <span style={{ color: '#aaa' }}>-</span>}
              </Descriptions.Item>
              <Descriptions.Item label="SPU Name">
                {spu_name || <span style={{ color: '#aaa' }}>-</span>}
              </Descriptions.Item>
              <Descriptions.Item label="SPU">
                {spu_display_name || <span style={{ color: '#aaa' }}>-</span>}
              </Descriptions.Item>
              <Descriptions.Item label="Version">
                {version || <span style={{ color: '#aaa' }}>-</span>}
              </Descriptions.Item>
            </Descriptions>
          </Col>

          {/* Resource Specifications */}
          <Col xs={24}>
            <Descriptions column={4} size="small" title="Resources">
              <Descriptions.Item label="CPU Cores">
                {cpu_num || <span style={{ color: '#aaa' }}>-</span>}
              </Descriptions.Item>
              <Descriptions.Item label="Memory">
                {memory_size_gi ? (
                  `${memory_size_gi} GiB`
                ) : (
                  <span style={{ color: '#aaa' }}>-</span>
                )}
              </Descriptions.Item>
              <Descriptions.Item label="Instance Type">
                {instance_type || <span style={{ color: '#aaa' }}>-</span>}
              </Descriptions.Item>
              <Descriptions.Item label="CPU Architecture">
                {instance_cpu_arch || <span style={{ color: '#aaa' }}>-</span>}
              </Descriptions.Item>
            </Descriptions>
          </Col>

          {/* TiDB Group Information */}
          {showTidbGroup && (
            <Col xs={24}>
              <Descriptions column={4} size="small" title="TiDB Group">
                <Descriptions.Item label="Display Name">
                  {tidb_group_display_name || (
                    <span style={{ color: '#aaa' }}>-</span>
                  )}
                </Descriptions.Item>
                <Descriptions.Item label="Group ID">
                  <Typography.Text type="secondary">
                    {tidb_group_id || '-'}
                  </Typography.Text>
                </Descriptions.Item>
              </Descriptions>
            </Col>
          )}

          {isCassandra && (
            <Col xs={24}>
              <Descriptions column={2} size="small" title="Connection Info">
                <Descriptions.Item label="Phase">
                  {renderText(phase)}
                </Descriptions.Item>
                <Descriptions.Item label="Host ID">
                  {renderLongText(host_id)}
                </Descriptions.Item>
                <Descriptions.Item label="Internal Endpoint">
                  {renderLongText(internal_endpoint)}
                </Descriptions.Item>
                <Descriptions.Item label="PrivateLink DNS">
                  {renderLongText(privatelink_dns_name)}
                </Descriptions.Item>
                <Descriptions.Item label="Endpoint Service Phase">
                  {renderText(private_link_service?.phase)}
                </Descriptions.Item>
                <Descriptions.Item label="Endpoint Service Name">
                  {renderLongText(private_link_service?.service_name)}
                </Descriptions.Item>
                <Descriptions.Item label="AZ IDs">
                  {renderText(
                    private_link_service?.availability_zone_ids?.join(', ')
                  )}
                </Descriptions.Item>
              </Descriptions>
            </Col>
          )}

          {/* Storage Configuration - Only show for components with storage */}
          {storages && Object.keys(storages).length > 0 && (
            <Col xs={24}>
              <div style={{ marginTop: 8 }}>
                <Typography.Title level={5} style={{ marginBottom: 12 }}>
                  Storage{' '}
                  {storageType && (
                    <Tag color="purple" style={{ margin: 0 }}>
                      {storageType.value}
                    </Tag>
                  )}
                </Typography.Title>
                <Row gutter={[16, 8]}>
                  {Object.entries(storages).map(([storageType, storage]) => (
                    <Col xs={24} sm={12} lg={8} key={storageType}>
                      {renderStorageCard(storage, storageType)}
                    </Col>
                  ))}
                </Row>
              </div>
            </Col>
          )}
        </Row>
      </Card>
    )
  }

  const renderComponentHeterogeneousDeploy = (comp: ClusterComponentInfo) => {
    if (!isGCPProvider) {
      return null
    }

    return (
      <ComponentHeterogeneousDeploy
        tenantId={tenantId}
        clusterId={clusterId}
        comp={comp}
      />
    )
  }

  const tabItems = [
    {
      key: 'tidb',
      label: 'TiDB',
      children:
        tidb?.length > 0 ? (
          <div>
            {tidb.map((comp, index) => (
              <React.Fragment key={`tidb-${index}`}>
                {renderComponentCard(comp, index, 'TiDB', tidb?.length)}
                {renderComponentHeterogeneousDeploy(comp)}
              </React.Fragment>
            ))}
          </div>
        ) : (
          <div style={{ textAlign: 'center', padding: 20, color: '#999' }}>
            No TiDB Configuration
          </div>
        )
    },
    ...(tikv?.length > 0
      ? [
          {
            key: 'tikv',
            label: 'TiKV',
            children:
              tikv?.length > 0 ? (
                <div>
                  {tikv.map((comp, index) => (
                    <React.Fragment key={`tikv-${index}`}>
                      {renderComponentCard(comp, index, 'TiKV', tikv?.length)}
                      {renderComponentHeterogeneousDeploy(comp)}
                    </React.Fragment>
                  ))}
                </div>
              ) : (
                <div
                  style={{ textAlign: 'center', padding: 20, color: '#999' }}
                >
                  No TiKV Configuration
                </div>
              )
          }
        ]
      : []),
    ...(pd?.length > 0
      ? [
          {
            key: 'pd',
            label: 'PD',
            children:
              pd?.length > 0 ? (
                <div>
                  {pd.map((comp, index) => (
                    <React.Fragment key={`pd-${index}`}>
                      {renderComponentCard(comp, index, 'PD', pd?.length)}
                      {renderComponentHeterogeneousDeploy(comp)}
                    </React.Fragment>
                  ))}
                </div>
              ) : (
                <div
                  style={{ textAlign: 'center', padding: 20, color: '#999' }}
                >
                  No PD Configuration
                </div>
              )
          }
        ]
      : []),
    ...(tiflash?.length > 0
      ? [
          {
            key: 'tiflash',
            label: 'TiFlash',
            children: (
              <div>
                {tiflash.map((comp, index) => (
                  <React.Fragment key={`tiflash-${index}`}>
                    {renderComponentCard(
                      comp,
                      index,
                      'TiFlash',
                      tiflash?.length
                    )}
                    {renderComponentHeterogeneousDeploy(comp)}
                  </React.Fragment>
                ))}
              </div>
            )
          }
        ]
      : []),
    ...(tiproxy?.length > 0
      ? [
          {
            key: 'tiproxy',
            label: 'TiProxy',
            children:
              tiproxy?.length > 0 ? (
                <div>
                  {tiproxy.map((comp, index) => (
                    <React.Fragment key={`tiproxy-${index}`}>
                      {renderComponentCard(
                        comp,
                        index,
                        'TiProxy',
                        tiproxy?.length
                      )}
                      {renderComponentHeterogeneousDeploy(comp)}
                    </React.Fragment>
                  ))}
                </div>
              ) : (
                <div
                  style={{ textAlign: 'center', padding: 20, color: '#999' }}
                >
                  No TiProxy Configuration
                </div>
              )
          }
        ]
      : []),
    ...(cassandra?.length > 0
      ? [
          {
            key: 'cassandra',
            label: 'Cassandra',
            children: (
              <div>
                {cassandra.map((comp, index) => (
                  <React.Fragment key={`cassandra-${index}`}>
                    {renderComponentCard(
                      comp,
                      index,
                      'Cassandra',
                      cassandra?.length
                    )}
                    {renderComponentHeterogeneousDeploy(comp)}
                  </React.Fragment>
                ))}
              </div>
            )
          }
        ]
      : [])
  ]

  return (
    <Card style={{ marginBottom: 24 }}>
      <Tabs defaultActiveKey="tidb" type="card" items={tabItems} />
    </Card>
  )
}
