import { Alert, Button } from '@blueprintjs/core'
import useAuthIdentity from '@inject/graphql/auth'
import { useTypedMutation } from '@inject/graphql/graphql'
import { DeleteUsers } from '@inject/graphql/mutations'
import { notify } from '@inject/shared/notification/engine'
import { useMemo, useState } from 'react'

const useDeleteUsers = ({
  userIds,
  showCount,
  onConfirm,
}: {
  userIds: string[]
  showCount?: boolean
  onConfirm?: () => void
}) => {
  const [alertOpen, setAlertOpen] = useState(false)
  const { id, isSuperuser } = useAuthIdentity()
  const [{ fetching: loading }, mutate] = useTypedMutation(DeleteUsers)

  const { disabled, title } = useMemo(() => {
    if (userIds.length === 0) {
      return { disabled: true, title: 'No users selected' }
    }

    if (userIds.length === 1 && id === userIds[0]) {
      return { disabled: true, title: 'Cannot delete current user' }
    }

    return { disabled: false, title: undefined }
  }, [id, userIds])

  const userCount = useMemo(
    () => (userIds.includes(id || '') ? userIds.length - 1 : userIds.length),
    [id, userIds]
  )

  const SuperUserButton = () => (
    <Button
      disabled={disabled}
      title={title}
      icon='trash'
      intent='danger'
      active={alertOpen}
      onClick={() => setAlertOpen(prev => !prev)}
    >
      {`Delete${showCount ? ` (${userCount})` : ''}`}
    </Button>
  )

  const SuperUserAlert = () => (
    <Alert
      loading={loading}
      isOpen={alertOpen}
      canEscapeKeyCancel
      canOutsideClickCancel
      cancelButtonText='Cancel'
      onCancel={() => setAlertOpen(false)}
      confirmButtonText='Delete'
      icon='trash'
      intent='danger'
      onConfirm={() => {
        mutate({ userIds })
          .then(({ error }) => {
            if (error) {
              notify(error.message, { intent: 'danger' })
            } else {
              onConfirm?.()
            }
          })
          .catch(error => {
            notify(error.message, { intent: 'danger' })
          })
      }}
      onClose={() => setAlertOpen(false)}
    >
      <p>
        {`Are you sure you want to delete the selected user${
          userIds.length > 1 ? `s (${userCount} in total)` : ''
        }? This action is irreversible.`}
      </p>
      {userIds.includes(id || '') && (
        <p>The current user will not be deleted.</p>
      )}
    </Alert>
  )

  return {
    button: isSuperuser ? <SuperUserButton /> : undefined,
    alert: isSuperuser ? <SuperUserAlert /> : undefined,
  }
}

export default useDeleteUsers
