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

import {
  PREMIUM_MAX_RCU_FALLBACK,
  PREMIUM_MIN_RCU
} from 'dbaas/screens/NextGen/my-tidb-creation/shared/premium-byoc/capacity/use-capacity-limits'
import { PremiumByocFormValue } from 'dbaas/screens/NextGen/my-tidb-creation/shared/premium-byoc/types'
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 { PremiumMaxRcuInput } from './PremiumMaxRcuInput'

interface CapacityFieldProps extends StackProps {
  formMaxRcuName?: string
  instanceMaxRcu?: number
  availableTotalRcu?: number
  servicePlan: Commonv1beta1ServicePlan
}

export const CapacityField = ({
  formMaxRcuName = 'maxRcu',
  instanceMaxRcu,
  availableTotalRcu,
  servicePlan,
  ...props
}: CapacityFieldProps) => {
  const { watch, setValue } = useFormContext<PremiumByocFormValue>()
  const maxRcu = watch(formMaxRcuName as 'maxRcu')
  const regionId = watch('regionId')
  const {
    store: {
      lastVisitLocation: { orgId, projectId }
    }
  } = useStores()

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

  useEffect(() => {
    setValue('minRcu', Number(minRcu), { shouldDirty: false, shouldValidate: false, shouldTouch: false })
  }, [minRcu])

  const effectiveMaxRcu = Math.min(
    instanceMaxRcu ?? PREMIUM_MAX_RCU_FALLBACK,
    availableTotalRcu ?? PREMIUM_MAX_RCU_FALLBACK
  )

  return (
    <Stack gap={8} {...props}>
      <Group align="flex-start" gap={24}>
        <NumberInput
          name="minimumRCU"
          value={minRcu}
          disabled
          leftAddon="Minimum Billing RCU"
          suffix=" RCUs"
          flex={1}
          step={100}
        />
        <Flex h={40} align="center">
          <Divider w={16} color="carbon.5"></Divider>
        </Flex>
        {servicePlan === 'Premium' ? (
          <PremiumMaxRcuInput
            formMaxRcuName={formMaxRcuName}
            effectiveMaxRcu={effectiveMaxRcu}
            instanceMaxRcu={instanceMaxRcu}
            availableTotalRcu={availableTotalRcu}
          />
        ) : (
          <FormNumberInput
            name={formMaxRcuName}
            leftAddon="Max"
            suffix=" RCUs"
            flex={1}
            min={PREMIUM_MIN_RCU}
            max={effectiveMaxRcu}
            step={100}
            rules={{
              required: 'Required',
              min: {
                value: PREMIUM_MIN_RCU,
                message: `Value must be at least ${PREMIUM_MIN_RCU}`
              },
              max: { value: effectiveMaxRcu, message: `Value cannot exceed ${effectiveMaxRcu}` },
              validate: (val) => {
                if (val % 100 !== 0) {
                  return 'Value must be in increments of 100'
                }

                if (instanceMaxRcu !== undefined && val > instanceMaxRcu) {
                  return `Max RCU cannot exceed the single instance limit of ${instanceMaxRcu}`
                }

                if (availableTotalRcu !== undefined && val > availableTotalRcu) {
                  return `Max RCU would exceed the total limit. Available: ${availableTotalRcu} RCUs`
                }

                return true
              }
            }}
          />
        )}
      </Group>
      <Typography variant="body-md" c="carbon.7">
        Minimum Billing RCU is automatically set based on your Maximum RCU value. If your actual usage falls below this
        threshold, you will be billed for the minimum amount to cover the cost of reserved resources. For detailed
        pricing information, please{' '}
        <Anchor
          href="https://www.pingcap.com/tidb-cloud-premium-pricing-details/"
          target="_blank"
          rel="noreferrer"
          sx={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}
        >
          refer to our pricing page <IconLinkExternal01 />
        </Anchor>
        .
      </Typography>
    </Stack>
  )
}
