import { notifier, Typography, TypographyProps } from '@tidbcloud/uikit'
import { useDebouncedValue } from '@tidbcloud/uikit/hooks'
import { observer } from 'mobx-react'

import { usePredictClusterSpendLimit, usePredictSpendLimit } from 'dbaas/services'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import useStores from 'dbaas/stores/useStores'
import { formatStorage, formatToMillions, toCents } from 'dbaas/utils/format'

interface SpendLimitInputDescProps extends TypographyProps {
  projectId: string
  value?: number
  region: string
  encrypted?: boolean
  tidbId?: string
  suffix?: string
  resourceName?: string
}

export const SpendLimitInputDesc = observer(
  ({
    projectId,
    value,
    region,
    encrypted,
    tidbId = '',
    suffix,
    resourceName = 'instance',
    ...restProps
  }: SpendLimitInputDescProps) => {
    const {
      store: {
        lastVisitLocation: { orgId }
      }
    } = useStores()

    const fixedValue = Number(value ?? 0)
    const [debouncedValue] = useDebouncedValue(fixedValue, 500)

    const { data: creationData, isFetching: creationLoading } = usePredictSpendLimit(
      orgId,
      {
        spend_limit: toCents(debouncedValue),
        project_id: projectId,
        region,
        enhanced_encryption_enabled: encrypted
      },
      {
        query: {
          enabled: !!(orgId && projectId && region && debouncedValue) && !tidbId,
          onError: (err) => {
            notifier.error(getErrorMessage(err, true))
          }
        }
      }
    )

    const { data: editData, isFetching: editLoading } = usePredictClusterSpendLimit(
      orgId,
      tidbId,
      {
        spend_limit: toCents(debouncedValue),
        region
      },
      {
        query: {
          enabled: !!(orgId && tidbId && region && debouncedValue),
          onError: (err) => {
            notifier.error(getErrorMessage(err, true))
          }
        }
      }
    )

    const data = tidbId ? editData : creationData
    const loading = tidbId ? editLoading : creationLoading

    if (!fixedValue || Number.isNaN(fixedValue)) {
      return (
        <Typography variant="body-sm" c="carbon.7" {...restProps}>
          If the limit is set to $0, you can use only the free quota. Once the free quota is exhausted and the spending
          limit is reached, the {resourceName} will be automatically throttled. You can update the spending limit at any
          time.
        </Typography>
      )
    }

    if (loading) {
      return (
        <Typography variant="body-sm" c="carbon.7" {...restProps}>
          Calculating quota...
        </Typography>
      )
    }

    if (!data) {
      return null
    }

    return (
      <Typography variant="body-sm" c="carbon.7" {...restProps}>
        Up to {formatToMillions(+data.max_request_units)} Request Units per month
        {+data.free_request_units > 0 ? ` with ${formatToMillions(+data.free_request_units)} free quota included` : ''},
        up to {formatStorage(+data.max_row_storage)} of Row-based Storage per month
        {+data.free_row_storage > 0 ? ` with ${formatStorage(+data.free_row_storage)} free quota included` : ''}.
        {suffix ? ` ${suffix}` : null}
      </Typography>
    )
  }
)
