import { MutableRefObject, RefObject, useLayoutEffect, useState } from 'react'

type Props = {
  selectedFilter: string | boolean
  panelRef: RefObject<HTMLDivElement | null>
  filtersRef: RefObject<HTMLDivElement | null>
  buttonRefs: MutableRefObject<Record<string, HTMLButtonElement | null>>
  isMobile: boolean
  tabs?: unknown[]
}

export const usePanelPosition = ({
  selectedFilter,
  panelRef,
  filtersRef,
  buttonRefs,
  isMobile,
  tabs,
}: Props) => {
  const [left, setLeft] = useState<number | undefined>()

  const hasMultipleTabs = tabs && tabs.length > 1
  const top = isMobile ? (hasMultipleTabs ? 60 : 0) : hasMultipleTabs ? 125 : 66

  useLayoutEffect(() => {
    if (!selectedFilter || typeof selectedFilter !== 'string' || isMobile) {
      setLeft(undefined)
      return
    }

    const panel = panelRef.current
    const container = filtersRef.current
    const button = buttonRefs.current[selectedFilter]

    if (!panel || !container || !button) return

    const panelRect = panel.getBoundingClientRect()
    const containerRect = container.getBoundingClientRect()
    const buttonRect = button.getBoundingClientRect()

    const buttonLeft = buttonRect.left - containerRect.left - 10

    const newLeft = Math.max(
      0,
      Math.min(buttonLeft, containerRect.width - panelRect.width)
    )

    setLeft(newLeft)
  }, [selectedFilter, isMobile])

  return { top, left }
}
