import { Alert, Box, Button, Divider, Flex, notifier, Typography } from '@tidbcloud/uikit'
import { FormSelect, FormSwitch } from '@tidbcloud/uikit/biz'
import { IconAlertTriangle, IconCheckCircle } from '@tidbcloud/uikit/icons'
import { useFormContext } from 'react-hook-form'
import { useQueryClient } from 'react-query'

import { SharedCluster } from 'dbaas/features/ClusterManagement/cluster'
import {
  databaseAuditLogServiceGetAuditLogConfig,
  getDatabaseAuditLogServiceGetAuditLogConfigQueryKey,
  useDatabaseAuditLogServiceUpdateAuditLogConfig
} from 'dbaas/services/api-clients/v2023/dedicated/v1beta1'
import { AuditLogConfigBucketManager } from 'dbaas/services/api-clients/v2023/dedicated/v1beta1/interface'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import useStores from 'dbaas/stores/useStores'

import { useDedicatedDBAuditLogContext } from '../../context/dedicated-context'

import {
  isClusterInDbLogBugVersion,
  maxAgeDefaultOptions,
  maxAgeDefaultWhiteListOptions,
  maxAgeDisabledOptions,
  maxSizeDefaultOptions
  // LOG_FORMATS
} from './helper'

interface LogSettingsProps {
  isUpdate?: boolean
  clusterId?: string
  cluster?: SharedCluster
  orgId: string
  projectId: string
  bucketManager?: AuditLogConfigBucketManager
  onCancel: () => void
  onPrevious?: () => void
}

export const LogSettings = ({
  isUpdate,
  clusterId,
  cluster,
  orgId,
  projectId,
  bucketManager,
  onCancel,
  onPrevious
}: LogSettingsProps) => {
  const {
    store: { config: whiteListConfig }
  } = useStores()
  const { getValues, watch } = useFormContext()
  const configUpdate = useDatabaseAuditLogServiceUpdateAuditLogConfig()
  const queryClient = useQueryClient()
  const redacted = watch('redacted')
  const { filterRulesLen } = useDedicatedDBAuditLogContext()

  const enableHandler = async () => {
    const values = getValues()
    try {
      await configUpdate.mutateAsync({
        clusterId: clusterId ?? '',
        data: {
          awsRoleArn: values.awsRoleArn,
          azureSasToken: values.azureSasToken,
          bucketRegionId: values.bucketRegionId,
          bucketUri: values.bucketUri,
          enabled: true,
          // format: values.format,
          rotationPolicy: values.rotationPolicy,
          unredacted: !values.redacted,
          bucketManager: bucketManager || values.bucketManager
        },
        params: {
          projectId,
          orgId
        }
      })

      if (!filterRulesLen) {
        notifier.success(
          'Database audit logging is enabled. Please proceed to set audit filters to select the events to be audited.'
        )
      }

      queryClient.fetchQuery(
        getDatabaseAuditLogServiceGetAuditLogConfigQueryKey(clusterId ?? '', { orgId, projectId }),
        () => databaseAuditLogServiceGetAuditLogConfig(clusterId ?? '', { orgId, projectId })
      )

      onCancel()
    } catch (e) {
      notifier.error(getErrorMessage(e, true))
    }
  }

  const formSelectBaseStyles = (theme) => ({
    root: {
      flex: 1
    },
    section: {
      '&[data-position="left"]': {
        color: theme.colors.carbon[9],
        borderRight: `1px solid ${theme.colors.carbon[4]}`,
        backgroundColor: theme.colors.carbon[2],
        marginRight: 10
      }
    },
    input: {
      flex: 1
    }
  })

  const maxAgeSeconds = [
    ...maxAgeDisabledOptions,
    ...(whiteListConfig.enableAuditLogRotation ? maxAgeDefaultWhiteListOptions : []),
    ...maxAgeDefaultOptions
  ]

  return (
    <Box>
      {!isUpdate && (
        <Alert color="green" mb={24} icon={<IconCheckCircle />}>
          The connection is successful
        </Alert>
      )}

      <Typography variant="label-lg" mb={8}>
        Log File Rotation
      </Typography>
      <Flex gap={16}>
        <FormSelect
          name="rotationPolicy.maxSizeMib"
          leftSectionWidth={112}
          leftSection="File Size Limit"
          styles={(theme) => ({
            ...formSelectBaseStyles(theme),
            input: {
              paddingLeft: 126
            }
          })}
          sx={{ maxWidth: '50%' }}
          data={maxSizeDefaultOptions}
        />

        {cluster && !isClusterInDbLogBugVersion(cluster) && (
          <FormSelect
            name="rotationPolicy.maxAgeSecond"
            leftSectionWidth={132}
            leftSection="Rotation Interval"
            data={maxAgeSeconds}
            styles={(theme) => ({
              ...formSelectBaseStyles(theme),
              input: {
                paddingLeft: 146
              }
            })}
          />
        )}
      </Flex>
      <Divider mx={-24} my={24} />

      <Flex justify="space-between" align="center" gap={32}>
        <Box>
          <Typography variant="label-lg">Log Redaction</Typography>
          <Typography variant="body-lg" mt={4}>
            Sensitive information contained in SQL text in the cluster log will be replaced by "?".
          </Typography>
          {!redacted && (
            <Alert color="yellow" icon={<IconAlertTriangle size={16} />} mt={8}>
              Database audit log redaction is currently disabled, resulting in log files pushed to the user's cloud
              storage service containing sensitive information. This configuration is not recommended due to potential
              security risks.
            </Alert>
          )}
        </Box>

        <FormSwitch name="redacted" />
      </Flex>
      <Divider mx={-24} my={24} />

      <Flex gap={16} justify="flex-end">
        <Button variant="default" onClick={onCancel}>
          Cancel
        </Button>

        {!isUpdate && (
          <Button variant="default" onClick={() => onPrevious?.()}>
            Previous
          </Button>
        )}

        <Button type="submit" loading={configUpdate.isLoading} onClick={enableHandler}>
          Save {isUpdate ? '' : 'and Enable'}
        </Button>
      </Flex>
    </Box>
  )
}
