import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators, compose } from 'redux';
import { injectIntl } from 'react-intl';
import * as globalActions from '../v2Containers/Cap/actions';
import * as creativesContainerActions from '../v2Containers/CreativesContainer/actions';
import { UserIsAuthenticated } from '../utils/authWrapper';

/**
 * Higher Order Component to common out creatives channel logic
 * @param {*} WrappedComponent
 * @returns {*} modified wrapped component
 */
export default ({
  WrappedComponent,
  mapStateToProps,
  mapDispatchToProps,
  userAuth,
  sagas = [],
  reducers = [],
}) => {
  const CreativesCommon = (props) => {
    useEffect(() => {
      const {
        globalActions: {
          setInjectedTags,
        },
        forwardedTags = {},
      } = props;
      // setting the passed tags from parent in Cap store
      setInjectedTags(forwardedTags);
    }, []);

    return <WrappedComponent {...props} />;
  };

  const hocMapDispatchToProps = (dispatch) => {
    const passedMapDispatchToProps = mapDispatchToProps(dispatch);
    return {
      ...passedMapDispatchToProps,
      globalActions: bindActionCreators(globalActions, dispatch),
      creativesContainerActions: bindActionCreators(creativesContainerActions, dispatch),
    };
  };

  const withConnect = connect(mapStateToProps, hocMapDispatchToProps);
  return compose(
    ...sagas,
    ...reducers,
    withConnect,
  )(userAuth ? UserIsAuthenticated(injectIntl(CreativesCommon)) : injectIntl(CreativesCommon));
};
