import { Alert, Anchor } from '@tidbcloud/uikit'
import { IconAlertTriangle } from '@tidbcloud/uikit/icons'
import { useLocation } from 'react-router-dom'

import { useResourcePoolServiceGetResourcePool } from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2'

import { isByocVcpuLimitReached } from './resource-pool-vcpu-limit-utils'

export interface ResourcePoolVcpuLimitValidation {
  isError: boolean
  isLimitReached: boolean
  isLoading: boolean
}

export const DEFAULT_RESOURCE_POOL_VCPU_LIMIT_VALIDATION: ResourcePoolVcpuLimitValidation = {
  isError: false,
  isLimitReached: false,
  isLoading: false
}

const SILENT_QUERY_REQUEST = { isShowToast: false, isHandleErr: false }

export const useResourcePoolVcpuLimitValidation = ({
  enabled = true,
  orgId,
  projectId,
  resourcePoolId
}: {
  enabled?: boolean
  orgId?: string
  projectId?: string
  resourcePoolId?: string
}) => {
  const query = useResourcePoolServiceGetResourcePool(
    resourcePoolId ?? '',
    { orgId: orgId ?? '', projectId: projectId ?? '' },
    {
      query: {
        enabled: enabled && !!orgId && !!projectId && !!resourcePoolId,
        refetchOnWindowFocus: false,
        retry: 1
      },
      request: SILENT_QUERY_REQUEST
    }
  )

  return {
    isError: enabled && !!resourcePoolId && query.isError,
    isLimitReached: enabled && isByocVcpuLimitReached(query.data),
    isLoading: enabled && !!resourcePoolId && query.isLoading,
    resourcePool: query.data
  }
}

export const ResourcePoolVcpuLimitFeedback = ({
  resourcePoolId,
  validation
}: {
  resourcePoolId?: string
  validation: ResourcePoolVcpuLimitValidation
}) => {
  const location = useLocation()

  if (validation.isError) {
    return (
      <Alert
        color="red"
        title="Resource pool details could not be loaded"
        data-testid="byoc-resource-pool-vcpu-limit-error"
      >
        Refresh the page or try again later.
      </Alert>
    )
  }

  if (!validation.isLimitReached || !resourcePoolId) {
    return null
  }

  const resourcePoolDetailsHref = `/byoc/resource-pools/${encodeURIComponent(resourcePoolId)}${location.search}`

  return (
    <Alert color="yellow" icon={<IconAlertTriangle size={16} />} data-testid="byoc-resource-pool-vcpu-limit-alert">
      This resource pool has reached its vCPU limit. Go to this{' '}
      <Anchor href={resourcePoolDetailsHref} c="peacock.7">
        Resource Pool Detail page
      </Anchor>{' '}
      to update the pool vCPU limit or select another resource pool to continue.
    </Alert>
  )
}
