import React from "react";
import { get } from "lodash";
import { connect } from "react-redux";

export const ContainerContent = (props) => {
  return (
    <div
      style={{
        backgroundImage: get(
          props,
          "style.backgroundImage",
          get(props, "properties.backgroundImage")
        ),
        backgroundSize: get(
          props,
          "style.backgroundSize",
          get(props, "properties.backgroundSize")
        ),
        backgroundPosition: get(
          props,
          "style.backgroundPosition",
          get(props, "properties.backgroundPosition")
        ),
        backgroundRepeat: get(
          props,
          "style.backgroundRepeat",
          get(props, "properties.backgroundRepeat")
        ),
      }}
    >
      <div
        style={{
          ...props.style,
          backgroundImage: `none`,
          backgroundColor: get(props.style, "backgroundColor"),
        }}
      >
        {props.children}
      </div>
    </div>
  );
};

const Container = (props) => {
  const handleClick = () => {
    const {
      dispatch,
      settings,
      cKey,
      fieldValues,
      updateComponentSettings,
      getComponentSettings,
    } = props;
    const { actions } = settings;

    if (actions) {
      const doTheseActions = actions.filter((itm) => itm.behavior === "click");
      doTheseActions.forEach((action) =>
        dispatch({
          ...action,
          settings: { ...settings, cKey, fieldValues },
          updateComponentSettings,
          getComponentSettings,
        })
      );
    }
  };

  const properties = props.settings.properties;
  const marginTop = properties.marginTop || -1; // temporarily fixes this problem: https://ambid.slack.com/archives/G164PAK7D/p1560526689091500
  const defaultPosition = marginTop < 0 ? "relative" : "inherit"; // this lets objects with a negative marginTop overlap nearby objects
  const position = get(properties, "position", defaultPosition);
  const width = get(properties, "width");

  return (
    <div
      style={{
        ...props.settings.properties,
        justifyContent: "normal",
        display: "block",
        padding: "1px 0 0 0", // temporarily fixes this problem: https://ambid.slack.com/archives/G164PAK7D/p1560526689091500
        height: props.settings.properties.height || "inherit",
        width,
        // maxWidth,
        marginTop,
        position,
      }}
      onClick={handleClick}
    >
      <ContainerContent
        {...props}
        style={{ padding: props.settings.properties.padding }}
      />
    </div>
  );
};

export default connect()(Container);
