import { Alert, Box, Loader, Stack } from '@tidbcloud/uikit'
import { FormNumberInput } from '@tidbcloud/uikit/biz'
import { observer } from 'mobx-react'
import { useFormContext } from 'react-hook-form'

import { SharedCluster } from 'dbaas/features/ClusterManagement/cluster'
import { SpendLimitInputDesc } from 'dbaas/features/ClusterManagement/serverless/spend-limit/FormField'
import { useSpendLimitFreeQuota } from 'dbaas/features/ClusterManagement/serverless/spend-limit/helpers'
import { HeadLabel } from 'dbaas/screens/ClustersV2/new/components'
import { useGetClusterSpendLimit } from 'dbaas/services/api'
import { useGetPricingDetails } from 'dbaas/services/api-clients/legacy/serverless'
import useStores from 'dbaas/stores/useStores'
import { toDollars } from 'dbaas/utils/format'

import { SpendEstimation } from '../Edit/SpendEstimation'

import { EditFormValueState } from './helpers'

interface ClusterPlanFieldProps {
  cluster: SharedCluster
}

export const ClusterPlanField = observer(({ cluster }: ClusterPlanFieldProps) => {
  const {
    store: {
      lastVisitLocation: { orgId }
    }
  } = useStores()
  const { id: clusterId } = cluster

  const {
    setValue,
    watch,
    formState: { errors }
  } = useFormContext<EditFormValueState>()
  const monthlySpendingLimit = watch('monthlySpendingLimit')
  const isError = !!errors?.monthlySpendingLimit

  const pricingQuery = useGetPricingDetails(
    {
      region: cluster.region,
      cloud_provider: cluster.provider
    },
    {
      query: {
        enabled: !!cluster.region && !!cluster.provider
      }
    }
  )
  const pricingValid = !!(pricingQuery.data?.request_units && pricingQuery.data.row_based_storage)
  const quotaQuery = useSpendLimitFreeQuota(cluster.computed.projectId)

  const spendingLimitQuery = useGetClusterSpendLimit(orgId, clusterId, {
    query: {
      refetchOnWindowFocus: false,
      onSuccess(data) {
        if (data.spend_limit > 0) {
          setValue('monthlySpendingLimit', toDollars(data.spend_limit))
        }
      }
    }
  })

  return (
    <Stack gap="xl">
      <HeadLabel
        label="Capacity"
        description={
          <>
            Capacity scales automatically based on your workload, and you only pay for what you use. Each organization
            can have up to {quotaQuery.maxFreeCount} free Starter instances, each with 5GiB Row-based Storage and 50M
            Request Units.{' '}
            {pricingValid &&
              `Additional resources are priced at ${pricingQuery.data?.row_based_storage} Row-based Storage and ${pricingQuery.data?.request_units} Request Units.`}{' '}
            Learn more about{' '}
            <a
              href="https://docs.pingcap.com/tidbcloud/manage-serverless-spend-limit/"
              target="_blank"
              rel="noreferrer"
              onClick={(e) => e.stopPropagation()}
            >
              capacity
            </a>
            .
          </>
        }
      />
      <Box>
        <FormNumberInput
          name="monthlySpendingLimit"
          label="Monthly Spending Limit"
          leftSection={
            <Box c={isError ? 'red' : 'carbon.8'} fz={14} w={16} ta="right">
              $
            </Box>
          }
          leftSectionWidth={28}
          disabled={spendingLimitQuery.isFetching}
          rightSection={spendingLimitQuery.isFetching ? <Loader size="xs" /> : undefined}
          fixedDecimalScale
          decimalScale={2}
          min={0.01}
          rules={{
            pattern: {
              value: /^\d+$|^\d+\.\d{0,2}$/,
              message: 'Please enter an integer or a number with two decimal places.'
            },
            min: {
              value: 0.01,
              message: 'The spending limit must be greater than or equal to $0.01.'
            },
            required: {
              value: true,
              message: 'The spending limit is required.'
            }
          }}
          styles={{ control: { cursor: 'pointer', ':disabled': { cursor: 'not-allowed' } } }}
        />
        {!isError && (
          <SpendLimitInputDesc value={monthlySpendingLimit} region={cluster.region} clusterId={clusterId} mt={8} />
        )}
      </Box>
      {quotaQuery.isSuccess && !quotaQuery.exhausted && (
        <Alert color="peacock">
          You will only be charged if you exceed the free 5GiB storage or free 50M Request Units per month. If you reach
          your spend limit, the instance is not accessible and your spend will not increase anymore. You'll receive
          alerts when you are nearing your limit.
        </Alert>
      )}
      <SpendEstimation cluster={cluster} />
    </Stack>
  )
})
