import { Badge, Box, Group, Typography } from '@tidbcloud/uikit'
import { FormSelect } from '@tidbcloud/uikit/biz'
import { useEffect, useMemo } from 'react'
import { useFormContext } from 'react-hook-form'

import { FormItem } from 'dbaas/screens/NextGen/my-tidb-creation/shared/FormItem'
import { PremiumByocFormValue } from 'dbaas/screens/NextGen/my-tidb-creation/shared/premium-byoc/types'
import { useTidbServiceListPremiumReservedCapacityOptions } from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2'
import { V1beta2ReservedCapacityScope } from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2/interface'
import useStores from 'dbaas/stores/useStores'
// import { formatToK } from 'dbaas/utils/format'

interface CapacitySectionProps {
  projectId?: string
  defaultReservedCapacityTemplateId?: string
}

interface CapacityOption {
  value: string
  label: string
  // peakQpsLabel: string
  purchasedVcpuLabel: string
  purchasedVcpu?: string
  scope?: V1beta2ReservedCapacityScope
}

// const formatPeakQpsLabel = (peakQps?: string) =>
//   `Peak QPS up to about ${peakQps ? formatToK(peakQps).replace(/\.\d+\sK$/, ' K') : '-'}`

export function CapacitySection({ projectId, defaultReservedCapacityTemplateId }: CapacitySectionProps) {
  const {
    store: {
      lastVisitLocation: { orgId }
    }
  } = useStores()
  const { register, watch, setValue } = useFormContext<PremiumByocFormValue>()
  const reservedCapacityTemplateId = watch('reservedCapacityTemplateId')

  const capacityOptionsQuery = useTidbServiceListPremiumReservedCapacityOptions(
    { orgId, projectId: projectId ?? '' },
    {
      query: {
        enabled: !!orgId,
        refetchOnWindowFocus: false,
        select: (data) => data?.reservedCapacities ?? []
      }
    }
  )

  const capacityOptions = useMemo<CapacityOption[]>(() => {
    return (capacityOptionsQuery.data ?? [])
      .filter((option) => !!option.id)
      .map((option) => ({
        value: option.id!,
        label: `${option.purchasedVcpu ?? '-'} vCPU`,
        // peakQpsLabel: `(${formatPeakQpsLabel(option.peakQps)})`,
        purchasedVcpuLabel: `${option.purchasedVcpu ?? '-'} vCPU`,
        purchasedVcpu: option.purchasedVcpu,
        scope: option.scope
      }))
  }, [capacityOptionsQuery.data])

  useEffect(() => {
    if (capacityOptions.length === 0) {
      if (reservedCapacityTemplateId) {
        setValue('reservedCapacityTemplateId', '')
      }

      setValue('purchasedVcpu', undefined)

      return
    }

    const hasSelectedOption = capacityOptions.some((option) => option.value === reservedCapacityTemplateId)
    const hasDefaultOption = capacityOptions.some((option) => option.value === defaultReservedCapacityTemplateId)

    if (!hasSelectedOption) {
      setValue(
        'reservedCapacityTemplateId',
        hasDefaultOption ? defaultReservedCapacityTemplateId! : capacityOptions[0].value,
        {
          shouldValidate: true,
          shouldDirty: true
        }
      )
    }
  }, [capacityOptions, defaultReservedCapacityTemplateId, reservedCapacityTemplateId, setValue])

  useEffect(() => {
    const selectedOption = capacityOptions.find((option) => option.value === reservedCapacityTemplateId)

    setValue('purchasedVcpu', selectedOption?.purchasedVcpu)
  }, [capacityOptions, reservedCapacityTemplateId, setValue])

  return (
    <FormItem
      label="Capacity"
      description={
        <Box>
          Select a default capacity option for this instance. Contact PingCAP sales to do size estimation if you need a
          custom option.
        </Box>
      }
    >
      <input type="hidden" {...register('purchasedVcpu')} />
      <FormSelect
        name="reservedCapacityTemplateId"
        label="Available Capacity Options"
        placeholder={capacityOptionsQuery.isLoading ? 'Loading capacity options...' : 'Select a capacity option'}
        disabled={capacityOptionsQuery.isLoading || capacityOptions.length <= 1}
        data={capacityOptions}
        renderOption={({ option }) => {
          const capacityOption = option as CapacityOption

          return (
            <Group justify="space-between" wrap="nowrap" gap={8}>
              <Group gap={4} wrap="wrap" sx={{ flex: 1 }}>
                <Typography>{capacityOption.purchasedVcpuLabel}</Typography>
                {/* <Typography c="carbon.6">{capacityOption.peakQpsLabel}</Typography> */}
              </Group>
              {capacityOption.scope && capacityOption.scope !== V1beta2ReservedCapacityScope.DEFAULT && (
                <Badge variant="outline" size="xs" c="peacock.7" fw={500}>
                  customed
                </Badge>
              )}
            </Group>
          )
        }}
        rules={{ required: 'Please select a capacity option.' }}
      />
    </FormItem>
  )
}
