import {
  Button,
  Dialog,
  DialogTrigger,
  OverlayArrow,
  Popover as RAPopover,
} from "react-aria-components"

import { CloseLargeIcon } from "@/components/Icons"
import useSetOverFlowVisibleOnRA from "@/hooks/useSetOverflowVisibleOnRA"

import { Arrow } from "./Arrow"
import { PopoverProps } from "./popover"

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

export default function Popover({
  triggerContent,
  children,
  isNestedPopover = false,
  ...props
}: PopoverProps) {
  const setOverflowVisible = useSetOverFlowVisibleOnRA(isNestedPopover)

  return (
    <DialogTrigger onOpenChange={setOverflowVisible}>
      <Button className={styles.trigger}>{triggerContent}</Button>

      <RAPopover
        {...props}
        offset={16}
        crossOffset={-24}
        className={styles.root}
      >
        <OverlayArrow>
          <Arrow />
        </OverlayArrow>
        <Dialog>
          {({ close }) => (
            <>
              <Button className={styles.closeButton} onPress={close}>
                <CloseLargeIcon height={20} width={20} />
              </Button>
              {children}
            </>
          )}
        </Dialog>
      </RAPopover>
    </DialogTrigger>
  )
}
