import { useComputedColorScheme } from '@tidbcloud/uikit'
import { useEffect } from 'react'
import { useHistory, useLocation } from 'react-router-dom'

import config from 'config'
import { SharedCluster } from 'dbaas/features/ClusterManagement/cluster'
import OverviewV2 from 'dbaas/screens/Cluster/OverviewV2'
import { ClusterPageShell } from 'dbaas/screens/ClusterV2/components'
import { CONNECT_MODAL_QUERY_VALUE, OPEN_MODAL_QUERY_KEY } from 'dbaas/screens/NextGen/shared/query-params'

import { OverviewContext, useOverviewEventBus } from './context'
import { ServerlessOnboaring } from './Onboarding'
import { ClusterToolbar } from './Toolbar'

interface ClusterOverviewProps {
  cluster: SharedCluster
}

const ClusterOverview = ({ cluster }: ClusterOverviewProps) => {
  const colorScheme = useComputedColorScheme()
  const eventBus = useOverviewEventBus()
  const history = useHistory()
  const location = useLocation()

  const connectBlocked = cluster?.computed?.creating || cluster?.computed?.recovering
  const isDedicated = cluster?.computed?.isDedicated

  useEffect(() => {
    document.title = `${config.PAGE_TITLE_PREFIX}Overview`
  }, [])

  useEffect(() => {
    const params = new URLSearchParams(location.search)
    const shouldOpenConnect = params.get(OPEN_MODAL_QUERY_KEY) === CONNECT_MODAL_QUERY_VALUE

    if (!shouldOpenConnect || isDedicated || connectBlocked) {
      return
    }

    eventBus.emit({
      connection: {
        opened: true
      }
    })

    params.delete(OPEN_MODAL_QUERY_KEY)
    history.replace({
      pathname: location.pathname,
      search: params.toString() ? `?${params.toString()}` : ''
    })
  }, [connectBlocked, eventBus, history, isDedicated, location.pathname, location.search])

  return (
    <OverviewContext.Provider value={eventBus}>
      <ClusterPageShell
        title="Overview"
        wrapperProps={{
          h: '100%',
          sx: (theme) => ({
            backgroundColor: colorScheme === 'dark' ? undefined : theme.colors.carbon[1]
          })
        }}
        headerProps={{
          sticky: true,
          rightSection: <ClusterToolbar cluster={cluster} />,
          sx: (theme) => ({
            background: colorScheme === 'dark' ? undefined : theme.colors.carbon[1]
          })
        }}
        bodyProps={{
          px: 0,
          pb: 96
        }}
      >
        <OverviewV2
          cluster={cluster}
          top={{
            serverless: <ServerlessOnboaring cluster={cluster} />
          }}
        />
      </ClusterPageShell>
    </OverviewContext.Provider>
  )
}

export default ClusterOverview
