import { ActionIcon, Alert, Box, Collapse, Group, Stack, Typography } from '@tidbcloud/uikit'
import { FormSelect, FormSwitch } from '@tidbcloud/uikit/biz'
import { IconChevronDown, IconChevronUp, IconLinkExternal01 } from '@tidbcloud/uikit/icons'
import { useEffect, useMemo, useRef, useState } from 'react'
import { useFormContext } from 'react-hook-form'

import { CloudProviderConst } from 'dbaas/features/Project'
import { Serverlessv1beta1ClusterHighAvailabilityType } from 'dbaas/services/api-clients/v2023/serverless/v1beta1/interface'
import { isHARegionalEnabledForOrg } from 'dbaas/utils/feature-flags'

import { StarterFormValue } from '../types'

interface AdvancedSettingsSectionProps {
  orgId: string
  disabled?: boolean
}

export function AdvancedSettingsSection({ orgId, disabled }: AdvancedSettingsSectionProps) {
  const { watch, getValues, setValue } = useFormContext<StarterFormValue>()

  const provider = watch('provider')
  const region = watch('region')
  const spendingLimit = watch('spendingLimit')
  const encrypted = watch('encrypted')
  const highAvailabilityType = watch('highAvailabilityType')

  const spendingLimitValue = Number(spendingLimit ?? 0)

  const encryptionEnabled = spendingLimitValue > 0
  const haEnabled = spendingLimitValue > 0 && provider === CloudProviderConst.AWS
  const haRegionalEnabled = isHARegionalEnabledForOrg(region, orgId)

  useEffect(() => {
    if (encrypted && spendingLimitValue <= 0) {
      setValue('encrypted', false)
    }
  }, [encrypted, spendingLimitValue, setValue])

  useEffect(() => {
    if (haEnabled && haRegionalEnabled) {
      if (highAvailabilityType === undefined) {
        setValue('highAvailabilityType', Serverlessv1beta1ClusterHighAvailabilityType.ZONAL)
      }
      return
    }

    setValue('highAvailabilityType', undefined)
  }, [haEnabled, haRegionalEnabled, highAvailabilityType, setValue])

  const [opened, setOpened] = useState<boolean>(Number(getValues('spendingLimit') ?? 0) > 0)
  const prevSpendingLimitRef = useRef<number>(Number(getValues('spendingLimit') ?? 0))

  useEffect(() => {
    const prevSpendingLimitValue = prevSpendingLimitRef.current

    if (spendingLimitValue <= 0 && prevSpendingLimitValue > 0) {
      setOpened(false)
    }

    prevSpendingLimitRef.current = spendingLimitValue
  }, [spendingLimitValue])

  const haOptions = useMemo(
    () => [
      { value: Serverlessv1beta1ClusterHighAvailabilityType.ZONAL, label: 'Zonal' },
      { value: Serverlessv1beta1ClusterHighAvailabilityType.REGIONAL, label: 'Regional' }
    ],
    []
  )

  return (
    <Box p="xl">
      <Group justify="space-between" align="flex-start" wrap="nowrap">
        <Stack gap={4}>
          <Typography variant="title-lg">Advanced Settings</Typography>
          <Typography variant="body-lg" c="carbon.7">
            Advanced settings are only available for TiDB Cloud Starter instances with a monthly spending limit.
          </Typography>
        </Stack>
        <ActionIcon
          variant="subtle"
          size="md"
          disabled={disabled}
          onClick={() => {
            setOpened((prev) => !prev)
          }}
          data-mp-no-event
        >
          {opened ? <IconChevronUp size={16} /> : <IconChevronDown size={16} />}
        </ActionIcon>
      </Group>

      <Collapse in={opened}>
        <Stack justify="flex-start" mt="md">
          <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>
            <FormSwitch name="encrypted" disabled={disabled || !encryptionEnabled} />
          </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>
                <Group gap={8} align="center" wrap="nowrap">
                  <Typography variant="label-lg" fw={600}>
                    High Availability
                  </Typography>
                  <Box
                    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, whiteSpace: 'nowrap' }}
                  >
                    Learn more <IconLinkExternal01 size={14} />
                  </Box>
                </Group>
                <Typography variant="body-lg" c="carbon.7" maw={480}>
                  {highAvailabilityType === Serverlessv1beta1ClusterHighAvailabilityType.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>
              <FormSelect name="highAvailabilityType" data={haOptions} disabled={disabled} />
            </Group>
          )}
        </Stack>
      </Collapse>
    </Box>
  )
}
