import { Card, Divider, Result } from 'antd'
import React, { useEffect, useState } from 'react'
import { Link, useHistory, useLocation, useParams } from 'react-router-dom'

import { useGetCluster } from 'apiClient/services/devops'
import { OperationOperationTarget } from 'apiClient/services/devops/interface'
import { CloudConfigControllerGetClusterConfigurationClusterType } from 'apiClient/services/devops/interface'
import Issues from 'pages/AIOps/Issues'

import Operations from '../../Devops/Operations/Operations'

import { Alerts } from './Alerts'
import { AzFaultActiveAlert } from './AzFaultActiveAlert'
import { BasicInfo } from './BasicInfo'
import { ClusterComponents } from './ComponentsInfo/ComponentsInfo'
import ClusterConfig from './Configs'
import SharedPoolConfig from './Configs/shared_pool'
import VPCPeering from './Configs/VPCPeering'
import DataPlane from './DataPlane'
import TerminalBasic from './Maintance/TerminalBasic'
import TiCDCCluster from './TiCDC'
import { isTiDBToolsSupportedDeployType } from './TiDBTools/types'
import ReplayList from './TrafficMirror/ReplayList'

const RESOURCE_POOL_TAB_ORDER = [
  'operations',
  'tools',
  'configs',
  'ticdc',
  'jira_tickets',
  'alerts'
]

