import { Anchor, NumberInput } from '@tidbcloud/uikit'
import { useController, useFormContext } from 'react-hook-form'

import { useRequestSupport } from 'dbaas/screens/HelpCenter/RequestSupport/helper'
import { PremiumByocFormValue } from 'dbaas/screens/NextGen/my-tidb-creation/shared/premium-byoc/types'

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

interface PremiumMaxRcuInputProps {
  formMaxRcuName: string
  effectiveMaxRcu: number
  instanceMaxRcu?: number
  availableTotalRcu?: number
}

export const PremiumMaxRcuInput = ({
  formMaxRcuName,
  effectiveMaxRcu,
  instanceMaxRcu,
  availableTotalRcu
}: PremiumMaxRcuInputProps) => {
  const { control } = useFormContext<PremiumByocFormValue>()
  const { open: openSupport } = useRequestSupport()
  const {
    field,
    fieldState: { error }
  } = useController({
    control,
    name: formMaxRcuName as 'maxRcu',
    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
      }
    }
  })
  const isInstanceLimitError = error?.message?.startsWith('Max RCUs cannot exceed the limit of')

  return (
    <NumberInput
      {...field}
      data-testid="premium-max-rcu-input"
      leftAddon="Max"
      suffix=" RCUs"
      flex={1}
      min={PREMIUM_MIN_RCU}
      max={effectiveMaxRcu}
      step={100}
      error={
        isInstanceLimitError ? (
          <>
            Max RCUs cannot exceed the limit of {instanceMaxRcu?.toLocaleString()}. Please{' '}
            <Anchor component="button" type="button" c="peacock.7" onClick={() => openSupport()}>
              contact support
            </Anchor>{' '}
            to request a quota increase.
          </>
        ) : (
          error?.message
        )
      }
    />
  )
}
