import { useAuthIdentity } from '@inject/graphql/auth'
import { notifyNoncommmit } from '@inject/shared/notification/var/notifications'
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) {
      notifyNoncommmit('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) {
      notifyNoncommmit('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) {
      notifyNoncommmit('Your account is not active', { intent: 'danger' })
      nav('/')
    }
  }, [isActive, loading, nav])
}

const MAX_ALLOWED_FILE_SIZE = 100 * 1000 * 1000 // 100MB
export const checkFileSize = (file: File) => {
  if (file.size > MAX_ALLOWED_FILE_SIZE) {
    notifyNoncommmit(`File is too large. Maximum allowed size is 100MB.`, {
      intent: 'danger',
    })
    return false
  }
  return true
}

export const convertMinutes = (minutes: number) => {
  let hours = Math.floor(minutes / 60)
  const days = Math.floor(hours / 24)
  hours = hours % 24
  minutes = minutes % 60

  let result = ''
  if (days > 0) {
    const dText = days == 1 ? 'day' : 'days'
    const coma = hours > 0 ? ', ' : ''
    result = result.concat(days.toString(), ' ', dText, coma)
  }
  if (hours > 0) {
    const hText = hours == 1 ? 'hour' : 'hours'
    result = result.concat(hours.toString(), ' ', hText)
  }
  if (minutes > 0) {
    const mText = minutes == 1 ? 'minute' : 'minutes'
    const conjunction = hours > 0 ? ' and ' : days > 0 ? ' and ' : ''
    result = result.concat(conjunction, minutes.toString(), ' ', mText)
  }

  return result
}
