import React, { useRef, useCallback } from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import styled from 'styled-components';
import isEmpty from 'lodash/isEmpty';
import get from 'lodash/get';
import CapRadioCard from '@capillarytech/cap-ui-library/CapRadioCard';
import CapInput from '@capillarytech/cap-ui-library/CapInput';
import CapUploader from '@capillarytech/cap-ui-library/CapUploader';
import CapSpin from '@capillarytech/cap-ui-library/CapSpin';
import CapButton from '@capillarytech/cap-ui-library/CapButton';
import CapError from '@capillarytech/cap-ui-library/CapError';
import ComponentWithLabelHOC from '@capillarytech/cap-ui-library/assets/HOCs/ComponentWithLabelHOC';
import { CAP_COLOR_06, CAP_WHITE } from '@capillarytech/cap-ui-library/styled/variables';
import { EmailWithoutSaga } from '../../Email';
import CmsTemplatesComponent from '../../../v2Components/CmsTemplatesComponent';
import EmailHTMLEditor from './EmailHTMLEditor';
import TestAndPreviewSlidebox from '../../../v2Components/TestAndPreviewSlidebox';
import { EMAIL } from '../../CreativesContainer/constants';
import messages from '../messages';
import { EMAIL_CREATE_MODES, STEPS } from '../constants';
import { hasSupportCKEditor } from '../../../utils/common';

const CapRadioCardWithLabel = ComponentWithLabelHOC(CapRadioCard);

const CardContainer = styled.div`
  margin-top: 16px;

  .ant-radio-group.cap-radioCard-v2 {
    .ant-radio-button-wrapper {
      &.ant-radio-button-wrapper-checked {
        .icon-container {
          background-color: ${CAP_COLOR_06};
          .anticon,
          .cap-icon {
            color: ${CAP_WHITE};
          }
        }
      }
    }
  }
`;


// Mode selection component
const ModeSelectionUI = ({
  isFullMode,
  templateName,
  onTemplateNameChange,
  isTemplateNameEmpty,
  modes,
  emailCreateMode,
  onChange,
  EmailLayout,
  modeContent,
  useFileUpload,
  uploadButtonLabel,
}) => (
  <>
    {isFullMode && (
      <CapInput
        label={<FormattedMessage {...messages.creativeName} />}
        onChange={onTemplateNameChange}
        value={templateName}
        labelPosition="top"
        size="default"
        style={{ width: '68%' }}
      />
    )}
    <CardContainer>
      <CapRadioCardWithLabel
        style={{ marginLeft: '-6px'}}
        panes={modes}
        onChange={onChange}
        selected={emailCreateMode}
        label={<FormattedMessage {...messages.editorType} />}
      />
    </CardContainer>
    <>
      {emailCreateMode === EMAIL_CREATE_MODES.UPLOAD && (
        <div>
          <CapUploader onChange={useFileUpload} accept=".zip, .html, .htm" showUploadList={false}>
            {(isFullMode && isTemplateNameEmpty) && (
              <CapError type="error">
                <FormattedMessage {...messages.emptyTemplateName} />
              </CapError>
            )}
            <CapButton disabled={isFullMode && isTemplateNameEmpty}>
              {uploadButtonLabel}
            </CapButton>
          </CapUploader>
          {!isEmpty(EmailLayout) && (
            <>{get(modeContent, "file.name")}</>
          )}
        </div>
      )}
    </>
  </>
);

ModeSelectionUI.propTypes = {
  isFullMode: PropTypes.bool,
  templateName: PropTypes.string,
  onTemplateNameChange: PropTypes.func.isRequired,
  isTemplateNameEmpty: PropTypes.bool,
  modes: PropTypes.array.isRequired,
  emailCreateMode: PropTypes.string,
  onChange: PropTypes.func.isRequired,
  EmailLayout: PropTypes.object,
  modeContent: PropTypes.object,
  useFileUpload: PropTypes.func.isRequired,
  uploadButtonLabel: PropTypes.node.isRequired,
};

// Content creation component
const ContentCreationUI = ({
  isShowEmailCreate,
  emailProps,
  cmsTemplatesProps,
  isHTMLEditorMode,
  htmlEditorProps,
}) => {
  
  return (
    <>
      {isShowEmailCreate ? (
        isHTMLEditorMode ? (
          <EmailHTMLEditor {...htmlEditorProps} />
        ) : (
          <EmailWithoutSaga {...emailProps} />
        )
      ) : (
        <CmsTemplatesComponent {...cmsTemplatesProps} />
      )}
    </>
  );
};

