import { useState } from 'react'
import { useIsomorphicLayoutEffect } from 'framer-motion'

import { BREAKPOINTS } from '@/lib/constants'
import type { Breakpoint } from '@/lib/types'

type WindowSize = {
  width?: number
  height?: number
}

export const useBreakpoint = () => {
  const [windowSize, setWindowSize] = useState<WindowSize>({
    width: undefined,
    height: undefined,
  })

  const breakpoint = Object.keys(BREAKPOINTS).reduce<null | string>((current, key) => {
    const pixels = parseInt(BREAKPOINTS[key as Breakpoint])
    const isValid = windowSize?.width && pixels <= windowSize.width

    if (!current) {
      if (isValid) return key
      else return current
    }

    const currentPixels = parseInt(BREAKPOINTS[current as Breakpoint])
    return isValid && pixels >= currentPixels ? key : current
  }, null)

  const isMobile = Boolean(breakpoint && ['xxs', 'xs', 'sm'].includes(breakpoint))
  const isDesktop = Boolean(breakpoint && ['md', 'lg'].includes(breakpoint))

  function handleResize() {
    setWindowSize({
      width: window.innerWidth,
      height: window.innerHeight,
    })
  }

  useIsomorphicLayoutEffect(() => {
    handleResize()
    window.addEventListener('resize', handleResize)
    return () => window.removeEventListener('resize', handleResize)
  }, [])

  return {
    windowSize,
    breakpoint,
    isMobile,
    isDesktop,
  }
}
