"use client"

import { usePathname, useRouter, useSearchParams } from "next/navigation"
import React, { Children, cloneElement, useEffect, useState } from "react"

import SidePeek from "@/components/TempDesignSystem/SidePeek"
import { SidePeekContentKey } from "@/components/TempDesignSystem/SidePeek/types"

export default function SidePeekContainer({
  children,
}: React.PropsWithChildren) {
  const router = useRouter()
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const [activeSidePeek, setActiveSidePeek] =
    useState<SidePeekContentKey | null>(() => {
      const sidePeekParam = searchParams.get(
        "sidepeek"
      ) as SidePeekContentKey | null
      return sidePeekParam || null
    })

  useEffect(() => {
    const sidePeekParam = searchParams.get(
      "sidepeek"
    ) as SidePeekContentKey | null
    if (sidePeekParam !== activeSidePeek) {
      setActiveSidePeek(sidePeekParam)
    }
  }, [searchParams, activeSidePeek])

  function handleClose(isOpen: boolean) {
    if (!isOpen) {
      setActiveSidePeek(null)

      const nextSearchParams = new URLSearchParams(searchParams.toString())
      nextSearchParams.delete("sidepeek")

      router.push(`${pathname}?${nextSearchParams}`, { scroll: false })
    }
  }
  const childrenWithIsActive = Children.map(children, (child) => {
    if (!React.isValidElement(child)) {
      return child
    }
    return cloneElement(child as React.ReactElement, {
      isActive:
        (child.props.contentKey as SidePeekContentKey) === activeSidePeek,
    })
  })

  return (
    <SidePeek activeContent={activeSidePeek} onClose={handleClose}>
      {childrenWithIsActive}
    </SidePeek>
  )
}
