import * as React from "react";
import classNames from "classnames";
import {
  AriaDialogProps,
  AriaPopoverProps,
  DismissButton,
  Overlay,
  useDialog,
  usePopover,
} from "react-aria";
import { OverlayTriggerState } from "react-stately";

import { useThemeClass } from "../ThemeProvider/ThemeProvider";

import styles from "./PickerPopover.module.css";

export interface PickerPopoverProps extends Omit<AriaPopoverProps, "popoverRef"> {
  children: React.ReactNode;
  state: OverlayTriggerState;
  dialogProps: AriaDialogProps;
}

export function PickerPopover({ children, state, offset = 8, ...props }: PickerPopoverProps) {
  const themeClass = useThemeClass();

  const popoverRef = React.useRef<HTMLDivElement>(null);
  const { popoverProps, underlayProps } = usePopover(
    {
      ...props,
      offset,
      popoverRef,
    },
    state,
  );

  const dialogRef = React.useRef<HTMLDivElement>(null);
  const { dialogProps } = useDialog(props.dialogProps, dialogRef);

  return (
    <Overlay>
      <div {...underlayProps} className={styles.popoverUnderlay} />
      <div {...popoverProps} ref={popoverRef} className={classNames(themeClass, styles.popover)}>
        <DismissButton onDismiss={state.close} />
        <div {...dialogProps} ref={dialogRef}>
          {children}
        </div>
        <DismissButton onDismiss={state.close} />
      </div>
    </Overlay>
  );
}
