import _ from "lodash";
import React from "react";
import { connect } from "react-redux";

const Content = props => {
  const { settings, queryString } = props;
  const { actions } = settings;

  const Parent = x => (
    <div style={{ ...settings.properties, marginTop: 0 }}>{x.children}</div>
  );
  const content = (
    <span
      // style={{ ...style.span }}
      dangerouslySetInnerHTML={{ __html: settings.html }}
    />
  );

  const haslink = _.get(
    _.filter(
      actions,
      itm =>
        itm.behavior === "click" &&
        (itm.type === "GO_TO_URL" || itm.type === "TRIGGER_NEXT_NODE")
    ),
    0,
    false
  );

  let href = haslink
    ? _.get(actions, "[0].payload.url", _.get(settings, "href", ""))
    : "";

  href = _.has(props, "queryString") ? `${href}?id=${queryString.id}` : href;

  return haslink ? (
    <Parent>
      <a href={href} style={{ cursor: "pointer", textDecoration: "underline" }}>
        {content}
      </a>
    </Parent>
  ) : (
    <Parent>{content}</Parent>
  );
};

const Paragraph = props => {
  const { settings } = props;
  const marginTop = settings.properties ? settings.properties.marginTop : 0;
  const textAlign = settings.properties
    ? settings.properties.textAlign
    : "inherit";

  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
        })
      );
    }
  };

  return (
    <div onClick={handleClick} style={{ marginTop, textAlign }}>
      <Content {...props} />
    </div>
  );
};

export default connect()(Paragraph);
