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

import { FormItem } from '../components/FormItem'

import { type StarterFormValue } from './index'

export const AdvancedSettings = () => {
  const { watch, setValue } = useFormContext<StarterFormValue>()
  const spendingLimit = watch('spendingLimit')
  const encrypted = watch('encrypted')

  const encryptionEnabled = (spendingLimit ?? 0) > 0

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

  return (
    <FormItem
      label="Advanced Settings"
      description="Advanced settings can only be used for clusters with a monthly spending limit."
    >
      <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>
          <FormSwitch name="encrypted" 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>
        )}
      </Stack>
    </FormItem>
  )
}
