import { Alert, Button, Divider, Group, notifier, Stack, Typography } from '@tidbcloud/uikit'
import { FormTextInput } from '@tidbcloud/uikit/biz'
import { IconAlertCircle } from '@tidbcloud/uikit/icons'
import { observer } from 'mobx-react'
import { FormProvider, useForm } from 'react-hook-form'

import { useOrgProjectClusterIds } from 'dbaas/features/Common'
import { useSharedTiDBContext } from 'dbaas/screens/NextGen/tidb-mgmt-container/shared/tidb-context'
import { useTidbServiceCreateTidbBackup } from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import { backupNameRegEx } from 'dbaas/utils/regex'

const _ManualBackupPremium = ({
  closeModal,
  onSuccess
}: {
  closeModal: () => void
  onSuccess?: () => void | Promise<void>
}) => {
  const { orgId, projectId } = useOrgProjectClusterIds()
  const tidb = useSharedTiDBContext()
  const methods = useForm<{ name: string }>({
    defaultValues: {
      name: ''
    }
  })
  const { handleSubmit } = methods
  const createBackup = useTidbServiceCreateTidbBackup()
  const dualLayerDataEncryption = tidb.dualLayerDataEncryption
  const isCmek = !!dualLayerDataEncryption?.cmek
  const isDualLayerEncryptionEnabled = !dualLayerDataEncryption?.noEncryption
  const handleClose = () => {
    closeModal()
  }

  const onSubmit = async (data: { name: string }) => {
    await createBackup.mutateAsync({
      tidbId: tidb.tidbId!,
      params: {
        orgId,
        projectId
      },
      data: {
        name: data.name
      }
    })
    notifier.success('Backup created successfully')
    handleClose()
    await onSuccess?.()
  }

  return (
    <FormProvider {...methods}>
      <form onSubmit={handleSubmit(onSubmit)}>
        <Stack>
          <FormTextInput
            inputWrapperOrder={['label', 'input', 'error', 'description']}
            rules={{
              required: 'Required',
              pattern: {
                value: backupNameRegEx,
                message: 'Invalid name'
              }
            }}
            name="name"
            placeholder="backup name"
            label="Backup Name"
            description="4~48 characters that can only include numbers, lowercase or uppercase letters, and hyphens. The first and last
        character must be a letter or number."
          />

          <Alert title="About Manual Backup" icon={<IconAlertCircle />}>
            <Stack gap={4}>
              {isCmek ? (
                <>
                  <Typography component="div">
                    • This manual backup will use the instance's Customer-Managed Encryption Key (CMEK). Restoring this
                    manual backup requires the same CMEK.
                  </Typography>
                  <Typography component="div">
                    • This manual backup will be retained indefinitely until you delete it manually or your account is
                    closed.
                  </Typography>
                </>
              ) : isDualLayerEncryptionEnabled ? (
                <>
                  <Typography component="div">
                    • This manual backup will use the instance's service-managed dual-layer encryption.
                  </Typography>
                  <Typography component="div">
                    • This manual backup will be retained indefinitely until you delete it manually or your account is
                    closed.
                  </Typography>
                </>
              ) : (
                <Typography component="div">
                  This manual backup will be retained indefinitely until you delete it manually or your account is
                  closed.
                </Typography>
              )}
            </Stack>
          </Alert>

          <Divider mx={-24} />

          {createBackup.error && (
            <Alert icon={<IconAlertCircle />} color="red">
              {getErrorMessage(createBackup.error)}
            </Alert>
          )}

          <Group justify="flex-end">
            <Button
              variant="default"
              type="button"
              data-mp-event="Manual Backup Cancel Button Clicked"
              onClick={handleClose}
            >
              Cancel
            </Button>
            <Button type="submit" loading={createBackup.isLoading} data-mp-event="Manual Backup Confirm Button Clicked">
              Confirm
            </Button>
          </Group>
        </Stack>
      </form>
    </FormProvider>
  )
}

export const ManualBackupPremium = observer(_ManualBackupPremium)
