import TimeRangePicker from '@tidb-cloud-uikit/components/TimeRangePicker'
import { Stack } from '@tidbcloud/uikit'
import { DEFAULT_TIME_RANGE, TimeRange, TimeRangeValue, toTimeRangeValue } from '@tidbcloud/uikit/biz'
import { useInterval } from 'ahooks'
import { SyncChartPointer as MetricsChartSyncProvider } from 'metrics-chart'
import { useState } from 'react'

import ChartCard from 'dbaas/components/ChartCard'
import { getNewTimeRange, INTERVAL_M_SEC, MetricInfo, MetricRequestOptions } from 'dbaas/components/ChartCard/helpers'

export const MetricsChartOnChangeFeed = ({
  metricInfo,
  metricSourceURI,
  showTimeRangePicker,
  metricRequestOptions
}: {
  metricInfo: MetricInfo[]
  metricSourceURI: string
  showTimeRangePicker?: boolean
  metricRequestOptions?: MetricRequestOptions
}) => {
  const sourceURI = metricSourceURI ?? ''

  const [timeRange, setTimeRange] = useState<TimeRange>(DEFAULT_TIME_RANGE)
  const [timeRangeValue, setTimeRangeValue] = useState<TimeRangeValue>(() =>
    showTimeRangePicker ? toTimeRangeValue(DEFAULT_TIME_RANGE) : getNewTimeRange()
  )

  useInterval(() => {
    if (showTimeRangePicker) {
      setTimeRangeValue(toTimeRangeValue(timeRange))
      return
    }
    setTimeRangeValue(getNewTimeRange())
  }, INTERVAL_M_SEC)

  if (!sourceURI) {
    return null
  }

  const charts = (
    <MetricsChartSyncProvider>
      {metricInfo.map((metric, index) => (
        <ChartCard
          key={index}
          title={metric.title}
          label={metric.label}
          sourceURI={sourceURI}
          timeRange={timeRangeValue}
          metric={metric}
          metricRequestOptions={metricRequestOptions}
        />
      ))}
    </MetricsChartSyncProvider>
  )

  if (!showTimeRangePicker) {
    return charts
  }

  return (
    <Stack>
      <TimeRangePicker
        value={timeRange}
        onChange={(value) => {
          setTimeRange(value)
          setTimeRangeValue(toTimeRangeValue(value))
        }}
      />

      {charts}
    </Stack>
  )
}
