import { SimpleGrid } from '@tidbcloud/uikit'
import { TimeRangeValue } from '@tidbcloud/uikit/biz'
import { useDebounceFn } from 'ahooks'
import { SyncChartPointer as MetricsChartSyncProvider } from 'metrics-chart'
import { useRef } from 'react'

import ChartCard, { ChartCardProps } from 'dbaas/components/ChartCard'
import { MetricInfo } from 'dbaas/components/ChartCard/helpers'

export interface UsageMetricInfo extends MetricInfo {
  url: string
  params?: string
  chartSettings?: ChartCardProps['chartSetting']
  fixMinInterval?: boolean
}

interface MonitorPanelProps {
  metrics: UsageMetricInfo[]
  timeRangeValue: TimeRangeValue
  onLoading?: (loading: boolean) => void
  timeFormat?: string
}

const MetricsPanel: React.FC<React.PropsWithChildren<MonitorPanelProps>> = ({
  metrics,
  timeRangeValue,
  onLoading,
  timeFormat
}) => {
  const loadingCounter = useRef(0)
  const { run: debouncedOnLoading } = useDebounceFn((v) => onLoading?.(v), { wait: 100, leading: true })

  return (
    <MetricsChartSyncProvider>
      <SimpleGrid type="container" cols={{ base: 1, '980px': 2 }} spacing="xl">
        {metrics.map((metric) => (
          <ChartCard
            key={metric.title}
            title={metric.title}
            label={metric.label}
            sourceURI={metric.url}
            timeRange={timeRangeValue}
            timeFormat={timeFormat}
            metric={metric}
            chartSetting={metric.chartSettings}
            fixMinInterval={metric.fixMinInterval}
            onLoading={(isLoading) => {
              isLoading ? (loadingCounter.current += 1) : loadingCounter.current > 0 && (loadingCounter.current -= 1)

              if (loadingCounter.current === 0) {
                debouncedOnLoading(false)
              } else {
                debouncedOnLoading(true)
              }
            }}
          />
        ))}
      </SimpleGrid>
    </MetricsChartSyncProvider>
  )
}

export default MetricsPanel
