import { Position } from '@elastic/charts'
import { notifier, SimpleGrid } from '@tidbcloud/uikit'
import { useRafInterval } from 'ahooks'
import { SyncChartPointer as MetricsChartSyncProvider } from 'metrics-chart'
import { observer } from 'mobx-react'
import { useMemo, useState } from 'react'

import ChartCard from 'dbaas/components/ChartCard'
import { CreationPendingOverlay } from 'dbaas/components/ChartCard/CreationPendingOverlay'
import { getNewTimeRange, INTERVAL_M_SEC } from 'dbaas/components/ChartCard/helpers'
import { HeroComponent } from 'dbaas/components/Measurement'
import { SharedCluster } from 'dbaas/features/ClusterManagement/cluster'
import { useGetMetricsQueryRangeURLForCluster } from 'dbaas/services/useO11YQuery'
import useStores from 'dbaas/stores/useStores'

import { getMetricsConfig } from './helpers'

interface MonitorPanelProps {
  cluster: SharedCluster
}

const MonitorPanel: React.FC<React.PropsWithChildren<MonitorPanelProps>> = ({ cluster }) => {
  const {
    store: {
      tenantData: { id: orgId },
      activeProjectId
    }
  } = useStores()
  const {
    data: metricSourceURI,
    isLoading: isLoadingMetricsURL,
    metricRequestOptions
  } = useGetMetricsQueryRangeURLForCluster(orgId, activeProjectId, cluster)
  const [fetched, setFetched] = useState(false)

  const metricsConfig = useMemo(() => {
    return getMetricsConfig(cluster)
  }, [cluster])

  const [timeRange, setTimeRange] = useState<[number, number]>(() => getNewTimeRange())

  // useRafInterval stops running when browser render doesn't work, for example, browser tab is not active, browser window is minimized.
  useRafInterval(() => {
    setTimeRange(getNewTimeRange())
  }, INTERVAL_M_SEC)

  return (
    <MetricsChartSyncProvider>
      <SimpleGrid type="container" cols={{ base: 1, '640px': 2 }} spacing="xl">
        {metricsConfig?.map((metric, index) => (
          <ChartCard
            key={`${metric.title}-${cluster.id}-${index}`}
            title={metric.title}
            label={metric.label}
            sourceURI={metricSourceURI ?? ''}
            timeRange={timeRange}
            metric={metric}
            metricRequestOptions={metricRequestOptions}
            height={250}
            chartSetting={{ legendPosition: Position.Bottom, legendSize: 62 }}
            onLoading={(loading) => {
              if (!loading) {
                setFetched(true)
              }
            }}
            pendingOverlay={cluster.computed.creating || cluster.computed.restoring ? <CreationPendingOverlay /> : null}
            initialLoading={isLoadingMetricsURL}
            enableCircuitBreaker
            onThrottleOpen={() => {
              notifier.warn('Metrics service is temporarily unavailable. Please try again later.', { autoClose: 6000 })
            }}
          />
        ))}
        {fetched && <HeroComponent />}
      </SimpleGrid>
    </MetricsChartSyncProvider>
  )
}

export default observer(MonitorPanel)
