"use client"

import { useIsSSR } from "@react-aria/ssr"
import React, { Children, cloneElement } from "react"
import {
  Dialog,
  DialogTrigger,
  Modal,
  ModalOverlay,
} from "react-aria-components"

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

import styles from "./sidePeek.module.css"

import type { SidePeekProps } from "./sidePeek"

function SidePeek({
  children,
  handleClose,
  activeSidePeek,
}: React.PropsWithChildren<SidePeekProps>) {
  const sidePeekChildren = Children.map(children, (child) => {
    if (!React.isValidElement(child)) {
      return child
    }
    return cloneElement(child as React.ReactElement, {
      isActive:
        (child.props.contentKey as SidePeekContentKey) === activeSidePeek,
      onClose: handleClose,
    })
  })

  const isSSR = useIsSSR()
  return isSSR ? (
    <div>{children}</div>
  ) : (
    <DialogTrigger>
      <ModalOverlay
        className={styles.overlay}
        isOpen={!!activeSidePeek}
        onOpenChange={handleClose}
        isDismissable
      >
        <Modal className={styles.sidePeek}>
          <Dialog className={styles.dialog}>{sidePeekChildren}</Dialog>
        </Modal>
      </ModalOverlay>
    </DialogTrigger>
  )
}

export default SidePeek
