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

import { FormItem } from '../components/FormItem'

import { ESSENTIAL_RCU_MAX, ESSENTIAL_RCU_MIN, ESSENTIAL_RCU_STEP } from './helper'

export const CapacityField = ({ ...props }: StackProps) => {
  const { watch, trigger } = useFormContext<{
    autoScaling: {
      minRcu?: number
      maxRcu?: number
    }
  }>()
  const minRcu = watch('autoScaling.minRcu')

  return (
    <Stack gap={8} {...props}>
      <Typography variant="label-md">Autoscaling</Typography>
      <Group align="flex-start" gap={24}>
        <FormNumberInput
          name="autoScaling.minRcu"
          leftAddon={
            <Group gap={4} wrap="nowrap" component="span">
              min
              <HoverCard shadow="md" withArrow width={400}>
                <HoverCard.Target>
                  <IconInfoCircle sx={{ cursor: 'pointer' }} />
                </HoverCard.Target>
                <HoverCard.Dropdown>
                  <Typography variant="body-lg">
                    Keep the value at the minimum ({ESSENTIAL_RCU_MIN}) if cost is a concern and traffic is bursty.
                    Increase it if you require more consistent performance, smoother autoscaling, or better readiness
                    for sudden surges.
                  </Typography>
                </HoverCard.Dropdown>
              </HoverCard>
            </Group>
          }
          sx={{ flex: 1 }}
          suffix=" RCUs"
          min={ESSENTIAL_RCU_MIN}
          max={ESSENTIAL_RCU_MAX}
          step={ESSENTIAL_RCU_STEP}
          rules={{
            required: 'Required',
            min: { value: ESSENTIAL_RCU_MIN, message: `RCUs should be greater than ${ESSENTIAL_RCU_MIN}` },
            max: { value: ESSENTIAL_RCU_MAX, message: `RCUs should be less than ${ESSENTIAL_RCU_MAX}` },
            validate: (val) => {
              if (val % ESSENTIAL_RCU_STEP !== 0) {
                return `RCUs should be in increments of ${ESSENTIAL_RCU_STEP}`
              }
              return true
            }
          }}
          onChange={() => {
            trigger('autoScaling')
          }}
        />
        <Flex h={40} align="center">
          <Divider w={16} color="carbon.5"></Divider>
        </Flex>
        <FormNumberInput
          name="autoScaling.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_RCU_MIN}
          max={ESSENTIAL_RCU_MAX}
          step={ESSENTIAL_RCU_STEP}
          rules={{
            required: 'Required',
            min: { value: ESSENTIAL_RCU_MIN, message: `RCUs should be greater than ${ESSENTIAL_RCU_MIN}` },
            max: { value: ESSENTIAL_RCU_MAX, message: `RCUs should be less than ${ESSENTIAL_RCU_MAX}` },
            validate: (val) => {
              if (val % ESSENTIAL_RCU_STEP !== 0) {
                return `RCUs should be in increments of ${ESSENTIAL_RCU_STEP}`
              }
              if (val && minRcu && val < minRcu) {
                return 'Max RCUs should be greater or equal to min RCUs'
              }
              return true
            }
          }}
          onChange={() => {
            trigger('autoScaling')
          }}
        />
      </Group>
      <Typography variant="body-md" c="carbon.7">
        <Box component="span" fw={500}>
          Minimum Billing RCUs = {minRcu && minRcu > ESSENTIAL_RCU_MIN ? minRcu : ESSENTIAL_RCU_MIN}.
        </Box>{' '}
        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>
  )
}

export const Capacity = () => {
  return (
    <FormItem
      label="Capacity"
      description={
        <Typography variant="body-md" c="carbon.7">
          Cluster provisioned 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>
      }
    >
      <CapacityField />
    </FormItem>
  )
}
