import { AnimatedNumber, Stack, Typography } from '@tidbcloud/uikit'
import { useDebouncedValue } from '@tidbcloud/uikit/hooks'

import { usePredictCost } from 'dbaas/services/api-clients/legacy/serverless'

interface PremiumPricingCostProps {
  cloudProvider: string
  region: string
  minRcu: number
  maxRcu: number
}

export function PremiumPricingCost({ cloudProvider, region, minRcu, maxRcu }: PremiumPricingCostProps) {
  const [debouncedMinRcu] = useDebouncedValue(minRcu, 500)
  const [debouncedMaxRcu] = useDebouncedValue(maxRcu, 500)
  const { data: minPredictCost } = usePredictCost(
    {
      cloud_provider: cloudProvider,
      region,
      rcu: debouncedMinRcu || 0,
      service_plan: 'premium'
    },
    {
      query: {
        enabled: !!(cloudProvider && region && debouncedMinRcu),
        select: (data) => ({
          monthly: Number(data?.rcu_cost_monthly || 0)
        }),
        keepPreviousData: true,
        refetchOnWindowFocus: false
      }
    }
  )
  const { data: maxPredictCost } = usePredictCost(
    {
      cloud_provider: cloudProvider,
      region,
      rcu: debouncedMaxRcu || 0,
      service_plan: 'premium'
    },
    {
      query: {
        enabled: !!(cloudProvider && region && debouncedMaxRcu),
        select: (data) => ({
          monthly: Number(data?.rcu_cost_monthly || 0)
        }),
        keepPreviousData: true,
        refetchOnWindowFocus: false
      }
    }
  )

  return (
    <Stack gap={4} py="xl">
      <AnimatedNumber
        value={minPredictCost?.monthly ?? 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-md" c="carbon.8" inline>
        Pay only for your actual usage. Monthly fees are limited by your maximum RCU setting, up to a maximum cost of{' '}
        <Typography variant="title-md" component="span">
          ${(maxPredictCost?.monthly ?? 0).toFixed(2)}
        </Typography>{' '}
        per month. Learn more{' '}
        <a target="_blank" rel="noreferrer" href="https://www.pingcap.com/tidb-cloud-premium-pricing-details/">
          Pricing
        </a>
      </Typography>
    </Stack>
  )
}
