import React, { useMemo } from 'react'

import useUrlState from '@ahooksjs/use-url-state'
import { Card, Stack, Title, Box } from '@mantine/core'
import dayjs from 'dayjs'
import { SyncChartPointer } from 'metrics-chart'

import DatePicker from '~/components/DatePicker'
import { useCurCluster, useCurOrg } from '~/hooks/state'

import { MetricChart } from '../components/MetricChart'
import { TimeRange } from '../components/TimeWindowSelect'
import {
  DEDICATED_METRIC_CONFIG,
  ESSENTIAL_METRIC_CONFIG,
  PREMIUM_METRIC_CONFIG,
  STARTER_METRIC_CONFIG
} from './metric-config'

export const ClusterMetricsPage: React.FC = () => {
  const { curOrg: org } = useCurOrg()
  const { curCluster: cluster } = useCurCluster()
  const endTime = cluster!.endTime!
  const [queryParams, setQueryParams] = useUrlState({
    from: 'end-2h',
    to: 'end'
  })
  function handleTimeRangeChange(newTr: TimeRange) {
    setQueryParams({ from: newTr.start.toFixed(0), to: newTr.end.toFixed(0) })
  }
  const timeRange = useMemo(() => {
    if (queryParams.to === 'end') {
      let now = endTime
      if (endTime === 0) {
        now = dayjs().unix()
      }
      return {
        start: now - 2 * 60 * 60,
        end: now
      }
    }
    return {
      start: Number(queryParams.from),
      end: Number(queryParams.to)
    }
  }, [queryParams.from, queryParams.to, { endTime }])

  const metricConfigs = useMemo(() => {
    if (cluster?.computed.isPremium) {
      return PREMIUM_METRIC_CONFIG
    }
    if (cluster?.computed.isEssential) {
      return ESSENTIAL_METRIC_CONFIG
    }
    if (cluster?.computed.isStarter) {
      return STARTER_METRIC_CONFIG
    }
    return DEDICATED_METRIC_CONFIG
  }, [cluster])

  return (
    <Card withBorder>
      <Stack>
        <Title order={5}>Overview</Title>
        <Box>
          <DatePicker.RangePicker
            showTime={{ format: 'HH:mm' }}
            format='YYYY-MM-DD HH:mm'
            value={[dayjs.unix(timeRange.start), dayjs.unix(timeRange.end)]}
            allowClear={false}
            onCalendarChange={(tr, _, info) => {
              if (info.range === 'start') {
                return
              }
              handleTimeRangeChange({
                start: tr?.[0]?.unix() ?? 0,
                end: tr?.[1]?.unix() ?? 0
              })
            }}
          />
        </Box>
        <SyncChartPointer>
          <MetricChart
            charts={metricConfigs}
            cluster={cluster!}
            range={[timeRange.start, timeRange.end]}
            orgId={org!.id!}
            isCloud={true}
          />
        </SyncChartPointer>
      </Stack>
    </Card>
  )
}
