import { Alert, Button } from '@blueprintjs/core'
import useAuthIdentity from '@inject/graphql/auth'
import useApolloClient from '@inject/graphql/client/useApolloClient'
import { useDeleteUsers as useDeleteUsersMutation } from '@inject/graphql/mutations/DeleteUsers.generated'
import { GetUsersDocument } from '@inject/graphql/queries/GetUsers.generated'
import { useNotifyContext } from '@inject/shared/notification/contexts/NotifyContext'
import { useMemo, useState } from 'react'

const useDeleteUsers = ({
  userIds,
  showCount,
  onConfirm,
}: {
  userIds: string[]
  showCount?: boolean
  onConfirm?: () => void
}) => {
  const apollo = useApolloClient()
  const [alertOpen, setAlertOpen] = useState(false)
  const { id, isSuperuser } = useAuthIdentity()
  const { notify } = useNotifyContext()
  const [mutate, { loading }] = useDeleteUsersMutation({
    variables: { userIds },
    onError: error => {
      notify(error.message, { intent: 'danger' })
    },
  })

  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({
          onCompleted: () => {
            apollo.refetchQueries({ include: [GetUsersDocument] })
            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>
  )

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

export default useDeleteUsers
