import type { MouseEvent } from 'react'
import { useState, useCallback } from 'react'

import { useToggle } from 'hooks'

import { PopupPages } from '../../types'

export const usePopupNavigation = () => {
  const {
    close,
    isOpen,
    open,
  } = useToggle()

  const [page, setPage] = useState<PopupPages>(PopupPages.PLAYLIST)

  const closePopup = useCallback(() => {
    close()
    setPage(PopupPages.PLAYLIST)
  }, [close])

  const goBack = useCallback((e?: MouseEvent<HTMLElement>) => {
    e?.stopPropagation()
    if (page === PopupPages.PLAYLIST) {
      closePopup()
    } else {
      setPage(PopupPages.PLAYLIST)
    }
  }, [page, closePopup])

  const goToSettings = useCallback((e: MouseEvent<HTMLElement>) => {
    e.stopPropagation()
    setPage(PopupPages.SETTINGS)
  }, [])

  return {
    closePopup,
    goBack,
    goToSettings,
    isOpen,
    openPopup: open,
    page,
  }
}
