import { Button, Flex, Modal, notifier, Typography } from '@tidbcloud/uikit'
import { observer } from 'mobx-react'
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 { Dedicatedv1beta1AuditLogConfig } from 'dbaas/services/api-clients/v2023/dedicated/v1beta1/interface'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import useStores from 'dbaas/stores/useStores'

interface AuditLogDisableModalProps {
  opened: boolean
  cluster: SharedCluster
  orgId: string
  projectId: string
  config?: Dedicatedv1beta1AuditLogConfig | undefined
  onClose: () => void
}

const AuditLogEditModal = observer(({ opened, cluster, orgId, projectId, onClose }: AuditLogDisableModalProps) => {
  const {
    store: { tenantData, activeProjectId }
  } = useStores()

  const configUpdater = useDatabaseAuditLogServiceUpdateAuditLogConfig()
  const queryClient = useQueryClient()

  const disableHandler = async () => {
    try {
      await configUpdater.mutateAsync({
        clusterId: cluster.id,
        data: {
          enabled: false
        },
        params: {
          orgId: tenantData.id,
          projectId: activeProjectId
        }
      })
    } catch (e) {
      notifier.error(getErrorMessage(e, true))
    }
    queryClient.fetchQuery(
      getDatabaseAuditLogServiceGetAuditLogConfigQueryKey(cluster?.id ?? '', { orgId, projectId }),
      () => databaseAuditLogServiceGetAuditLogConfig(cluster?.id ?? '', { orgId, projectId })
    )
    onClose()
  }

  return (
    <Modal
      opened={opened}
      centered
      title="Disable Database Audit Logging"
      size={480}
      trapFocus={false}
      onClose={onClose}
    >
      <Typography mb={32} variant="body-lg">
        When disabled, the database will no longer generate audit log files.
      </Typography>

      <Flex justify="flex-end" gap={16}>
        <Button variant="outline" data-mp-event="Disable DB Audit Logging Cancel Button Clicked" onClick={onClose}>
          Cancel
        </Button>
        <Button
          variant="outline"
          color="red"
          loading={configUpdater.isLoading}
          data-mp-event="Disable DB Audit Logging Confirm Button Clicked"
          data-mp-plan="Dedicated"
          onClick={disableHandler}
        >
          Disable
        </Button>
      </Flex>
    </Modal>
  )
})

export default AuditLogEditModal
