import { observer } from 'mobx-react';
import { useApphouse } from '../../context/useApphouse';
import { css } from 'glamor';
import React, { ForwardedRef, forwardRef } from 'react';
import { ApphouseComponent } from '../component.interfaces';
import { useLocalStyles } from '../../styles/defaults/useLocalStyles';
import { merge } from '../../utils/obj/merge';
import { PopupBodyStyles } from './Popup.interface';
import { getAllowChildToFillParentHeightStyle } from '../../styles/helpers';
import { getGutterStyles } from '../../styles/getGutterStyles';

/**
 * Interface for the popup body component
 */
export interface PopupBodyProps extends ApphouseComponent<PopupBodyStyles> {
  /**
   * If fullscreen it will occupy the whole window height
   */
  fullscreen?: boolean;
  /**
   * The content of the popup body
   */
  children?: React.ReactNode;
  /**
   * A fixed height for the popup body
   * If number, it will be converted to px
   * @optional
   * @default auto
   */
  height?: string | number;
}
/**
 * A component that renders a popup body
 * DO NOT EXPORT THIS COMPONENT, ONLY FOR INTERNAL USE.
 * Must export the observer version of this component available
 * at the bottom of this file.
 */
const PopupBodyComponent = forwardRef(
  (props: PopupBodyProps, ref: ForwardedRef<HTMLDivElement>) => {
    const {
      fullscreen = false,
      styleOverwrites,
      gutters,
      children,
      height = 'auto'
    } = props;
    const {
      theme: { tokens },
      app
    } = useApphouse();
    const {
      windowSize: { height: windowHeight }
    } = app.layout;

    const allowChildToFillHeight = fullscreen
      ? getAllowChildToFillParentHeightStyle(windowHeight)
      : getAllowChildToFillParentHeightStyle(height);
    const componentStyles = merge(
      {},
      {
        container: {
          boxSizing: 'border-box',
          color: 'inherit',
          fontFamily: tokens.fontFamily.text,
          outline: 'none',
          backgroundColor: 'transparent'
        },
        content: {
          ...allowChildToFillHeight,
          ...getGutterStyles(gutters)
        }
      }
    );
    const localStyles = useLocalStyles(componentStyles, styleOverwrites);

    return (
      <div
        ref={ref}
        tabIndex={0}
        data-style="body"
        data-xray="PopupBody"
        {...css(localStyles.container)}
      >
        <div {...css(localStyles.content)}>{children}</div>
      </div>
    );
  }
);

export const PopupBody = observer(PopupBodyComponent);
