import { Code, notifier } from '@tidbcloud/uikit'
import { Modal, Typography } from '@tidbcloud/uikit'
import { Form, FormTextInput } from '@tidbcloud/uikit/biz'
import { useMemoizedFn } from 'ahooks'
import { useForm } from 'react-hook-form'

import { useDeleteOpenAPIKey } from 'dbaas/services/account'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import useStores from 'dbaas/stores/useStores'

import { APIKeyItem } from '../shared/helpers'

interface DeletionConfirmProps {
  data: APIKeyItem
  onConfirm?: () => Promise<unknown>
  visible: boolean
  onClose: () => void
}

export const DeletionConfirm: React.FC<React.PropsWithChildren<DeletionConfirmProps>> = ({
  onConfirm,
  data,
  visible,
  onClose
}) => {
  const {
    store: {
      tenantData: { id: orgId }
    }
  } = useStores()
  const { mutateAsync: deleteOrgAPIKey, isLoading: deleting } = useDeleteOpenAPIKey({
    mutation: {
      onError: (error) => {
        notifier.error(getErrorMessage(error))
      }
    }
  })
  const onDelete = useMemoizedFn(async () => {
    await deleteOrgAPIKey({
      orgId: orgId,
      apiKeyId: data.id || ''
    })
    onConfirm?.()
    onClose()
  })

  const form = useForm<{ confirmation: string }>({
    mode: 'onSubmit',
    defaultValues: {
      confirmation: ''
    }
  })
  const { watch } = form
  const confirmation = watch('confirmation')

  return (
    <Modal
      title={
        <>
          Delete API Key <Code fw={600}>{data.public_key}</Code>
        </>
      }
      centered
      size="lg"
      opened={visible}
      onClose={onClose}
    >
      <Typography variant="body-lg">
        Deleting API key will only eliminate the API Key's info and authority, while clusters and services created and
        managed by the API Key will still be running and can be modified by other users and API Keys who have the
        permission.
      </Typography>
      <Typography variant="body-lg" mb={12}>
        Are you sure you want to delete it?
      </Typography>
      <Typography variant="body-lg" mb={6}>
        To confirm, type{' '}
        <Code fz={13} fw={600}>
          {data.public_key}
        </Code>{' '}
        in the box below.
      </Typography>
      <Form
        layout="none"
        form={form}
        onSubmit={onDelete}
        onCancel={onClose}
        actionsProps={{
          confirmText: 'I understand, delete it',
          confirmProps: {
            color: 'red',
            variant: 'light',
            disabled: confirmation !== data.public_key,
            'data-mp-event': 'Delete API Key Consequence Button Clicked'
          },
          cancelProps: {
            disabled: deleting,
            'data-mp-event': 'Delete API Key Cancel Button Clicked'
          }
        }}
      >
        <FormTextInput name="confirmation" autoFocus />
      </Form>
    </Modal>
  )
}

export default DeletionConfirm
