"use client"
import { usePathname, useRouter, useSearchParams } from "next/navigation"
import { createContext, useEffect, useState } from "react"

interface ISidePeekContext {
  handleClose: (isOpen: boolean) => void
  activeSidePeek: string | null
}

export const SidePeekContext = createContext<ISidePeekContext | null>(null)

function SidePeekProvider({ children }: React.PropsWithChildren) {
  const router = useRouter()
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const [activeSidePeek, setActiveSidePeek] = useState<string | null>(() => {
    const sidePeekParam = searchParams.get("s")
    return sidePeekParam || null
  })

  useEffect(() => {
    const sidePeekParam = searchParams.get("s")
    if (sidePeekParam !== activeSidePeek) {
      setActiveSidePeek(sidePeekParam)
    }
  }, [searchParams, activeSidePeek])

  function handleClose(isOpen: boolean) {
    if (!isOpen) {
      const nextSearchParams = new URLSearchParams(searchParams.toString())
      nextSearchParams.delete("s")

      router.push(`${pathname}?${nextSearchParams}`, { scroll: false })
      setActiveSidePeek(null)
    }
  }

  return (
    <SidePeekContext.Provider value={{ handleClose, activeSidePeek }}>
      {children}
    </SidePeekContext.Provider>
  )
}

export default SidePeekProvider
