import { useAuthIdentity } from '@inject/graphql/auth'
import { notify } from '@inject/shared/notification/engine'
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(
      /<embed[^>]*file_type="([^"]*)"[^>]*><\/embed>/g,
      '{{ embedded $1 }}'
    )
    .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()

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

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

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

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

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