"use client"
import { useEffect, useState } from "react"
import { SidePeekContext } from "./index"

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

export default function SidePeekProvider({
  children,
  searchParams,
  onOpen,
  onClose,
}: SidepeekProviderProps) {
  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) {
      onClose?.()
      setActiveSidePeek(null)
    }
  }

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