'use client'

import { useContext, useRef } from 'react'
import { Dialog, Modal, ModalOverlay } from 'react-aria-components'

import { MaterialIcon } from '../Icons/MaterialIcon'
import { Typography } from '../Typography'

import { SidePeekContext } from './SidePeekContext'

import SidePeekSEO from './SidePeekSEO'

import { IconButton } from '../IconButton'
import styles from './sidePeek.module.css'

interface SidePeekProps {
  contentKey?: string
  title: string
  isOpen?: boolean
  openInRoot?: boolean
  handleClose?: (isOpen: boolean) => void
  closeLabel: string
}

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

  const context = useContext(SidePeekContext)
  function onClose() {
    const closeHandler = handleClose || context?.handleClose
    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.aside}>
                <header className={styles.header}>
                  {title ? (
                    <Typography variant="Title/md">
                      <h2 className={styles.heading}>{title}</h2>
                    </Typography>
                  ) : null}
                  <IconButton
                    theme="Black"
                    style="Muted"
                    onPress={onClose}
                    aria-label={closeLabel}
                  >
                    <MaterialIcon
                      icon="close"
                      color="Icon/Interactive/Default"
                    />
                  </IconButton>
                </header>
                <div className={styles.sidePeekContent}>{children}</div>
              </aside>
            </Dialog>
          </Modal>
        </ModalOverlay>
      </div>

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