import { Anchor, Box, Group, Stack, StackProps, Typography } from '@tidbcloud/uikit'
import { FormNumberInput } from '@tidbcloud/uikit/biz'
import { IconLinkExternal01 } from '@tidbcloud/uikit/icons'
import { useFormContext } from 'react-hook-form'

import { PREMIUM_MIN_RCU, PREMIUM_MAX_RCU_FALLBACK } from './use-capacity-limits'

interface CapacityFieldProps extends StackProps {
  formMaxRcuName?: string
  instanceMaxRcu?: number
  availableTotalRcu?: number
  showBillingDescription?: boolean
}

export const CapacityField = ({
  formMaxRcuName = 'maxRcu',
  instanceMaxRcu,
  availableTotalRcu,
  showBillingDescription = true,
  ...props
}: CapacityFieldProps) => {
  const { watch } = useFormContext<{ maxRcu: number }>()
  const maxRcu = watch(formMaxRcuName as 'maxRcu')
  const minRcu = maxRcu ? Math.max(maxRcu / 4, PREMIUM_MIN_RCU) : PREMIUM_MIN_RCU
  const earlyBirdMinRcuRendered = minRcu > PREMIUM_MIN_RCU

  // Calculate effective maximum value for maxRcu from all constraints
  const effectiveMaxRcu = Math.min(
    instanceMaxRcu ?? PREMIUM_MAX_RCU_FALLBACK,
    availableTotalRcu ?? PREMIUM_MAX_RCU_FALLBACK
  )

  return (
    <Stack gap={8} {...props}>
      <Group align="flex-start">
        <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'
              }

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

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

              return true
            }
          }}
        />
      </Group>
      {showBillingDescription && (
        <Typography variant="body-md" c="carbon.7">
          <Box component="span" fw={500}>
            Minimum Billing RCU ={' '}
            {earlyBirdMinRcuRendered ? (
              <>
                <Box component="span" c="carbon.6" sx={{ textDecoration: 'line-through' }}>
                  {minRcu}
                </Box>{' '}
                {PREMIUM_MIN_RCU}
              </>
            ) : (
              minRcu
            )}
            .
          </Box>{' '}
          If your actual usage is below this limit, you will be billed for this amount. Max RCU must be in increments of
          100. For detailed pricing information, please{' '}
          <Anchor
            href="https://www.pingcap.com/contact-us/"
            target="_blank"
            rel="noreferrer"
            sx={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}
          >
            contact our sales team <IconLinkExternal01 />
          </Anchor>
          .
        </Typography>
      )}
    </Stack>
  )
}
