import { Box, Divider, Flex, Group, HoverCard, NumberInput, Stack, Typography } from '@tidbcloud/uikit'
import { FormNumberInput } from '@tidbcloud/uikit/biz'
import { IconInfoCircle } from '@tidbcloud/uikit/icons'
import { useEffect } from 'react'
import { useFormContext } from 'react-hook-form'
import { useQuery } from 'react-query'

import { FormItem } from 'dbaas/screens/NextGen/my-tidb-creation/shared/FormItem'
import { tidbServiceCalculateMinRcu } from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2'
import { Commonv1beta1ServicePlan } from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2/interface'
import useStores from 'dbaas/stores/useStores'

import { ESSENTIAL_V2_RCU_MAX, ESSENTIAL_V2_RCU_MIN, ESSENTIAL_V2_RCU_STEP } from '../schema'
import { EssentialV2FormValue } from '../types'

const SERVICE_PLAN = Commonv1beta1ServicePlan.Essential_V2

interface CapacitySectionProps {
  projectId: string
}

export function CapacitySection({ projectId }: CapacitySectionProps) {
  const { watch, setValue } = useFormContext<EssentialV2FormValue>()
  const maxRcu = watch('maxRcu')
  const currentMinRcu = watch('minRcu')
  const regionId = watch('region')
  const {
    store: {
      lastVisitLocation: { orgId }
    }
  } = useStores()

  const { data: calculatedMinRcu } = useQuery(
    ['essential-v2-calculate-min-rcu', orgId, projectId, regionId, maxRcu],
    () =>
      tidbServiceCalculateMinRcu(
        {
          maxRcu: String(maxRcu),
          regionId,
          servicePlan: SERVICE_PLAN
        },
        { orgId, projectId }
      ),
    {
      refetchOnWindowFocus: false,
      keepPreviousData: true,
      enabled: !!(orgId && projectId && regionId && maxRcu),
      select: (data) => Number(data?.minRcu || ESSENTIAL_V2_RCU_MIN)
    }
  )

  const minRcu = calculatedMinRcu ?? currentMinRcu ?? ESSENTIAL_V2_RCU_MIN

  useEffect(() => {
    if (calculatedMinRcu === undefined) {
      return
    }

    setValue('minRcu', calculatedMinRcu, { shouldDirty: false, shouldValidate: false, shouldTouch: false })
  }, [calculatedMinRcu, setValue])

  return (
    <FormItem
      label="Capacity"
      description={
        <Typography variant="body-md" c="carbon.7">
          TiDB Cloud Essential instance capacity is measured in Request Capacity Units (RCUs). TiDB Cloud automatically
          creates scaling rules based on the minimum and maximum capacity setting.{' '}
          <a href="https://www.pingcap.com/tidb-cloud-essential-pricing-details/" target="_blank" rel="noreferrer">
            Learn more
          </a>
          .
        </Typography>
      }
    >
      <Stack gap={8}>
        <Group align="center" gap="xl">
          <NumberInput
            name="minimumRCU"
            value={minRcu}
            disabled
            leftAddon="Minimum Billing RCU"
            sx={{ flex: 1 }}
            suffix=" RCUs"
            step={ESSENTIAL_V2_RCU_STEP}
          />
          <Flex h={40} align="center">
            <Divider w={16} color="carbon.5" />
          </Flex>
          <FormNumberInput
            name="maxRcu"
            leftAddon={
              <Group gap={4} wrap="nowrap" component="span">
                max
                <HoverCard shadow="md" withArrow width={400}>
                  <HoverCard.Target>
                    <IconInfoCircle sx={{ cursor: 'pointer' }} />
                  </HoverCard.Target>
                  <HoverCard.Dropdown>
                    <Typography variant="body-lg">
                      TiDB Cloud offers a small buffer above the maximum RCU to accommodate short bursts in demand and
                      lower the chance of throttling. Continuous demand that exceeds the maximum, though, may still lead
                      to throttling.
                    </Typography>
                  </HoverCard.Dropdown>
                </HoverCard>
              </Group>
            }
            sx={{ flex: 1 }}
            suffix=" RCUs"
            min={ESSENTIAL_V2_RCU_MIN}
            max={ESSENTIAL_V2_RCU_MAX}
            step={ESSENTIAL_V2_RCU_STEP}
            rules={{
              required: 'Required',
              min: { value: ESSENTIAL_V2_RCU_MIN, message: `RCUs should be greater than ${ESSENTIAL_V2_RCU_MIN}` },
              max: { value: ESSENTIAL_V2_RCU_MAX, message: `RCUs should be less than ${ESSENTIAL_V2_RCU_MAX}` },
              validate: (val) => {
                if (val % ESSENTIAL_V2_RCU_STEP !== 0) {
                  return `RCUs should be in increments of ${ESSENTIAL_V2_RCU_STEP}`
                }
                return true
              }
            }}
          />
        </Group>
        <Typography variant="body-md" c="carbon.7">
          <Box component="span" fw={500}>
            Minimum Billing RCUs = {minRcu}.
          </Box>{' '}
          It is automatically set based on your maximum RCU value. If your actual usage is below this limit, you will be
          billed for this amount. RCUs start from 2,000 and can be increased up to 100,000 in increments of 100.
        </Typography>
      </Stack>
    </FormItem>
  )
}
