import React from "react";
import styled, { css } from "styled-components";

import { Transition, Div } from "../../base";

import {
  theme,
  getColor,
  getFontWeight,
  getMargin,
  getBorder,
  getBorderRadius,
  getFontSize,
} from "../../styled-config";

const margin = (props) => {
  if (props.top) {
    return css`
      margin-bottom: ${getMargin(props, "popover", "topBottom")};
    `;
  } else if (props.left) {
    return css`
      margin-right: ${getMargin(props, "popover", "leftRight")};
    `;
  } else if (props.bottom) {
    return css`
      margin-top: ${getMargin(props, "popover", "bottomTop")};
    `;
  }

  return css`
    margin-left: ${getMargin(props, "popover", "rightLeft")};
  `;
};

const borderRadius = (props) => {
  return css`
    border-radius: ${getBorderRadius(props, "popover", "default")};
  `;
};

export const PopoverWithoutTransition = styled(Div)`
  position: absolute;
  z-index: 1000;
  font-family: Montserrat;
  font-style: normal;
  font-weight: ${(props) => getFontWeight(props, "popover", "default")};
  line-height: 1.5;
  text-align: left;
  text-decoration: none;
  text-shadow: none;
  text-transform: none;
  letter-spacing: normal;
  word-break: normal;
  word-spacing: normal;
  white-space: normal;
  line-break: auto;
  font-size: ${(props) => getFontSize(props, "popover", "sm")};
  word-wrap: break-word;
  background-color: ${(props) => getColor(props, "popover", "backgroundColor")};
  background-clip: padding-box;
  border: ${(props) => getBorder(props, "popover", "default")}
    ${(props) => getColor(props, "popover", "borderColor")};
  ${(props) => margin(props)};
  ${(props) => borderRadius(props)};
`;

PopoverWithoutTransition.defaultProps = {
  theme,
};

export const Popover = React.forwardRef((props, ref) => {
  const { hidden, children, transitionProps, ...rest } = props;

  return (
    <Transition
      noInitialEnter
      hidden={hidden}
      duration={250}
      ref={ref}
      {...transitionProps}
    >
      <PopoverWithoutTransition {...rest}>{children}</PopoverWithoutTransition>
    </Transition>
  );
});
