import { Result, Spin, Typography } from 'antd'
import React from 'react'
import { useParams } from 'react-router-dom'

import { useGetCluster } from 'apiClient/services/devops'

import Overview from './Overview'
import { strings } from './strings'
import ToolsTabs from './Tabs'
import { ToolsPageProvider } from './ToolsPageContext'
import { isTiDBToolsSupportedDeployType } from './types'

export default function ToolsPage() {
  const { org_id, cluster_id } = useParams<{
    org_id: string
    cluster_id: string
  }>()

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

  if (isLoading) {
    return (
      <div style={{ padding: 48, textAlign: 'center' }}>
        <Spin />
      </div>
    )
  }

  if (isError) {
    return (
      <Result
        status="error"
        title="Failed to load cluster"
        subTitle={cluster_id}
      />
    )
  }

  const cluster = data?.data
  if (!cluster) {
    return (
      <Result status="404" title="Cluster not found" subTitle={cluster_id} />
    )
  }

  const deployType = cluster.deploy_type
  if (!isTiDBToolsSupportedDeployType(deployType)) {
    return (
      <Result
        status="403"
        title="TiDB Tools is not available for this cluster type"
        subTitle={`Deploy type: ${deployType ?? 'unknown'}`}
      />
    )
  }

  return (
    <div style={{ padding: 24 }}>
      <Typography.Title level={4} style={{ marginBottom: 16 }}>
        {strings.page.title}
      </Typography.Title>

      <ToolsPageProvider
        cluster={cluster}
        clusterId={cluster_id}
        orgId={org_id}
      >
        <Overview />
        <ToolsTabs />
      </ToolsPageProvider>
    </div>
  )
}
