import type { ReactNode } from 'react';
import { cx } from 'class-variance-authority';
import * as PopoverPrimitive from '@radix-ui/react-popover';

import './popover.css';
import { PopoverClose } from './popover-close';

type PopoverProps = Pick<PopoverPrimitive.PopoverProps, 'open' | 'onOpenChange'> &
  Pick<PopoverPrimitive.PortalProps, 'container'> &
  PopoverPrimitive.PopperContentProps & {
    children: ReactNode;
    closeButton?: boolean | JSX.Element;
    hasArrow?: boolean;
    content: ReactNode;
  };

export function Popover({
  children,
  closeButton,
  content,
  side,
  open,
  onOpenChange,
  className,
  container,
  hasArrow = true,
  ...delegatedContent
}: PopoverProps) {
  return (
    <PopoverPrimitive.Root open={open} onOpenChange={onOpenChange}>
      <PopoverPrimitive.Trigger asChild>{children}</PopoverPrimitive.Trigger>
      <PopoverPrimitive.Portal container={container}>
        <PopoverPrimitive.Content {...delegatedContent} side={side} className={cx('c-popover-content', className)}>
          {!closeButton ? null : (
            <PopoverClose asChild={typeof closeButton !== 'boolean'}>
              {typeof closeButton !== 'boolean' ? closeButton : null}
            </PopoverClose>
          )}
          {hasArrow && <PopoverPrimitive.Arrow className="c-popover-arrow" offset={5} />}
          {content}
        </PopoverPrimitive.Content>
      </PopoverPrimitive.Portal>
    </PopoverPrimitive.Root>
  );
}
