import { Row, Col } from 'antd'
import React, { useMemo } from 'react'
import { useParams } from 'react-router-dom'

import {
  useCloudConfigControllerGetClusterConfiguration,
  useGetClusterComponents
} from 'apiClient/services/devops'
import { CloudConfigControllerGetClusterConfigurationClusterType } from 'apiClient/services/devops/interface'

import { ComponentTabs } from './Component'

interface ClusterComponentsProps {
  provider?: string
  cloudConfigClusterType?: CloudConfigControllerGetClusterConfigurationClusterType
}

type ClusterConfiguration = {
  components?: Record<
    string,
    {
      name?: string
      version?: string
    }
  >
}

export const ClusterComponents: React.FC<
  React.PropsWithChildren<ClusterComponentsProps>
> = ({ provider, cloudConfigClusterType }) => {
  const { cluster_id, org_id } = useParams<{
    cluster_id: string
    org_id: string
  }>()
  const { data: components } = useGetClusterComponents(cluster_id)
  const { data: configuration } =
    useCloudConfigControllerGetClusterConfiguration(
      {
        cluster_id,
        cluster_type: cloudConfigClusterType!
      },
      {
        query: {
          enabled: Boolean(cluster_id && cloudConfigClusterType)
        }
      }
    )
  const versionByComponent = useMemo(() => {
    const config = configuration?.data.configuration as
      | ClusterConfiguration
      | undefined
    const versions: Record<string, string> = {}

    Object.entries(config?.components || {}).forEach(([key, component]) => {
      const name = component?.name || key
      if (component?.version) {
        versions[name.toLowerCase()] = component.version
      }
    })

    return versions
  }, [configuration])

  if (!components) {
    return null
  }

  return (
    <ComponentTabs
      tenantId={org_id}
      clusterId={cluster_id}
      tidb={components.data.tidb!}
      tikv={components.data.tikv!}
      pd={components.data.pd!}
      tiflash={components.data.tiflash!}
      tiproxy={components.data.tiproxy!}
      cassandra={components.data.cassandra ?? []}
      tikvStorageType={components.data.tikv_storage_type!}
      tiflashStorageType={components.data.tiflash_storage_type!}
      provider={provider}
      versionByComponent={versionByComponent}
    />
  )
}
