import { useEffect, useState } from 'react'

import { debounce } from '../../services/HelperServiceTyped'
import isClient from '../../services/isClient'

type WindowSizeType = {
  width: number | undefined
  height: number | undefined
}

export const useWindowSize = (ignoreHeaderHeight?: boolean): WindowSizeType => {
  const [windowSize, setWindowSize] = useState<WindowSizeType>({
    width: undefined,
    height: undefined,
  })
  const headerHeight = isClient
    ? Number(
        getComputedStyle(document.documentElement).getPropertyValue(
          '--header-height',
        ),
      )
    : 0

  // This sets initial window size to prevent negative height values
  useEffect(() => {
    setWindowSize({
      width: window.innerWidth,
      height: window.innerHeight - (!ignoreHeaderHeight ? headerHeight : 0),
    })
  }, [headerHeight, ignoreHeaderHeight])

  useEffect(() => {
    // Handler to call on window resize with the
    const handleResize = debounce(() => {
      // if this is ran in a test after the environment is torn down, window might be undefined
      if (typeof window === 'undefined') return

      // Set window width/height to state
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight - (!ignoreHeaderHeight ? headerHeight : 0),
      })
    }, 250)
    window.addEventListener('resize', handleResize)
    // Initial window size
    handleResize()
    return () => {
      window.removeEventListener('resize', handleResize)
    }
  }, [headerHeight, ignoreHeaderHeight])

  return windowSize
}
