import { Box, Flex, Paper, Typography } from '@tidbcloud/uikit'
import { observer } from 'mobx-react'

import config from 'config'
import { SharedCluster } from 'dbaas/features/ClusterManagement/cluster'
import { useSpendLimitSummary } from 'dbaas/screens/Cluster/OverviewV2/helpers'
import { SpendingEstimationChart } from 'dbaas/screens/Cluster/OverviewV2/SpendLimitUsage/EstimationCard'
import { useGetForecastResult } from 'dbaas/screens/Cluster/OverviewV2/SpendLimitUsage/EstimationCard/helpers'
import { useGetSpendLimitDetails } from 'dbaas/services/api'
import useStores from 'dbaas/stores/useStores'
import { toDollars } from 'dbaas/utils/format'
import { moneyFormatter } from 'dbaas/utils/numberFormat'

interface SpendEstimationProps {
  cluster: SharedCluster
}

export const SpendEstimation = observer(({ cluster }: SpendEstimationProps) => {
  const {
    store: {
      lastVisitLocation: { orgId }
    }
  } = useStores()
  const projectId = cluster.computed.projectId

  const { data: detailData } = useGetSpendLimitDetails(orgId, cluster?.id, {
    query: {
      refetchInterval: 30 * 1000
    }
  })
  const { cost, hasCost, hasSpendlimit } = useSpendLimitSummary(detailData)
  const { data: forecastData } = useGetForecastResult(orgId, projectId, cluster, {
    query: {
      enabled: config.ENABLE_SERVERLESS_ESTIMATION && hasSpendlimit
    },
    request: {
      isHandleErr: true,
      _warningStatus: [404]
    }
  })
  const estimationVisible = !!detailData?.spend_limit && hasCost && !!forecastData

  if (!estimationVisible) {
    return null
  }

  return (
    <Box>
      <Flex mb={8} align="center">
        <Typography variant="label-lg">Recommend monthly spending limit:</Typography>
        <Typography variant="headline-sm" ml={4}>
          {moneyFormatter(forecastData.data.predict_month_end_water_mark)}
        </Typography>
      </Flex>
      <Paper
        shadow="none"
        withBorder
        p="md"
        sx={(theme) => ({
          borderColor: theme.colors.carbon[4],
          background: theme.colors.carbon[1]
        })}
      >
        <Typography variant="label-lg" mt={-8} ta="center">
          Spend Estimation
        </Typography>
        <SpendingEstimationChart
          data={forecastData.data}
          currentLimit={toDollars(detailData.spend_limit)}
          cost={toDollars(cost)}
          markerFontSize={12}
        />
      </Paper>
    </Box>
  )
})
