"use client"

import { useContext, useRef } from "react"
import { Dialog, Modal, ModalOverlay } from "react-aria-components"
import { useIntl } from "react-intl"

import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"
import { Typography } from "@scandic-hotels/design-system/Typography"

import { SidePeekContext } from "@/components/SidePeeks/SidePeekProvider"

import Button from "../Button"
import SidePeekSEO from "./SidePeekSEO"

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

import type { SidePeekProps } from "./sidePeek"

export default function SidePeek({
  children,
  title,
  contentKey,
  handleClose,
  isOpen,
  openInRoot = false,
}: React.PropsWithChildren<SidePeekProps>) {
  const intl = useIntl()
  const rootDiv = useRef<HTMLDivElement>(null)

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

  return (
    <>
      <div ref={openInRoot ? null : rootDiv}>
        <ModalOverlay
          UNSTABLE_portalContainer={rootDiv.current || undefined}
          className={styles.overlay}
          isOpen={
            isOpen || (!!contentKey && contentKey === context?.activeSidePeek)
          }
          onOpenChange={onClose}
          isDismissable
        >
          <Modal className={styles.modal}>
            <Dialog className={styles.dialog} aria-label={title}>
              <aside className={styles.sidePeek}>
                <header className={styles.header}>
                  {title ? (
                    <Typography variant="Title/md">
                      <h2 className={styles.heading}>{title}</h2>
                    </Typography>
                  ) : null}
                  <Button
                    aria-label={intl.formatMessage({
                      defaultMessage: "Close",
                    })}
                    className={styles.closeButton}
                    intent="text"
                    onPress={onClose}
                  >
                    <MaterialIcon
                      icon="close"
                      color="Icon/Interactive/Default"
                    />
                  </Button>
                </header>
                <div className={styles.sidePeekContent}>{children}</div>
              </aside>
            </Dialog>
          </Modal>
        </ModalOverlay>
      </div>

      <SidePeekSEO title={title}>{children}</SidePeekSEO>
    </>
  )
}
