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 { useMemo, useState } from 'react'

const RemoveUsers = ({
  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]
  )

  if (!isSuperuser) {
    return null
  }

  return (
    <>
      <Button
        disabled={disabled}
        title={title}
        icon='trash'
        intent='danger'
        active={alertOpen}
        onClick={() => setAlertOpen(prev => !prev)}
      >
        {`Delete${showCount ? ` (${userCount})` : ''}`}
      </Button>
      <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) {
              onConfirm?.()
            }
          })
        }}
        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>
    </>
  )
}

export default RemoveUsers
