import { notifier } from '@tidbcloud/uikit'
import { Button, Group, Modal, Stack, Typography } from '@tidbcloud/uikit'
import { observer } from 'mobx-react'

import { useDeleteProjectUser, useDeleteUser } from 'dbaas/services/account'
import { CentralUser } from 'dbaas/services/account/interface'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import useStores from 'dbaas/stores/useStores'

import { ScopeTypes } from './helpers'

const deletionDesc = {
  org: 'The user will lose access to this organization. This operation cannot be undone. Are you sure you want to continue?',
  project:
    'The user will lose access to this project. This operation cannot be undone. Are you sure you want to continue?'
}

interface UserDeletionModalProps {
  scopeType: ScopeTypes
  scopeId: string
  user: CentralUser | undefined
  opened: boolean
  onClose: () => void
  onFinish?: () => void
}

export const UserDeletionModal = observer(
  ({ scopeType, scopeId, user, opened = false, onClose, onFinish }: UserDeletionModalProps) => {
    const {
      store: {
        tenantData: { id: orgId }
      }
    } = useStores()

    const orgUserDeletionMutation = useDeleteUser({
      mutation: {
        onError: (err) => {
          notifier.error(getErrorMessage(err))
        }
      }
    })

    const projectUserDeletionMutation = useDeleteProjectUser({
      mutation: {
        onError: (err) => {
          notifier.error(getErrorMessage(err))
        }
      }
    })

    const handleDelete = async () => {
      if (!user) {
        return
      }

      if (scopeType === 'org') {
        await orgUserDeletionMutation.mutateAsync({
          orgId,
          userId: user.id
        })
      } else if (scopeId) {
        await projectUserDeletionMutation.mutateAsync({
          orgId,
          projectId: scopeId,
          userId: user.id
        })
      } else {
        return
      }

      onFinish?.()
      onClose()
    }

    const loading = scopeType === 'org' ? orgUserDeletionMutation.isLoading : projectUserDeletionMutation.isLoading
    const desc = deletionDesc[scopeType]

    return (
      <Modal title={`Delete User ${user?.email ?? ''}`} opened={opened} onClose={onClose} centered size="lg">
        <Stack>
          <Typography variant="body-lg">{desc}</Typography>
          <Group justify="flex-end">
            <Button variant="default" onClick={onClose} data-mp-event="mp-cancel-1691461016462">
              Cancel
            </Button>
            <Button
              color="red"
              variant="light"
              loading={loading}
              disabled={!user}
              onClick={handleDelete}
              data-mp-event="Delete User Consequence Button Clicked"
              data-mp-type={scopeType}
            >
              I understand, delete the user.
            </Button>
          </Group>
        </Stack>
      </Modal>
    )
  }
)
