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

import { useGetCluster } from 'apiClient/services/devops'
import { OperationOperationTarget } from 'apiClient/services/devops/interface'
import Issues from 'pages/AIOps/Issues'
import Operations from 'pages/Devops/Operations/Operations'
import { Alerts } from 'pages/Tenants/ClusterDetail/Alerts'
import { BasicInfo } from 'pages/Tenants/ClusterDetail/BasicInfo'
import { ClusterComponents } from 'pages/Tenants/ClusterDetail/ComponentsInfo/ComponentsInfo'
import ClusterConfig from 'pages/Tenants/ClusterDetail/Configs'
import DataPlane from 'pages/Tenants/ClusterDetail/DataPlane'
import TerminalBasic from 'pages/Tenants/ClusterDetail/Maintance/TerminalBasic'
import TiCDCCluster from 'pages/Tenants/ClusterDetail/TiCDC'
import ReplayList from 'pages/Tenants/ClusterDetail/TrafficMirror/ReplayList'

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

type SharedResourcePoolDetailParams = {
  resource_pool_id: string
}

const SharedResourcePoolDetail = () => {
  const location = useLocation()
  const searchParams = new URLSearchParams(location.search)
  const prev = searchParams.get('activeKey')
  const [activeTabKey, setActiveTabKey] = useState<string>(prev || 'components')
  const { resource_pool_id } = useParams<SharedResourcePoolDetailParams>()

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

  const { data, refetch } = useGetCluster(resource_pool_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: 'ticdc',
      tab: 'Changefeeds',
      disabled:
        data.data.deploy_type !== 'DEPLOY_TYPE_DEDICATED' &&
        data.data.deploy_type !== 'DEPLOY_TYPE_NEXTGEN' &&
        data.data.deploy_type !== 'DEPLOY_TYPE_RESOURCE_POOL'
    },
    {
      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} />,
    dataplane: <DataPlane />,
    operations: (
      <Operations
        target_type={
          data.data.deploy_type === 'DEPLOY_TYPE_RESOURCE_POOL'
            ? OperationOperationTarget.resource_pool
            : OperationOperationTarget.cluster
        }
        target_id={resource_pool_id}
      />
    ),
    alerts: <Alerts clusterId={resource_pool_id} />,
    terminal: <TerminalBasic deploy_type={data.data.deploy_type || ''} />,
    configs: <ClusterConfig />,
    ticdc: <TiCDCCluster deploy_type={data.data.deploy_type || ''} />,
    jira_tickets: (
      <Issues preDefinedSearchParam={{ cluster_id_in: [resource_pool_id] }} />
    ),
    traffic_mirror: (
      <ReplayList
        org_id={data.data.tenant_id!}
        project_id={data.data.project_id!}
        cluster_id={resource_pool_id}
        cloud_provder={data.data.provider}
        region={data.data.region}
      />
    )
  }

  return (
    <>
      <BasicInfo
        cluster={data.data}
        hideSetDefaultResourcePoolAction={
          data.data.service_plan !== 'Essential_V2'
        }
        reload={async () => {
          await refetch()
        }}
      />
      <Divider />
      <Card
        tabList={visibleTabList}
        tabProps={{ size: 'middle' }}
        bordered={false}
        activeTabKey={activeContentKey}
        onTabChange={(key) => setActiveTabKey(key)}
      >
        {contentList[activeContentKey]}
      </Card>
    </>
  )
}

export default SharedResourcePoolDetail