ContentCreationUI.propTypes = {
  isShowEmailCreate: PropTypes.bool.isRequired,
  emailProps: PropTypes.object.isRequired,
  cmsTemplatesProps: PropTypes.object.isRequired,
  isHTMLEditorMode: PropTypes.bool,
  htmlEditorProps: PropTypes.object,
};

// Main EmailWrapper presentational component
const EmailWrapperView = ({
  isUploading,
  emailCreateMode,
  step,
  isFullMode,
  templateName,
  onTemplateNameChange,
  isTemplateNameEmpty,
  modes,
  onChange,
  EmailLayout,
  modeContent,
  useFileUpload,
  uploadButtonLabel,
  isShowEmailCreate,
  emailProps,
  cmsTemplatesProps,
  metaEntities,
  loadingTags,
  injectedTags,
  globalActions,
  supportedTags,
  getDefaultTags,
  location,
  currentOrgDetails,
  forwardedTags,
  selectedOfferDetails,
  eventContextTags,
  waitEventContextTags,
  getFormdata,
  isGetFormData,
  getLiquidTags,
  showLiquidErrorInFooter,
  onValidationFail,
  emailActions,
  Email,
  templateData: templateDataProp,
  params,
  isEditEmail = true,
  fetchingLiquidTags,
  createTemplateInProgress,
  fetchingCmsData,
  setIsLoadingContent,
  showTestAndPreviewSlidebox,
  handleCloseTestAndPreview,
  showTemplateName,
  onHtmlEditorValidationStateChange,
  moduleType,
}) => {
  const htmlEditorRef = useRef(null);
  const supportCKEditor = hasSupportCKEditor();
  const hasParamsIdForEditor = params?.id || location?.query?.id || location?.params?.id || location?.pathname?.includes('/edit/');
  const isEditModeForEditor = hasParamsIdForEditor;
  const isBEEFromProps = emailProps?.editor === 'BEE' && emailProps?.selectedEditorMode === null;
  const isDragDropFromCreateMode = emailCreateMode === EMAIL_CREATE_MODES.DRAG_DROP;
  const isExplicitlyBEEEditor = isBEEFromProps || isDragDropFromCreateMode;
  let isHTMLEditorMode = false;

  if (supportCKEditor) {
    // UPLOAD mode should use Email component (CKEditor), NOT HTML editor
    // This ensures consistency between create and edit flows when SUPPORT_CK_EDITOR is enabled
    isHTMLEditorMode = false; // Always use Email component (CKEditor) in legacy flow
  } else if (isEditModeForEditor) {
    isHTMLEditorMode = !isExplicitlyBEEEditor;
  } else {
    if (isExplicitlyBEEEditor || isBEEFromProps || isDragDropFromCreateMode) {
      isHTMLEditorMode = false;
    } else {
      isHTMLEditorMode = emailProps?.selectedEditorMode === EMAIL_CREATE_MODES.HTML_EDITOR ||
        emailCreateMode === EMAIL_CREATE_MODES.HTML_EDITOR;
    }
  }

  const isShowTemplateSelection = step === STEPS.MODE_SELECTION;

  // Create onFormDataChange callback for template name updates (similar to Email component)
  // This allows CreativesContainer to update the template name when user clicks "Edit name"
  // When user edits the name in CreativesContainer header, it calls this callback
  // which updates the template name in EmailWrapper, and then CreativesContainer
  // will call showTemplateName again with the updated formData
  const handleFormDataChange = useCallback((updatedFormData) => {
    const newTemplateName = updatedFormData?.['template-name'] || templateName;
    if (newTemplateName !== templateName && onTemplateNameChange) {
      // Update template name in parent (useEmailWrapper hook)
      onTemplateNameChange({ target: { value: newTemplateName } });
    }
    // Note: CreativesContainer will call showTemplateName again after this callback
    // (it stores the callback in templateContainerDetails and calls it after state updates)
  }, [templateName, onTemplateNameChange]);

  const htmlEditorProps = isHTMLEditorMode ? {
    // Location and params
    location,
    params,
    // Tag-related props
    getDefaultTags,
    supportedTags,
    metaEntities,
    injectedTags,
    globalActions,
    loadingTags,
    eventContextTags,
    waitEventContextTags,
    forwardedTags,
    selectedOfferDetails,
    currentOrgDetails,
    // Email Redux state and actions
    Email,
    emailActions,
    // Full mode props
    isFullMode,
    templateName,
    isGetFormData,
    getFormdata,
    // Library mode props
    templateData: templateDataProp,
    isEditEmail,
    // Uploaded content from zip file
    EmailLayout,
    // Liquid validation
    getLiquidTags,
    showLiquidErrorInFooter,
    // Validation state callback
    onHtmlEditorValidationStateChange,
    onValidationFail,
    // Template name
    showTemplateName,
    onFormDataChange: handleFormDataChange,
    // Module type for unsubscribe tag validation
    moduleType,
    // Loading states
    fetchingLiquidTags: fetchingLiquidTags || false,
    createTemplateInProgress: createTemplateInProgress || false,
    fetchingCmsData: fetchingCmsData || false,
    // Parent loading control
    setIsLoadingContent,
    ref: htmlEditorRef,
  } : {};

  // Get formData for TestAndPreviewSlidebox when needed
  const getFormDataForPreview = () => {
    if (htmlEditorRef.current && htmlEditorRef.current.getFormDataForPreview) {
      return htmlEditorRef.current.getFormDataForPreview();
    }
    return {};
  };

  const getContentForPreview = () => {
    if (htmlEditorRef.current && htmlEditorRef.current.getContentForPreview) {
      return htmlEditorRef.current.getContentForPreview();
    }
    return '';
  };

  return (
    <>
      <CapSpin spinning={emailCreateMode === EMAIL_CREATE_MODES.UPLOAD ? isUploading : false}>
        {isShowTemplateSelection ? (
          <ModeSelectionUI
            isFullMode={isFullMode}
            templateName={templateName}
            onTemplateNameChange={onTemplateNameChange}
            isTemplateNameEmpty={isTemplateNameEmpty}
            modes={modes}
            emailCreateMode={emailCreateMode}
            onChange={onChange}
            EmailLayout={EmailLayout}
            modeContent={modeContent}
            useFileUpload={useFileUpload}
            uploadButtonLabel={uploadButtonLabel}
          />
        ) : (
          <ContentCreationUI
            isShowEmailCreate={isShowEmailCreate}
            emailProps={emailProps}
            cmsTemplatesProps={cmsTemplatesProps}
            isHTMLEditorMode={isHTMLEditorMode}
            htmlEditorProps={htmlEditorProps}
          />
        )}
      </CapSpin>
      {/* Render TestAndPreviewSlidebox for HTML Editor (similar to legacy Email component) */}
      {isHTMLEditorMode && showTestAndPreviewSlidebox && (
        <TestAndPreviewSlidebox
          show={showTestAndPreviewSlidebox}
          onClose={handleCloseTestAndPreview}
          formData={getFormDataForPreview()}
          content={getContentForPreview()}
          currentChannel={EMAIL}
          currentTab={1}
        />
      )}
    </>
  );
};

