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

import { useOrgProjectClusterIds } from 'dbaas/features/Common'
import {
  ESSENTIAL_V2_RCU_MAX,
  ESSENTIAL_V2_RCU_MIN,
  ESSENTIAL_V2_RCU_STEP
} from 'dbaas/screens/NextGen/my-tidb-creation/plans/EssentialV2/schema'
import { FormSection } from 'dbaas/screens/Restore/FormSection'
import { tidbServiceCalculateMinRcu } from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2'

interface EssentialV2RestoreCapacityFormData {
  maxRcu: number
  minRcu?: number
  regionId: string
}

export const EssentialV2RestoreCapacitySection = ({ projectId }: { projectId: string }) => {
  const methods = useFormContext<EssentialV2RestoreCapacityFormData>()
  const { orgId } = useOrgProjectClusterIds()
  const maxRcu = methods.watch('maxRcu')
  const currentMinRcu = methods.watch('minRcu')
  const regionId = methods.watch('regionId')

  const { data: calculatedMinRcu } = useQuery(
    ['essential-v2-restore-calculate-min-rcu', orgId, projectId, regionId, maxRcu],
    () =>
      tidbServiceCalculateMinRcu(
        {
          maxRcu: String(maxRcu),
          regionId,
          servicePlan: 'Essential_V2'
        },
        { 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
    }

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

  return (
    <FormSection
      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.
        </Typography>
      }
    >
      <Stack gap={8} data-testid="essential-v2-restore-capacity">
        <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="Max"
            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: (value) =>
                value % ESSENTIAL_V2_RCU_STEP === 0 ? true : `RCUs should be in increments of ${ESSENTIAL_V2_RCU_STEP}`
            }}
          />
        </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>
    </FormSection>
  )
}
