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

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

  if (!isSuperuser) {
    return null
  }

  return (
    <>
      <Button
        disabled={disabled}
        title={title}
        icon='key'
        intent='warning'
        active={alertOpen}
        onClick={() => {
          setAlertOpen(prev => !prev)
        }}
      >
        {`Reset credentials${userIds.length > 1 ? ` for selected` : ''}`}
      </Button>
      <Alert
        loading={loading}
        isOpen={alertOpen}
        canEscapeKeyCancel
        canOutsideClickCancel
        cancelButtonText='Cancel'
        onCancel={() => setAlertOpen(false)}
        confirmButtonText='Reset'
        icon='key'
        intent='warning'
        onConfirm={() => {
          mutate({
            userIds,
          })
        }}
        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 ResetCredentials
