import { notifier } from '@tidbcloud/uikit'
import { Button, Group, Modal, Typography } from '@tidbcloud/uikit'
import { useMemoizedFn } from 'ahooks'

import { ModalCodeTitle } from 'dbaas/components'
import { useDeleteOpenAPIKey, useDeleteProjectOpenAPIKey } from 'dbaas/services/account'
import { getErrorMessage } from 'dbaas/services/errorCodes'

import { ScopeTypeConst, ScopeTypes } from '../../UserAccess/helpers'
import { APIKeyItem } from '../helpers'

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

export const DeletionConfirm: React.FC<React.PropsWithChildren<DeletionConfirmProps>> = ({
  onConfirm,
  data,
  visible,
  onClose,
  type
}) => {
  const { mutateAsync: deleteOrgAPIKey, isLoading: deleting } = useDeleteOpenAPIKey({
    mutation: {
      onError: (error) => {
        notifier.error(getErrorMessage(error))
      }
    }
  })
  const { mutateAsync: deleteProjectAPIKey, isLoading: deletingProjectAPIKey } = useDeleteProjectOpenAPIKey({
    mutation: {
      onError: (error) => {
        notifier.error(getErrorMessage(error))
      }
    }
  })
  const onDelete = useMemoizedFn(async () => {
    if (type === ScopeTypeConst.Org) {
      await deleteOrgAPIKey({
        orgId: data.org_id,
        apiKeyId: data.id
      })
    } else {
      await deleteProjectAPIKey({
        orgId: data.org_id,
        projectId: data.project_id,
        apiKeyId: data.id
      })
    }
    onConfirm?.()
    onClose()
  })

  return (
    <Modal
      title={
        <>
          Delete API Key <ModalCodeTitle>{data.public_key}</ModalCodeTitle>
        </>
      }
      centered
      size="lg"
      opened={visible}
      onClose={onClose}
    >
      <Typography variant="body-lg" mb={24}>
        Deleting an 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. Are you sure you want to delete it?
      </Typography>
      <Group justify="flex-end">
        <Button variant="default" onClick={onClose} data-mp-event="Delete API Key Cancel Button Clicked">
          Cancel
        </Button>
        <Button
          color="red"
          variant="light"
          loading={deleting || deletingProjectAPIKey}
          onClick={onDelete}
          data-mp-event="Delete API Key Consequence Button Clicked"
        >
          I understand, delete it.
        </Button>
      </Group>
    </Modal>
  )
}
