import { Accordion, Box, Loader } from '@tidbcloud/uikit'
import { FormNumberInput } from '@tidbcloud/uikit/biz'
import { useEffect } from 'react'
import { useFormContext } from 'react-hook-form'

import { SpendLimitInputDesc, useSpendLimitFreeQuota } from 'dbaas/features/ClusterManagement/serverless'
import { useGetPricingDetails } from 'dbaas/services/api-clients/legacy/serverless'

import { HeadLabel } from '../../components'
import { CreationFormValueState } from '../../helpers'

interface StarterCapacityItemProps {
  names: {
    plan: string
    spendingLimit: string
  }
  spendingLimitDescSuffix?: string
}

export const StarterCapacityItem = ({ names, spendingLimitDescSuffix }: StarterCapacityItemProps) => {
  const {
    register,
    watch,
    setValue,
    trigger,
    formState: { errors }
  } = useFormContext<Pick<CreationFormValueState, 'serverless'>>()
  const formValues = watch('serverless') || {}
  const { provider, region, plan, monthlySpendingLimit, encrypted } = formValues
  const isError = !!errors?.serverless?.monthlySpendingLimit

  const pricingQuery = useGetPricingDetails(
    {
      region,
      cloud_provider: provider
    },
    {
      query: {
        enabled: !!(provider && region)
      }
    }
  )
  const pricingValid = !!(pricingQuery.data?.request_units && pricingQuery.data.row_based_storage)
  const { exhausted, maxFreeCount, ...quotaQuery } = useSpendLimitFreeQuota()

  useEffect(() => {
    if (exhausted) {
      setValue(names.plan as 'serverless.plan', 'scalable')
    } else if (quotaQuery.isSuccess && !exhausted) {
      setValue(names.spendingLimit as 'serverless.monthlySpendingLimit', 0)
      setValue(names.plan as 'serverless.plan', 'free')
    }
  }, [exhausted, names.plan, names.spendingLimit, quotaQuery.isSuccess, setValue])
  useEffect(() => {
    if (plan) {
      trigger(names.spendingLimit as 'serverless.monthlySpendingLimit')
    }
  }, [plan, names.spendingLimit, trigger])

  return (
    <>
      <Accordion.Control data-mp-no-event>
        <HeadLabel
          label="Capacity"
          description={
            <>
              Capacity scales automatically based on your workload, and you only pay for what you use. Each organization
              can have up to {maxFreeCount} free Starter instances, each with 5GiB Row-based Storage and 50M Request
              Units.{' '}
              {pricingValid &&
                `Additional resources are priced at ${pricingQuery.data?.row_based_storage} Row-based Storage and ${pricingQuery.data?.request_units} Request Units.`}{' '}
              Learn more about{' '}
              <a
                href="https://www.pingcap.com/tidb-serverless-pricing-details/"
                target="_blank"
                rel="noreferrer"
                onClick={(e) => e.stopPropagation()}
              >
                capacity
              </a>
              .
            </>
          }
        />
      </Accordion.Control>
      <Accordion.Panel>
        <input type="hidden" {...register(names.plan as 'serverless.plan')} />
        <FormNumberInput
          name={names.spendingLimit}
          label="Monthly Spending Limit"
          fixedDecimalScale
          decimalScale={2}
          min={exhausted ? 0.01 : 0}
          disabled={quotaQuery.isLoading}
          rightSection={quotaQuery.isLoading ? <Loader size="xs" /> : undefined}
          leftSection={
            <Box c={isError ? 'red' : 'carbon.8'} fz={14} w={16} ta="right">
              $
            </Box>
          }
          leftSectionWidth={28}
          rules={{
            pattern: {
              value: /^\d+$|^\d+\.\d{0,2}$/,
              message: 'Please enter an integer or a number with two decimal places.'
            },
            min: {
              value: exhausted ? 0.01 : 0,
              message: exhausted ? 'The spending limit must be greater than or equal to $0.01' : ''
            },
            required: {
              value: exhausted,
              message: 'The free quota of your organization is exhausted. Please set the spending limit.'
            }
          }}
          onChange={(value) => {
            const fixedValue = Number(value ?? 0)

            if (fixedValue > 0) {
              setValue(names.plan as 'serverless.plan', 'scalable')
            } else if (!fixedValue && !exhausted) {
              setValue(names.plan as 'serverless.plan', 'free')
            }
          }}
          styles={{
            control: {
              cursor: 'pointer',
              ':disabled': {
                cursor: 'not-allowed'
              }
            }
          }}
        />
        {!isError && (
          <SpendLimitInputDesc
            value={monthlySpendingLimit}
            region={region}
            encrypted={encrypted}
            mt={8}
            suffix={spendingLimitDescSuffix}
          />
        )}
      </Accordion.Panel>
    </>
  )
}