export default function ClusterDetail() {
  const location = useLocation()
  const history = useHistory()
  const searchParams = new URLSearchParams(location.search)
  var prev = searchParams.get('activeKey')
  const [activeTabKey, setActiveTabKey] = useState<string>(prev || 'components')
  const { cluster_id, org_id } = useParams<{
    cluster_id: string
    org_id: string
  }>()
  const onTabChange = (key: string) => {
    if (key === 'tools') {
      history.push(`/orgs/${org_id}/clusters/${cluster_id}/tidbtools`)
      return
    }
    setActiveTabKey(key)
  }

  useEffect(() => {
    const key = new URLSearchParams(location.search).get('activeKey')
    setActiveTabKey(key || 'components')
  }, [cluster_id, location.search])

  const { data, refetch } = useGetCluster(cluster_id, {
    query: {
      refetchInterval: false,
      refetchIntervalInBackground: false,
      refetchOnWindowFocus: false
    }
  })

  if (!data) {
    return null
  }

  const isResourcePool = data.data.deploy_type === 'DEPLOY_TYPE_RESOURCE_POOL'
  const tabList = [
    {
      key: 'components',
      tab: 'Components Info',
      disabled:
        data.data.deploy_type === 'DEPLOY_TYPE_SERVERLESS' ||
        data.data.deploy_type === 'DEPLOY_TYPE_RESOURCE_POOL'
    },
    {
      key: 'dataplane',
      tab: 'Data Plane',
      disabled: data.data.deploy_type !== 'DEPLOY_TYPE_DEDICATED'
    },
    {
      key: 'operations',
      tab: 'Operations'
    },
    {
      key: 'alerts',
      tab: 'Alerts'
    },
    {
      key: 'terminal',
      tab: 'Terminal',
      disabled: data.data.deploy_type === 'DEPLOY_TYPE_RESOURCE_POOL'
    },
    {
      key: 'configs',
      tab: 'Configs',
      disabled: data.data.deploy_type === 'DEPLOY_TYPE_SERVERLESS'
    },
    {
      key: 'sharedPool',
      tab: 'Resource Pool',
      disabled: data.data.deploy_type !== 'DEPLOY_TYPE_NEXTGEN'
    },
    {
      key: 'ticdc',
      tab: 'Changefeeds',
      disabled:
        data.data.deploy_type !== 'DEPLOY_TYPE_SERVERLESS' &&
        data.data.deploy_type !== 'DEPLOY_TYPE_DEDICATED' &&
        data.data.deploy_type !== 'DEPLOY_TYPE_NEXTGEN' &&
        data.data.deploy_type !== 'DEPLOY_TYPE_RESOURCE_POOL'
    },
    {
      key: 'tools',
      tab: 'TiDB Tools',
      disabled: !isTiDBToolsSupportedDeployType(data.data.deploy_type)
    },
    {
      key: 'jira_tickets',
      tab: 'Jira Tickets'
    },
    {
      key: 'traffic_mirror',
      tab: 'Traffic Mirror',
      disabled:
        data.data.deploy_type !== 'DEPLOY_TYPE_DEDICATED' &&
        data.data.deploy_type !== 'DEPLOY_TYPE_NEXTGEN'
    }
  ]
  const visibleTabList = isResourcePool
    ? tabList
        .filter((tab) => !tab.disabled)
        .sort(
          (left, right) =>
            RESOURCE_POOL_TAB_ORDER.indexOf(left.key) -
            RESOURCE_POOL_TAB_ORDER.indexOf(right.key)
        )
    : tabList
  const activeContentKey = visibleTabList.some(
    (tab) => tab.key === activeTabKey
  )
    ? activeTabKey
    : visibleTabList[0]?.key || activeTabKey
  const contentList: Record<string, React.ReactNode> = {
    components: (
      <ClusterComponents
        provider={data.data.provider}
        cloudConfigClusterType={
          data.data.deploy_type === 'DEPLOY_TYPE_NEXTGEN'
            ? CloudConfigControllerGetClusterConfigurationClusterType.LOGICAL_CLUSTER
            : undefined
        }
      />
    ),
    dataplane: <DataPlane />,
    operations: (
      <Operations
        target_type={
          data.data.deploy_type === 'DEPLOY_TYPE_RESOURCE_POOL'
            ? OperationOperationTarget.resource_pool
            : OperationOperationTarget.cluster
        }
        target_id={cluster_id}
      />
    ),
    alerts: <Alerts clusterId={cluster_id} />,
    terminal: <TerminalBasic deploy_type={data.data.deploy_type || ''} />,
    configs: <ClusterConfig />,
    sharedPool: data.data.nextgen_details?.resource_pool_id ? (
      <div>
        <Result
          title="Resource Pool"
          subTitle="The resource pool details have been moved to the resource pool's own detail page."
          extra={
            <Link
              to={`/orgs/${data.data.tenant_id}/clusters/${data.data.nextgen_details.resource_pool_id}`}
            >
              Go to Resource Pool {data.data.nextgen_details.resource_pool_id}
            </Link>
          }
        />
        <Divider />
        <VPCPeering cluster_id={cluster_id} cluster={data.data} />
      </div>
    ) : (
      <SharedPoolConfig />
    ),
    ticdc: <TiCDCCluster deploy_type={data.data.deploy_type || ''} />,
    tools: (
      <div style={{ padding: 16 }}>
        <Link to={`/orgs/${org_id}/clusters/${cluster_id}/tidbtools`}>
          Open TiDB Tools
        </Link>
      </div>
    ),
    jira_tickets: (
      <Issues preDefinedSearchParam={{ cluster_id_in: [cluster_id] }} />
    ),
    traffic_mirror: (
      <ReplayList
        org_id={data.data.tenant_id!}
        project_id={data.data.project_id!}
        cluster_id={cluster_id}
        cloud_provder={data.data.provider}
        region={data.data.region}
      />
    )
  }

  return (
    <>
      <AzFaultActiveAlert
        clusterId={cluster_id}
        enabled={data.data.deploy_type === 'DEPLOY_TYPE_DEDICATED'}
      />
      <BasicInfo
        cluster={data.data}
        reload={async () => {
          await refetch()
        }}
      ></BasicInfo>
      <Divider />
      <Card
        tabList={visibleTabList}
        tabProps={{ size: 'middle' }}
        bordered={false}
        activeTabKey={activeContentKey}
        onTabChange={(key) => {
          onTabChange(key)
        }}
      >
        {contentList[activeContentKey]}
      </Card>
    </>
  )
}
