"use client"

import { useIsSSR } from "@react-aria/ssr"
import { useContext, useState } from "react"
import {
  Dialog,
  DialogTrigger,
  Modal,
  ModalOverlay,
} from "react-aria-components"
import { useIntl } from "react-intl"

import { CloseLargeIcon } from "@/components/Icons"
import { SidePeekContext } from "@/components/SidePeekProvider"

import Button from "../Button"
import Title from "../Text/Title"

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

import type { SidePeekProps } from "./sidePeek"

function SidePeek({
  children,
  title,
  contentKey,
  handleClose,
  isOpen,
}: React.PropsWithChildren<SidePeekProps>) {
  const isSSR = useIsSSR()
  const intl = useIntl()

  const [rootDiv, setRootDiv] = useState<HTMLDivElement | undefined>(undefined)

  function setRef(node: HTMLDivElement | null) {
    if (node) {
      setRootDiv(node)
    }
  }

  const context = useContext(SidePeekContext)
  function onClose() {
    const closeHandler = handleClose || context?.handleClose
    closeHandler && closeHandler(false)
  }

  if (isSSR) {
    return (
      <div>
        <h2>{title}</h2>
        {children}
      </div>
    )
  }

  return (
    <div ref={setRef}>
      <DialogTrigger>
        <ModalOverlay
          UNSTABLE_portalContainer={rootDiv}
          className={styles.overlay}
          isOpen={
            isOpen || (!!contentKey && contentKey === context?.activeSidePeek)
          }
          onOpenChange={onClose}
          isDismissable
        >
          <Modal className={styles.modal}>
            <Dialog className={styles.dialog}>
              <aside className={styles.sidePeek}>
                <header className={styles.header}>
                  {title ? (
                    <Title
                      color="burgundy"
                      textTransform="uppercase"
                      level="h2"
                      as="h3"
                    >
                      {title}
                    </Title>
                  ) : null}
                  <Button
                    aria-label={intl.formatMessage({ id: "Close" })}
                    className={styles.closeButton}
                    intent="text"
                    onPress={onClose}
                  >
                    <CloseLargeIcon color="burgundy" />
                  </Button>
                </header>
                <div className={styles.sidePeekContent}>{children}</div>
              </aside>
            </Dialog>
          </Modal>
        </ModalOverlay>
      </DialogTrigger>
    </div>
  )
}

export default SidePeek
