/*
 *
 * EmailWrapper
 *
 */
import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
import { injectIntl, intlShape } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import { bindActionCreators } from 'redux';
import { compose } from 'redux';
import { UserIsAuthenticated } from '../../utils/authWrapper';
import {
  selectEmailLayout,
  selectCmsTemplates,
  selectEdmEditor,
  uploadSelector,
  selectCmsTemplatesLoader,
} from '../Templates/selectors';
import * as templatesActionsCreators from '../Templates/actions';
import { selectCurrentOrgDetails, makeSelectMetaEntities, isLoadingMetaEntities, setInjectedTags, selectLiquidStateDetails } from "../../v2Containers/Cap/selectors";
import { makeSelectEmail, selectLoadingStatus, makeSelectFetchingCmsData } from '../Email/selectors';
import * as emailActionsCreators from '../Email/actions';
import * as globalActions from '../Cap/actions';
import EmailWrapperView from './components/EmailWrapperView';
import useEmailWrapper from './hooks/useEmailWrapper';
import HTMLEditorTesting from './components/HTMLEditorTesting';
import injectReducer from '../../utils/injectReducer';
import injectSaga from '../../utils/injectSaga';
import v2EmailReducer from '../Email/reducer';
import { v2EmailSagas } from '../Email/sagas';


const EmailWrapper = (props) => {
  // Destructure props for clarity before passing to hook
  const {
    emailCreateMode,
    step,
    isFullMode,
    EmailLayout,
    isUploading,
    onEmailModeChange,
    isGetFormData,
    type,
    templatesActions,
    CmsTemplates,
    SelectedEdmDefaultTemplate,
    showNextStep,
    getFormdata,
    intl,
    cap,
    onResetStep,
    setIsLoadingContent,
    showTemplateName,
    showLiquidErrorInFooter,
    onValidationFail,
    forwardedTags,
    selectedOfferDetails,
    getCmsTemplatesInProgress,
    currentOrgDetails,
    moduleType,
    onEnterTemplateName,
    onRemoveTemplateName,
    eventContextTags,
    waitEventContextTags,
    isLoyaltyModule,
    cmsTemplatesLoader,
    onPreviewContentClicked,
    onTestContentClicked,
    editor,
    showTestAndPreviewSlidebox,
    handleTestAndPreview,
    handleCloseTestAndPreview,
    isTestAndPreviewMode,
    location,
    emailActions,
    Email,
    metaEntities,
    loadingTags,
    injectedTags,
    globalActions: globalActionsProp,
    templateData,
    params,
    fetchingLiquidTags,
    createTemplateInProgress,
    fetchingCmsData,
    onHtmlEditorValidationStateChange,
    isEditEmail = true,
  } = props;

  // Pass destructured props to the custom hook
  const {
    templateName,
    isTemplateNameEmpty,
    modeContent,
    modes,
    isShowEmailCreate,
    emailProps,
    cmsTemplatesProps,
    uploadButtonLabel,
    onTemplateNameChange,
    onChange,
    useFileUpload,
  } = useEmailWrapper({
    emailCreateMode,
    step,
    isFullMode,
    EmailLayout,
    isUploading,
    onEmailModeChange,
    isGetFormData,
    type,
    templatesActions,
    CmsTemplates,
    SelectedEdmDefaultTemplate,
    showNextStep,
    getFormdata,
    intl,
    cap,
    onResetStep,
    setIsLoadingContent,
    showTemplateName,
    showLiquidErrorInFooter,
    onValidationFail,
    forwardedTags,
    selectedOfferDetails,
    getCmsTemplatesInProgress,
    currentOrgDetails,
    moduleType,
    onEnterTemplateName,
    onRemoveTemplateName,
    eventContextTags,
    waitEventContextTags,
    isLoyaltyModule,
    cmsTemplatesLoader,
    onPreviewContentClicked,
    onTestContentClicked,
    editor,
    showTestAndPreviewSlidebox,
    handleTestAndPreview,
    handleCloseTestAndPreview,
    isTestAndPreviewMode,
    location,
    emailActions,
    Email,
    templateData,
    params,
    isEditEmail,
  });

  // Render using the presentation component with data from the hook
  return (
    <div>
      <EmailWrapperView
        isUploading={isUploading}
        emailCreateMode={emailCreateMode}
        step={step}
        isFullMode={isFullMode}
        templateName={templateName}
        onTemplateNameChange={onTemplateNameChange}
        isTemplateNameEmpty={isTemplateNameEmpty}
        modes={modes}
        onChange={onChange}
        EmailLayout={EmailLayout}
        modeContent={modeContent}
        useFileUpload={useFileUpload}
        uploadButtonLabel={uploadButtonLabel}
        isShowEmailCreate={isShowEmailCreate}
        emailProps={emailProps}
        cmsTemplatesProps={cmsTemplatesProps}
        onPreviewContentClicked={onPreviewContentClicked}
        onTestContentClicked={onTestContentClicked}
        editor={editor}
        // New flow props - only used when supportCKEditor is false
        // These props are needed for EmailHTMLEditor component (tag loading, validation, etc.)
        metaEntities={metaEntities}
        loadingTags={loadingTags}
        injectedTags={injectedTags}
        globalActions={globalActionsProp}
        supportedTags={props.supportedTags}
        getDefaultTags={type}
        location={location}
        currentOrgDetails={currentOrgDetails}
        onValidationFail={onValidationFail}
        forwardedTags={forwardedTags}
        selectedOfferDetails={selectedOfferDetails}
        eventContextTags={eventContextTags}
        waitEventContextTags={waitEventContextTags}
        getFormdata={getFormdata}
        isGetFormData={isGetFormData}
        getLiquidTags={globalActionsProp?.getLiquidTags}
        showLiquidErrorInFooter={showLiquidErrorInFooter}
        intl={intl}
        emailActions={emailActions}
        showTestAndPreviewSlidebox={showTestAndPreviewSlidebox}
        handleTestAndPreview={handleTestAndPreview}
        handleCloseTestAndPreview={handleCloseTestAndPreview}
        Email={Email}
        setIsLoadingContent={setIsLoadingContent}
        templateData={templateData}
        params={params}
        isEditEmail={isEditEmail}
        showTemplateName={showTemplateName}
        fetchingLiquidTags={fetchingLiquidTags}
        createTemplateInProgress={createTemplateInProgress}
        fetchingCmsData={fetchingCmsData}
        onHtmlEditorValidationStateChange={onHtmlEditorValidationStateChange}
        moduleType={moduleType}
      />

      {/* HTMLEditor Testing Component - Console Controlled */}
      <HTMLEditorTesting />
    </div>
  );
};

