import { Alert, Box, Flex, Group, SegmentedControlItem, Stack, Tooltip, Typography } from '@tidbcloud/uikit'
import { FormSwitch } from '@tidbcloud/uikit/biz'
import { IconLinkExternal01 } from '@tidbcloud/uikit/icons'
import { useEffect } from 'react'
import { useFormContext } from 'react-hook-form'

import buildConfig from 'config'
import { Serverlessv1beta1ClusterHighAvailabilityType } from 'dbaas/services/api-clients/v2023/serverless/v1beta1/interface'
import useStores from 'dbaas/stores/useStores'
import { isHARegionalEnabled } from 'dbaas/utils/feature-flags'

import { FormSegmentedControl } from '../../components/FormSegmentedControl'
import { CreationFormValueState } from '../../helpers'

interface AdvancedSettingsProps {
  names: {
    encrypted: string
    ha: string
  }
  encryptedOptions?: {
    disabled?: boolean
    tooltip?: string
  }
  haOptions?: {
    disabled?: boolean
  }
}

export const HADescriptions = {
  [Serverlessv1beta1ClusterHighAvailabilityType.ZONAL]: 'Zonal',
  [Serverlessv1beta1ClusterHighAvailabilityType.REGIONAL]: 'Regional'
} as const

export const AdvancedSettings = ({
  names,
  encryptedOptions,
  haOptions = { disabled: false }
}: AdvancedSettingsProps) => {
  const { watch, setValue } = useFormContext<CreationFormValueState>()
  const spendingLimit = watch('serverless.monthlySpendingLimit')
  const encrypted = watch('serverless.encrypted')
  const highAvailabilityType = watch('serverless.highAvailabilityType')
  const region = watch('serverless.region')

  const encryptionEnabled = (spendingLimit ?? 0) > 0
  const haEnabled = (spendingLimit ?? 0) > 0 && !haOptions.disabled

  useEffect(() => {
    if (encrypted && !spendingLimit) {
      setValue('serverless.encrypted', false)
    }
  }, [encrypted, spendingLimit, setValue])

  const {
    store: {
      tenantData: { id: orgId }
    }
  } = useStores()

  const haRegionalEnabled = isHARegionalEnabled(region) || buildConfig.HA_REGIONAL_ORG_IDS?.split(',')?.includes(orgId)

  useEffect(() => {
    if (haEnabled) {
      if (!haRegionalEnabled || highAvailabilityType === undefined) {
        setValue('serverless.highAvailabilityType', Serverlessv1beta1ClusterHighAvailabilityType.ZONAL)
      }
    } else {
      setValue('serverless.highAvailabilityType', undefined)
    }
  }, [haRegionalEnabled, setValue, haEnabled, highAvailabilityType])

  const HAOptions: SegmentedControlItem[] = [
    {
      label: HADescriptions[Serverlessv1beta1ClusterHighAvailabilityType.ZONAL],
      value: Serverlessv1beta1ClusterHighAvailabilityType.ZONAL
    },
    {
      label: HADescriptions[Serverlessv1beta1ClusterHighAvailabilityType.REGIONAL],
      value: Serverlessv1beta1ClusterHighAvailabilityType.REGIONAL
    }
  ]

  return (
    <>
      <Stack justify="flex-start" gap="xl">
        <Group justify="space-between" wrap="nowrap">
          <Box>
            <Typography variant="label-lg" fw={600}>
              Dual-Layer Data Encryption
            </Typography>
            <Typography variant="body-lg" c="carbon.7">
              Add a second layer of encryption on top of the default encryption at rest with an isolated service-managed
              key.
            </Typography>
          </Box>
          <Tooltip
            withinPortal
            label={encryptedOptions?.tooltip}
            disabled={!encryptedOptions?.disabled || !encryptedOptions?.tooltip}
          >
            <div>
              <FormSwitch name={names.encrypted} disabled={!encryptionEnabled || encryptedOptions?.disabled} />
            </div>
          </Tooltip>
        </Group>
        {encrypted && (
          <Alert>
            This feature will charge fee according to your usage, please note the resource cost changes above. It cannot
            be canceled after creating.
          </Alert>
        )}
        {haEnabled && haRegionalEnabled && (
          <Group justify="space-between" wrap="nowrap" align="flex-start">
            <Box>
              <Flex align="center">
                <Typography variant="label-lg" fw={600}>
                  High Availability
                </Typography>
                <Box
                  ml="xs"
                  component="a"
                  target="_blank"
                  rel="noreferrer"
                  href="https://docs.pingcap.com/tidbcloud/serverless-high-availability"
                  fw={400}
                  sx={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}
                >
                  Learn more <IconLinkExternal01 size={14} />
                </Box>
              </Flex>
              <Typography variant="body-lg" c="carbon.7" maw={480}>
                {highAvailabilityType === 'REGIONAL'
                  ? 'Ensures redundancy across multiple availability zones with increased fault tolerance. Potential data transfer costs between zones may increase. Recommended for critical workloads.'
                  : 'High availability within a single availability zone with minimal latency'}
              </Typography>
            </Box>
            <FormSegmentedControl name={names.ha} data={HAOptions} />
          </Group>
        )}
      </Stack>
    </>
  )
}
