import { Alert, Button, Group, notifier, Stack } 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 { useQueryClient } from 'react-query'

import { getListBackupsQueryKey, useCreateBackupSchedule } from 'dbaas/services/dataflow'
import { DataflowBackupType } from 'dbaas/services/dataflow/interface'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import useStores from 'dbaas/stores/useStores'
import { backupNameRegEx } from 'dbaas/utils/regex'

const ManualBackup = ({ closeModal }: { closeModal: () => void }) => {
  const {
    store: { tenantData, activeProjectId, currentCluster }
  } = useStores()
  const methods = useForm<{ name: string }>({
    defaultValues: {
      name: ''
    }
  })
  const { handleSubmit } = methods
  const createBackup = useCreateBackupSchedule()
  const handleClose = () => {
    closeModal()
  }

  const queryClient = useQueryClient()

  const onSubmit = async (data: { name: string }) => {
    await createBackup.mutateAsync({
      orgId: tenantData.id,
      projectId: activeProjectId,
      clusterId: currentCluster?.id!,
      data: {
        description: '',
        name: data.name,
        backup_mode: 'FULL',
        backup_time: new Date().toISOString(),
        backup_type: DataflowBackupType.MANUAL
      }
    })
    notifier.success('Backup created successfully')
    handleClose()
    await queryClient.invalidateQueries(
      getListBackupsQueryKey(tenantData.id, activeProjectId, currentCluster?.id!, {
        page: 1,
        per_page: 10
      })
    )
  }

  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 icon={<IconAlertCircle />}>
            This manual backup will be retained indefinitely until you delete it manually or your account is closed.
          </Alert>

          {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 default observer(ManualBackup)