EmailWrapper.propTypes = {
  onEmailModeChange: PropTypes.func.isRequired,
  isGetFormData: PropTypes.bool,
  type: PropTypes.string,
  emailCreateMode: PropTypes.string,
  EmailLayout: PropTypes.object,
  templatesActions: PropTypes.object,
  CmsTemplates: PropTypes.arrayOf(PropTypes.object),
  SelectedEdmDefaultTemplate: PropTypes.object,
  step: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  showNextStep: PropTypes.func,
  getFormdata: PropTypes.func,
  intl: intlShape,
  cap: PropTypes.object,
  onResetStep: PropTypes.func,
  isFullMode: PropTypes.bool,
  isUploading: PropTypes.bool,
  setIsLoadingContent: PropTypes.func,
  showTemplateName: PropTypes.func,
  showLiquidErrorInFooter: PropTypes.func,
  onValidationFail: PropTypes.func,
  forwardedTags: PropTypes.object,
  selectedOfferDetails: PropTypes.array,
  getCmsTemplatesInProgress: PropTypes.bool,
  currentOrgDetails: PropTypes.object,
  moduleType: PropTypes.string,
  onEnterTemplateName: PropTypes.func,
  onRemoveTemplateName: PropTypes.func,
  eventContextTags: PropTypes.array,
  waitEventContextTags: PropTypes.object,
  isLoyaltyModule: PropTypes.bool,
  onPreviewContentClicked: PropTypes.func,
  onTestContentClicked: PropTypes.func,
  editor: PropTypes.object,
  showTestAndPreviewSlidebox: PropTypes.bool,
  handleTestAndPreview: PropTypes.func,
  handleCloseTestAndPreview: PropTypes.func,
  isTestAndPreviewMode: PropTypes.bool,
  location: PropTypes.object,
  onHtmlEditorValidationStateChange: PropTypes.func,
};

const mapStateToProps = createStructuredSelector({
  EmailLayout: selectEmailLayout(),
  CmsTemplates: selectCmsTemplates(),
  SelectedEdmDefaultTemplate: selectEdmEditor(),
  isUploading: uploadSelector(),
  cmsTemplatesLoader: selectCmsTemplatesLoader(),
  currentOrgDetails: selectCurrentOrgDetails(),
  Email: makeSelectEmail(),
  metaEntities: makeSelectMetaEntities(),
  loadingTags: isLoadingMetaEntities(),
  injectedTags: setInjectedTags(),
  fetchingLiquidTags: selectLiquidStateDetails(),
  createTemplateInProgress: selectLoadingStatus(),
  fetchingCmsData: makeSelectFetchingCmsData(),
});

function mapDispatchToProps(dispatch) {
  return {
    templatesActions: bindActionCreators(templatesActionsCreators, dispatch),
    emailActions: bindActionCreators(emailActionsCreators, dispatch),
    globalActions: bindActionCreators(globalActions, dispatch),
  };
}

// Inject Email reducer and saga so that getCmsSetting action can be handled
const withReducer = injectReducer({ key: 'email', reducer: v2EmailReducer });
const withEmailSaga = injectSaga({ key: 'email', saga: v2EmailSagas });

const ConnectedEmailWrapper = connect(mapStateToProps, mapDispatchToProps)(injectIntl(EmailWrapper));

export default compose(
  UserIsAuthenticated,
  withReducer,
  withEmailSaga,
)(ConnectedEmailWrapper);
