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

const useRegenerateCredentials = ({ userIds }: { userIds: string[] }) => {
  const [alertOpen, setAlertOpen] = useState(false)
  const { id, isSuperuser } = useAuthIdentity()
  const [{ fetching: loading }, mutate] = useTypedMutation(
    RegenerateCredentials
  )

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

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

  return {
    button: isSuperuser && (
      <Button
        disabled={disabled}
        title={title}
        icon='key'
        intent='warning'
        active={alertOpen}
        onClick={() => {
          setAlertOpen(prev => !prev)
        }}
      >
        {`Reset credentials${userIds.length > 1 ? ` for selected` : ''}`}
      </Button>
    ),
    alert: isSuperuser && (
      <Alert
        loading={loading}
        isOpen={alertOpen}
        canEscapeKeyCancel
        canOutsideClickCancel
        cancelButtonText='Cancel'
        onCancel={() => setAlertOpen(false)}
        confirmButtonText='Reset'
        icon='key'
        intent='warning'
        onConfirm={() => {
          mutate({
            userIds,
          }).catch(error => notify(error.message, { intent: 'danger' }))
        }}
        onClose={() => setAlertOpen(false)}
      >
        <p>
          {`Are you sure you want to reset credentials for the selected user${
            userIds.length > 1
              ? `s (${
                  userIds.includes(id || '')
                    ? userIds.length - 1
                    : userIds.length
                } in total)`
              : ''
          }?`}
        </p>
        <p>
          {`New credentials will be sent to the email address${
            userIds.length > 1 ? 'es' : ''
          } of the selected user${userIds.length > 1 ? 's' : ''}.`}
        </p>
        {userIds.includes(id || '') && (
          <p>
            <b>
              You are changing the credentials of the current user &mdash;
              you&apos;ll need to log in with the new credentials.
            </b>
          </p>
        )}
      </Alert>
    ),
  }
}

export default useRegenerateCredentials
