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

import useSetOverFlowVisibleOnRA from "@scandic-hotels/common/hooks/useSetOverflowVisibleOnRA"
import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"

import { Arrow } from "./Arrow"

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

import type { PopoverProps } from "./popover"

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

  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}>
                <MaterialIcon icon="close" size={20} />
              </Button>
              {children}
            </>
          )}
        </Dialog>
      </RAPopover>
    </DialogTrigger>
  )
}
