import { useAuthIdentity } from '@inject/graphql/auth'
import { useNotifyContext } from '@inject/shared/notification/contexts/NotifyContext'
import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'

/**
 * Removes HTML tags from the given content and returns the plain text.
 * @param content - The content containing HTML tags.
 * @returns The plain text without HTML tags.
 */
export const textFromRenderedContent = (content: string) =>
  content.replace(/<[^>]+>/g, '')

export const useSetPageTitle = (title: string) => {
  useEffect(() => {
    document.title = `INJECT${title ? `- ${title}` : ''}`
  }, [title])
}

export const NOTIFICATION_SELECTION_ID = '-2'
export const CUSTOM_INJECT_SELECTION_ID = '-1'

export const useStaffBoundary = () => {
  const { isStaff, loading } = useAuthIdentity()
  const nav = useNavigate()
  const { notify } = useNotifyContext()

  useEffect(() => {
    if (!isStaff && !loading) {
      notify('You are not authorized to access this page', { intent: 'danger' })
      nav('/')
    }
  }, [loading])
}

export const useSuperuserBoundary = () => {
  const { isSuperuser, loading } = useAuthIdentity()
  const nav = useNavigate()
  const { notify } = useNotifyContext()

  useEffect(() => {
    if (!isSuperuser && !loading) {
      notify('You are not authorized to access this page', { intent: 'danger' })
      nav('/')
    }
  }, [loading])
}

export const useActiveBoundary = () => {
  const { isActive, loading } = useAuthIdentity()
  const nav = useNavigate()
  const { notify } = useNotifyContext()

  useEffect(() => {
    if (!isActive && !loading) {
      notify('Your account is not active', { intent: 'danger' })
      nav('/')
    }
  }, [loading])
}
