import { forwardRef } from 'react';

import { Position } from '..';
import BottomSheet from '../bottomSheet';
import { useLayout } from '../hooks';
import Panel, { type PanelProps } from '../panel';
import { isServerSide } from '../domHelpers';

const ResponsivePanel = forwardRef<HTMLDivElement, PanelProps>(function ResponsivePanel(
  {
    anchorRef,
    arrow = false,
    flip = true,
    children,
    className = undefined,
    onClose,
    open = false,
    position = Position.BOTTOM,
    anchorWidth = false,
    'aria-label': ariaLabel,
    considerHeight = false,
    'aria-labelledby': ariaLabelledBy,
  }: PanelProps,
  reference,
) {
  const { isMobile } = useLayout();
  const SHORT_SCREEN = 500;
  const isShortViewport = considerHeight && !isServerSide() && window.innerHeight < SHORT_SCREEN;

  if (isMobile || isShortViewport) {
    return (
      <BottomSheet
        key="bottomSheet"
        aria-label={ariaLabel}
        aria-labelledby={ariaLabelledBy}
        open={open}
        className={className}
        onClose={onClose}
      >
        {children}
      </BottomSheet>
    );
  }
  return (
    <Panel
      key="panel"
      ref={reference}
      flip={flip}
      arrow={arrow}
      open={open}
      position={position}
      anchorWidth={anchorWidth}
      anchorRef={anchorRef}
      aria-label={ariaLabel}
      considerHeight={considerHeight}
      aria-labelledby={ariaLabelledBy}
      className={className}
      onClose={onClose}
    >
      {children}
    </Panel>
  );
});

export default ResponsivePanel;
