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

interface SidepeekProviderProps extends React.PropsWithChildren {
  onOpen?: (sidePeek: string) => void
}

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

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

export default function SidePeekProvider({
  children,
  onOpen,
}: SidepeekProviderProps) {
  const router = useRouter()
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const [activeSidePeek, setActiveSidePeek] = useState<string | null>(null)
  useEffect(() => {
    const sidePeekParam = searchParams.get("s")
    if (sidePeekParam !== activeSidePeek) {
      setActiveSidePeek(sidePeekParam)
    }
  }, [searchParams, activeSidePeek])

  useEffect(() => {
    if (activeSidePeek && onOpen) {
      onOpen(activeSidePeek)
    }
  }, [activeSidePeek, onOpen])

  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>
  )
}
