import { Alert, Anchor, Box, HoverCard, Typography } from '@tidbcloud/uikit'
import { useLocalStorage } from '@tidbcloud/uikit/hooks'
import { IconInfoCircle } from '@tidbcloud/uikit/icons'

import useStores from 'dbaas/stores/useStores'
import { AccountProviders } from 'dbaas/utils/marketplace'
import { eventTracking, MixpanelEvents } from 'dbaas/utils/tracking'

export type SupportedMarketplaceAccountProvider = (typeof AccountProviders)['aws'] | (typeof AccountProviders)['gcp']

export interface MarketplaceRestrictionConfig {
  accountProvider: SupportedMarketplaceAccountProvider
  marketplaceName: 'AWS Marketplace' | 'Google Cloud Marketplace'
  dedicatedOnly: boolean
}

const MARKETPLACE_RESTRICTION_CONFIGS: Record<SupportedMarketplaceAccountProvider, MarketplaceRestrictionConfig> = {
  [AccountProviders.aws]: {
    accountProvider: AccountProviders.aws,
    marketplaceName: 'AWS Marketplace',
    dedicatedOnly: false
  },
  [AccountProviders.gcp]: {
    accountProvider: AccountProviders.gcp,
    marketplaceName: 'Google Cloud Marketplace',
    dedicatedOnly: true
  }
}

export function getMarketplaceRestrictionConfig(accountProvider?: string) {
  return MARKETPLACE_RESTRICTION_CONFIGS[accountProvider as SupportedMarketplaceAccountProvider]
}

export function getMarketplaceRestrictionStorageKey(orgId: string, accountProvider: string) {
  return `nextgen:create-resource-marketplace-restriction-dismissed:${orgId}:${accountProvider}`
}

function useMarketplaceRestrictionDetails() {
  const {
    store: {
      tenantData: { id: orgId, third_party_account_provider: accountProvider }
    }
  } = useStores()
  const config = getMarketplaceRestrictionConfig(accountProvider)
  return { orgId, accountProvider, config }
}

function useMarketplaceRestriction() {
  const { orgId, accountProvider, config } = useMarketplaceRestrictionDetails()
  const storageKey = getMarketplaceRestrictionStorageKey(orgId || 'unknown', accountProvider || 'unknown')
  const [dismissed, setDismissed] = useLocalStorage<boolean | undefined>({
    key: storageKey,
    defaultValue: undefined,
    getInitialValueInEffect: false
  })

  return {
    config,
    alertVisible: !!config && dismissed !== true,
    dismissAlert: () => setDismissed(true)
  }
}

interface MarketplaceRestrictionAlertProps {
  mt?: number | string
}

export function MarketplaceRestrictionAlert({ mt }: MarketplaceRestrictionAlertProps = {}) {
  const { config, alertVisible, dismissAlert } = useMarketplaceRestriction()

  if (!config || !alertVisible) {
    return null
  }

  const handleDismiss = () => {
    eventTracking(MixpanelEvents.TidbResource.Create.ButtonClicked, {
      action: 'dismissMarketplaceRestriction'
    })
    dismissAlert()
  }

  return (
    <Alert
      color="peacock"
      icon={<IconInfoCircle />}
      withCloseButton
      closeButtonLabel="Dismiss marketplace restriction notice"
      onClose={handleDismiss}
      mt={mt}
      data-testid="marketplace-restriction-alert"
      data-marketplace-provider={config.accountProvider}
    >
      <Typography variant="body-lg" c="peacock.9">
        This organization is integrated with the <strong>{config.marketplaceName}</strong> subscription, resource
        creation is restricted exclusively to the associated cloud provider.{' '}
        {config.dedicatedOnly && (
          <>For now, Google Cloud is only available on Dedicated plan and is unsupported on other plans. </>
        )}
        If you want to deploy resources with a different cloud provider, please{' '}
        <Anchor href="/signup" target="_blank" rel="noopener noreferrer">
          sign up
        </Anchor>{' '}
        for a new account and establish a separate organization.
      </Typography>
    </Alert>
  )
}

interface MarketplaceRestrictionHoverCardProps extends React.PropsWithChildren {
  availableProviderCount: number
  width: number
}

export function MarketplaceRestrictionHoverCard({
  availableProviderCount,
  width,
  children
}: MarketplaceRestrictionHoverCardProps) {
  const { config } = useMarketplaceRestrictionDetails()
  const hoverCardEnabled = !!config && availableProviderCount <= 1

  return (
    <HoverCard disabled={!hoverCardEnabled} position="bottom" withinPortal shadow="md">
      <HoverCard.Target>
        <Box
          w={width}
          sx={{ flexShrink: 1 }}
          data-testid="marketplace-restriction-hover-card-target"
          data-marketplace-provider={config?.accountProvider}
        >
          {children}
        </Box>
      </HoverCard.Target>
      <HoverCard.Dropdown maw={560}>
        <Typography variant="body-lg" c="carbon.7">
          Cloud provider options are restricted due to Marketplace binding.
        </Typography>
      </HoverCard.Dropdown>
    </HoverCard>
  )
}
