import { Box, Modal } from '@tidbcloud/uikit'
import { Form, FormSelect } from '@tidbcloud/uikit/biz'
import { observer } from 'mobx-react'
import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { useQueryClient } from 'react-query'

import {
  databaseAuditLogServiceGetAuditLogConfig,
  getDatabaseAuditLogServiceGetAuditLogConfigQueryKey
} from 'dbaas/services/db-audit-log/serverless'
import { CloudStorageTypeEnum, S3CloudStorageS3AuthType } from 'dbaas/services/db-audit-log/serverless/interface'
import useStores from 'dbaas/stores/useStores'

import { useEssentialDBAuditLogContext } from '../../context/starter-context'

import { AliCloudFormContent } from './AliCloudFormContent'
import { AwsFormContent } from './AwsFormContent'
import { AzureFormContent } from './AzureFormContent'
import { GcpFormContent } from './GCSFormContent'
import TiDBCloudContent from './TiDBCloudContent'

interface AuditLogEnableModalProps {
  opened: boolean
  clusterId?: string
  onClose: () => void
  onSucc?: () => void
}

const AuditLogEditModal = observer(({ opened, clusterId, onClose, onSucc }: AuditLogEnableModalProps) => {
  const { config } = useEssentialDBAuditLogContext()
  const [curConfig, setCurConfig] = useState(config)
  const defaultStorageType = CloudStorageTypeEnum.S3
  const {
    store: { tenantData, activeProjectId }
  } = useStores()
  const form = useForm({
    mode: 'onChange'
  })
  const queryClient = useQueryClient()

  const { watch } = form
  const storageType = watch('storage_type')

  useEffect(() => {
    let cur = { ...config }
    if (!cur.enabled) {
      if (!cur.cloud_storage) {
        cur.cloud_storage = {
          type: defaultStorageType
        }
      } else {
        cur.cloud_storage.type = defaultStorageType
      }
    }
    setCurConfig(cur)
  }, [config])

  useEffect(() => {
    if (opened) {
      form.setValue('storage_type', curConfig?.cloud_storage?.type ?? defaultStorageType)
      if (!curConfig?.enabled) {
        form.setValue('s3.auth_type', S3CloudStorageS3AuthType.ROLE_ARN)
      }
    }
  }, [opened])

  const succHandler = () => {
    refetConfigInfo()
    onSucc?.()
  }

  const refetConfigInfo = () => {
    queryClient.fetchQuery(
      getDatabaseAuditLogServiceGetAuditLogConfigQueryKey(tenantData.id, activeProjectId, clusterId ?? ''),
      () => databaseAuditLogServiceGetAuditLogConfig(tenantData.id, activeProjectId, clusterId ?? '')
    )
  }

  return (
    <>
      <Modal
        title={config ? 'Database Audit Log Storage Configuration' : 'Enable Database Audit Logging'}
        opened={opened}
        onClose={onClose}
        size={800}
        centered
        trapFocus={false}
        closeOnClickOutside={false}
      >
        <Form layout="none" form={form} withActions={false} onSubmit={() => {}} onCancel={onClose}>
          <FormSelect
            name="storage_type"
            label="Log Storage Location"
            data={[
              {
                label: 'AWS S3',
                value: CloudStorageTypeEnum.S3
              },
              {
                label: 'Azure Blob Storage',
                value: CloudStorageTypeEnum.AZURE_BLOB
              },
              {
                label: 'Google Cloud Storage',
                value: CloudStorageTypeEnum.GCS
              },
              {
                label: 'Alibaba Cloud OSS',
                value: CloudStorageTypeEnum.OSS
              },
              {
                label: 'TiDB Cloud',
                value: CloudStorageTypeEnum.TIDB_CLOUD
              }
            ]}
          />

          <Box mt="lg">
            {storageType === CloudStorageTypeEnum.S3 && (
              <AwsFormContent clusterId={clusterId} onSucc={succHandler} onCancel={onClose} />
            )}
            {storageType === CloudStorageTypeEnum.AZURE_BLOB && (
              <AzureFormContent clusterId={clusterId} onSucc={succHandler} onCancel={onClose} />
            )}
            {storageType === CloudStorageTypeEnum.GCS && (
              <GcpFormContent clusterId={clusterId} onCancel={onClose} onSucc={succHandler} />
            )}
            {storageType === CloudStorageTypeEnum.OSS && (
              <AliCloudFormContent clusterId={clusterId} onCancel={onClose} onSucc={succHandler} />
            )}
            {storageType === CloudStorageTypeEnum.TIDB_CLOUD && (
              <TiDBCloudContent clusterId={clusterId} onCancel={onClose} onSucc={succHandler} />
            )}
          </Box>
        </Form>
      </Modal>
    </>
  )
})

export default AuditLogEditModal
