import React from 'react'
import { useRouter } from 'next/router'

export function useSearchParams() {
	const router = useRouter()
	const isClientSide = typeof window !== 'undefined'

	const set = React.useCallback(
		(key: string, v: string | number | boolean) => {
			if (!isClientSide) return

			const url = new URL(window.location.href)
			const params = new URLSearchParams(url.search)

			if (!v || (typeof v === 'string' && v.length === 0)) {
				params.delete(key)
			} else {
				params.set(key, String(v))
			}

			router.replace(`${url.pathname}?${params.toString()}`, undefined, {
				shallow: true,
			})
		},
		[router, isClientSide]
	)

	const remove = React.useCallback(
		(keys: string[]) => {
			if (!isClientSide) return

			const url = new URL(window.location.href)
			const params = new URLSearchParams(url.search)

			keys.forEach((key) => {
				params.delete(key)
			})

			router.replace(`${url.pathname}?${params.toString()}`, undefined, {
				shallow: true,
			})
		},
		[router, isClientSide]
	)

	const get = React.useCallback(
		<T = string,>(key: string, fn?: (v: string | null) => T): T | null => {
			if (!isClientSide) return null

			const params = new URLSearchParams(window.location.search)
			const val = params.get(key)

			if (fn) {
				return fn(val)
			}

			return val as unknown as T
		},
		[isClientSide]
	)

	return { set, remove, get }
}