import React, { FC } from 'react';
// TODO @grsmto: might be worth migrating to react-pose once https://github.com/reach/reach-ui/issues/126 is fixed
import { Transition } from 'react-spring/renderprops';
import { transparentize } from 'polished';
import { withTheme, ThemeInterface } from '../../styles';
import * as sc from './styles';

interface Props {
  isOpen: boolean;
  onClose?: () => void;
  isCloseable?: boolean;
  isCentered?: boolean;
  theme: ThemeInterface;
}

export const ModalBaseComponent: FC<Props> = ({
  children,
  isOpen: isOpenProps,
  isCloseable,
  isCentered,
  onClose,
  theme,
}) => {
  const handleCloseRequest = () => {
    if (!isCloseable) {
      return;
    }

    if (onClose) {
      onClose();
    }
  };

  return (
    <Transition
      items={isOpenProps}
      from={{ background: transparentize(1, theme.colors.gray[4]) }}
      enter={{ background: transparentize(0.99, theme.colors.gray[4]) }}
      leave={{ background: transparentize(1, theme.colors.gray[4]) }}
    >
      {isOpen =>
        isOpen &&
        (styles => (
          <sc.Overlay
            style={styles}
            onDismiss={handleCloseRequest}
            isCentered={isCentered}
          >
            {children}
          </sc.Overlay>
        ))
      }
    </Transition>
  );
};

export const ModalBase = withTheme(ModalBaseComponent);

ModalBase.defaultProps = {
  isOpen: false,
  isCloseable: true,
  isCentered: true,
};
