import { forwardRef } from "react";
import { Icons } from "../icons";
import {
  StyledArrow,
  StyledClose,
  StyledContent,
  StyledPortal,
  StyledRoot,
  StyledTrigger,
} from "./popover.styled";
import type { WithTestId } from "../../types";

interface PopoverProps extends WithTestId<React.ComponentProps<typeof StyledRoot>> {
  trigger?: React.ReactNode;
  showArrow?: boolean;
  showCloseButton?: boolean;
  triggerProps?: React.ComponentProps<typeof StyledTrigger>;
  portalProps?: React.ComponentProps<typeof StyledPortal>;
  contentProps?: React.ComponentProps<typeof StyledContent>;
  closeProps?: React.ComponentProps<typeof StyledClose>;
  arrowProps?: React.ComponentProps<typeof StyledArrow>;
}

export const Popover = forwardRef<HTMLDivElement, PopoverProps>((props, ref) => {
  const {
    trigger,
    showArrow,
    showCloseButton,
    triggerProps,
    portalProps,
    contentProps,
    children,
    closeProps,
    arrowProps,
    ...rootProps
  } = props;
  return (
    <StyledRoot {...rootProps}>
      <StyledTrigger {...triggerProps}>{trigger}</StyledTrigger>
      <StyledPortal {...portalProps}>
        <StyledContent ref={ref} {...contentProps}>
          {children}
          {showCloseButton && (
            <StyledClose {...closeProps}>
              <Icons.Close color="$light-off-white" />
            </StyledClose>
          )}
          {showArrow && <StyledArrow {...arrowProps} />}
        </StyledContent>
      </StyledPortal>
    </StyledRoot>
  );
});

Popover.displayName = "Popover";
