import { AnimatedNumber, Stack, Typography } from '@tidbcloud/uikit'
import { useFormContext } from 'react-hook-form'
import { useQuery } from 'react-query'

import { PremiumByocFormValue } from 'dbaas/screens/NextGen/my-tidb-creation/shared/premium-byoc/types'
import { useTidbServiceEstimatePrice } 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'

interface PremiumReservedPricingCostProps {
  cloudProvider: string
  region: string
  projectId: string
}

export function PremiumReservedPricingCost({ cloudProvider, region, projectId }: PremiumReservedPricingCostProps) {
  const {
    store: {
      lastVisitLocation: { orgId }
    }
  } = useStores()
  const { watch } = useFormContext<PremiumByocFormValue>()
  const reservedCapacityTemplateId = watch('reservedCapacityTemplateId')
  const estimatePriceMutator = useTidbServiceEstimatePrice()

  const { data: predictCost } = useQuery(
    ['premium-reserved-estimate-price', orgId, projectId, cloudProvider, region, reservedCapacityTemplateId],
    () =>
      estimatePriceMutator.mutateAsync({
        data: {
          regionId: region,
          reservedCapacityTemplateId,
          servicePlan: Commonv1beta1ServicePlan.Premium_Reserved
        },
        params: {
          orgId,
          projectId
        }
      }),
    {
      enabled: !!(orgId && cloudProvider && region && reservedCapacityTemplateId),
      keepPreviousData: true,
      refetchOnWindowFocus: false
    }
  )

  return (
    <Stack gap={4} py="xl">
      <AnimatedNumber
        value={Number(predictCost?.rcuCostMonthly ?? 0)}
        format={{ maximumFractionDigits: 5, minimumFractionDigits: 2 }}
        prefix="From $"
        suffix=" / month"
        c="carbon.9"
        fw={700}
        fz={20}
        sx={{
          '&::part(suffix)': {
            color: 'var(--mantine-color-carbon-8)',
            fontWeight: 400,
            fontSize: 14,
            marginLeft: 4
          }
        }}
      />
      <Typography variant="body-lg" c="carbon.7">
        estimated cost by purchased vCPU
      </Typography>
    </Stack>
  )
}
