import { Alert, Button } from '@blueprintjs/core'
import useAuthIdentity from '@inject/graphql/auth'
import { useRegenerateCredentials as useRegenerateCredentialsMutation } from '@inject/graphql/mutations/RegenerateCredentials.generated'
import { useNotifyContext } from '@inject/shared/notification/contexts/NotifyContext'
import { useMemo, useState } from 'react'

const useRegenerateCredentials = ({ userIds }: { userIds: string[] }) => {
  const [alertOpen, setAlertOpen] = useState(false)
  const { id, isSuperuser } = useAuthIdentity()
  const { notify } = useNotifyContext()
  const [mutate, { loading }] = useRegenerateCredentialsMutation({
    variables: { userIds },
    onError: error => {
      notify(error.message, { intent: 'danger' })
    },
  })

  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()
        }}
        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
