import { useCallback, useEffect, useState } from 'react'
import { useRouter } from 'next/router'

export function parsePageQuery(value: string | string[] | undefined): number {
  const raw = typeof value === 'string' ? value : Array.isArray(value) ? value[0] : undefined
  if (!raw) {
    return 1
  }

  const parsed = parseInt(raw, 10)
  return Number.isFinite(parsed) && parsed > 0 ? parsed : 1
}

export function useListPageQuery() {
  const router = useRouter()
  const [page, setPageState] = useState(1)

  useEffect(() => {
    if (!router.isReady) {
      return
    }
    setPageState(parsePageQuery(router.query.page))
  }, [router.isReady, router.query.page])

  const setPage = useCallback(
    (nextPage: number) => {
      const normalized = Math.max(1, Math.floor(nextPage) || 1)
      setPageState(normalized)

      if (!router.isReady) {
        return
      }

      const query = { ...router.query }
      if (normalized === 1) {
        delete query.page
      } else {
        query.page = String(normalized)
      }

      void router.replace({ pathname: router.pathname, query }, undefined, { shallow: true })
    },
    [router],
  )

  return { page, setPage, isReady: router.isReady }
}