EmailWrapperView.propTypes = {
  isUploading: PropTypes.bool,
  emailCreateMode: PropTypes.string,
  step: PropTypes.string,
  isFullMode: PropTypes.bool,
  getFormdata: PropTypes.func,
  isGetFormData: PropTypes.bool,
  getLiquidTags: PropTypes.func,
  showLiquidErrorInFooter: PropTypes.func,
  templateName: PropTypes.string,
  onTemplateNameChange: PropTypes.func.isRequired,
  isTemplateNameEmpty: PropTypes.bool,
  modes: PropTypes.array.isRequired,
  onChange: PropTypes.func.isRequired,
  EmailLayout: PropTypes.object,
  modeContent: PropTypes.object,
  useFileUpload: PropTypes.func.isRequired,
  uploadButtonLabel: PropTypes.node.isRequired,
  isShowEmailCreate: PropTypes.bool.isRequired,
  emailProps: PropTypes.object.isRequired,
  cmsTemplatesProps: PropTypes.object.isRequired,
  metaEntities: PropTypes.object,
  loadingTags: PropTypes.bool,
  injectedTags: PropTypes.object,
  globalActions: PropTypes.object,
  supportedTags: PropTypes.array,
  getDefaultTags: PropTypes.string,
  location: PropTypes.object,
  currentOrgDetails: PropTypes.object,
  forwardedTags: PropTypes.object,
  selectedOfferDetails: PropTypes.array,
  eventContextTags: PropTypes.array,
  waitEventContextTags: PropTypes.object,
  emailActions: PropTypes.object,
  Email: PropTypes.object,
  templateData: PropTypes.object,
  params: PropTypes.object,
  isEditEmail: PropTypes.bool,
  fetchingLiquidTags: PropTypes.bool,
  createTemplateInProgress: PropTypes.bool,
  fetchingCmsData: PropTypes.bool,
  setIsLoadingContent: PropTypes.func,
  showTestAndPreviewSlidebox: PropTypes.bool,
  handleCloseTestAndPreview: PropTypes.func,
};

export default EmailWrapperView;