import React from 'react';
import { FormattedMessage } from 'react-intl';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import CapButton from '@capillarytech/cap-ui-library/CapButton';
import CapError from '@capillarytech/cap-ui-library/CapError';
import PropTypes from 'prop-types';
import messages from './messages';
import ErrorInfoNote from '../../v2Components/ErrorInfoNote';
import { PREVIEW, EMAIL, SMS, EDIT_TEMPLATE, MOBILE_PUSH } from './constants';
import { EMAIL_CREATE_MODES } from '../EmailWrapper/constants';
import { hasSupportCKEditor } from '../../utils/common';
import { getMessageForDevice, getTitleForDevice } from '../../utils/commonUtils';

function getFullModeSaveBtn(slidBoxContent, isCreatingTemplate) {
  if (isCreatingTemplate) {
    return <FormattedMessage {...messages.creativesTemplatesDone} />;
  }
  return slidBoxContent === EDIT_TEMPLATE
    ? <FormattedMessage {...messages.creativesTemplatesUpdate} />
    : <FormattedMessage {...messages.creativesTemplatesSaveFullMode} />;
}
function SlideBoxFooter(props) {
  const {
    slidBoxContent,
    onSave,
    onEditTemplate,
    isTemplateArchived,
    onCreateNextStep,
    isFullMode,
    fetchingCmsData,
    isTemplateNameEmpty,
    errorMessages,
    // eslint-disable-next-line no-unused-vars
    isLiquidValidationError, // Legacy prop, kept for PropTypes compatibility
    currentTab,
    onTestAndPreview,
    // isEmptyContent,
    showTestAndPreviewButton,
    shouldShowDoneFooter,
    shouldShowContinueFooter,
    isContinueButtonDisabled,
    continueButtonLabel,
    htmlEditorValidationState,
    isCreatingTemplate,
    currentChannel,
    emailCreateMode,
    selectedEmailCreateMode,
    restrictPersonalization = false,
    isAnonymousType = false,
    templateData = {},
    hasPersonalizationTokenError: hasPersonalizationTokenErrorProp = false,
  } = props;
  // Calculate if buttons should be disabled
  // Only apply validation state checks for EMAIL channel in HTML Editor mode (not BEE/DragDrop)
  // For other channels, BEE editor, or when htmlEditorValidationState is not provided, don't disable based on validation
  const isEmailChannel = currentChannel?.toUpperCase() === EMAIL;
  const isSmsChannel = currentChannel?.toUpperCase() === SMS;
  // Use templateData.type in library/edit so footer shows when editing a mobile push template (currentChannel may not be set to template channel)
  const isMobilePushChannel =
    currentChannel?.toUpperCase() === MOBILE_PUSH ||
    (templateData?.type && templateData.type.toUpperCase() === MOBILE_PUSH);
  const isEditMode = slidBoxContent === EDIT_TEMPLATE;

  // Use selectedEmailCreateMode for accurate mode detection in create mode (emailCreateMode is mapped for backwards compatibility)
  // In edit mode: htmlEditorValidationState is initialized as {} but only updated by HTML Editor
  // If it's still in initial state (validationComplete === false, issueCounts.total === 0), it's BEE editor
  // Upload mode also uses HTML Editor, so include it in HTML Editor mode check
  const isUploadMode = emailCreateMode === EMAIL_CREATE_MODES.UPLOAD;
  const isHTMLEditorModeInCreate = selectedEmailCreateMode === EMAIL_CREATE_MODES.HTML_EDITOR || isUploadMode;
  // In edit mode: Check if htmlEditorValidationState has been updated by HTML Editor
  // HTML Editor will call updateHtmlEditorValidationState, setting validationComplete to true at some point
  // If validationComplete is false and issueCounts.total === 0, it's likely still in initial state (BEE editor)
  const isHtmlEditorValidationStateActive = htmlEditorValidationState && (
    htmlEditorValidationState.validationComplete === true
    || (htmlEditorValidationState.issueCounts && htmlEditorValidationState.issueCounts.total > 0)
    || htmlEditorValidationState.hasErrors === true
  );
  const isHTMLEditorModeInEdit = isEditMode && isHtmlEditorValidationStateActive;
  const isHTMLEditorMode = isHTMLEditorModeInCreate || isHTMLEditorModeInEdit;

  // BEE editor detection: drag_drop mode OR (editor mode AND not HTML Editor)
  // In edit mode: if htmlEditorValidationState is in initial state (not updated by HTML Editor), it's BEE editor
  const isBEEEditor = selectedEmailCreateMode === EMAIL_CREATE_MODES.DRAG_DROP
    || (emailCreateMode === EMAIL_CREATE_MODES.EDITOR && !isHTMLEditorMode)
    || (isEditMode && !isHtmlEditorValidationStateActive);
  const isSupportCKEditor = hasSupportCKEditor();
  // Only check validation for HTML Editor mode, not for BEE/DragDrop editor
  // In upload mode the legacy Email (CK) component does not report validation state, so do not disable buttons
  const shouldCheckValidation = isEmailChannel && htmlEditorValidationState && isHTMLEditorMode && !isBEEEditor && !isSupportCKEditor;
  const isContentEmpty = shouldCheckValidation ? (htmlEditorValidationState?.isContentEmpty ?? true) : false;
  // Check if validation has completed
  const validationComplete = shouldCheckValidation ? (htmlEditorValidationState?.validationComplete ?? false) : true;
  // Only Rule Group #1 (Input & Sanitization) blocks; hasErrors is set by HTMLEditor from hasBlockingErrors.
  // hasErrors should always be set (defaults to false), so we only check for explicit true value.
  // Warnings (label issues, HTML/CSS compatibility) do NOT block buttons.
  const hasValidationErrors = shouldCheckValidation && htmlEditorValidationState?.hasErrors === true;
  const errorsAcknowledged = shouldCheckValidation ? (htmlEditorValidationState?.errorsAcknowledged ?? false) : true;

  // IMPORTANT: In both modes, if validation finds errors, buttons must stay disabled until user acknowledges by clicking redirection icon
  let shouldDisableButtons = false;
  if (shouldCheckValidation) {
    if (isEditMode) {
      // Edit mode: Disable if validation has completed AND found errors AND errors not acknowledged
      shouldDisableButtons = validationComplete && hasValidationErrors && !errorsAcknowledged;
    } else {
      // Create mode:
      // 1. Disable until validation completes
      // 2. Disable if content is empty
      // 3. Disable if validation finds errors AND errors not acknowledged (user must click redirection icon)
      shouldDisableButtons = !validationComplete || isContentEmpty || (hasValidationErrors && !errorsAcknowledged);
    }
  }

  // Show ErrorInfoNote for API validation errors (from validateLiquidTemplateContent)
  // For HTML Editor: API validation errors are shown in ValidationErrorDisplay (inside CodeEditorPane), not here
  const hasStandardErrors = errorMessages && errorMessages.STANDARD_ERROR_MSG && errorMessages.STANDARD_ERROR_MSG.length > 0;
  const hasLiquidErrors = errorMessages && errorMessages.LIQUID_ERROR_MSG && errorMessages.LIQUID_ERROR_MSG.length > 0;

  // Check if htmlEditorValidationState has actual validation errors
  // If htmlEditorValidationState exists but has no errors (total === 0), and we have STANDARD/LIQUID errors,
  // then those errors are from BEE editor (FormBuilder validation), not HTML Editor
  const htmlEditorHasErrors = htmlEditorValidationState && htmlEditorValidationState.issueCounts && htmlEditorValidationState.issueCounts.total > 0;

  // BEE editor errors: We have STANDARD/LIQUID errors AND either:
  // 1. No htmlEditorValidationState exists, OR
  // 2. htmlEditorValidationState exists but has no actual errors (meaning errors are from FormBuilder/BEE editor)
  // IMPORTANT: Only check for BEE editor errors when NOT in HTML Editor mode (upload or html_editor)
  // Upload mode uses HTML Editor, so BEE editor errors don't apply
  // IMPORTANT: BEE editor doesn't have real-time content updates,
  // so we should NOT disable buttons based on validation errors
  // In edit mode: Check if htmlEditorValidationState is in initial state (not updated by HTML Editor)
  // In edit mode with BEE editor, htmlEditorValidationState will remain in initial state
  // In create mode, check selectedEmailCreateMode or emailCreateMode
  const isBEEEditorModeInEdit = isEditMode && !isHtmlEditorValidationStateActive;
  const isBEEEditorModeInCreate = !isHTMLEditorMode && !isEditMode;
  const isBEEEditorMode = isBEEEditorModeInEdit || isBEEEditorModeInCreate;
  const hasBEEEditorErrors = isEmailChannel && isBEEEditorMode && (hasStandardErrors || hasLiquidErrors) && (!htmlEditorValidationState || !htmlEditorHasErrors);
  const hasSmsValidationErrors = isSmsChannel && (hasStandardErrors || hasLiquidErrors);
  // Mobile Push OLD: footer only for extractTags/Aira liquid errors, not standard tag errors
  const hasMobilePushValidationErrors = isMobilePushChannel && hasLiquidErrors;

  const shouldShowErrorInfoNote = hasBEEEditorErrors || hasSmsValidationErrors || hasMobilePushValidationErrors || isSupportCKEditor;

  // Check for personalization tokens in title/message when anonymous user tries to save
  const hasPersonalizationTokens = () => {
    if (!isAnonymousType || !templateData) return false;

    const androidTitle = getTitleForDevice(templateData, 'ANDROID') || '';
    const iosTitle = getTitleForDevice(templateData, 'IOS') || '';
    const androidMessageBody = getMessageForDevice(templateData, 'ANDROID') || '';
    const iosMessageBody = getMessageForDevice(templateData, 'IOS') || '';
    // Check for personalization tags {{ }} in title or message body
    const contentToCheck = `${androidTitle} ${iosTitle} ${androidMessageBody} ${iosMessageBody}`;
    // Check for liquid tags {{ }}
    if (contentToCheck.includes('{{') && contentToCheck.includes('}}')) {
      return true;
    }
    // Check for event context tags [
    if (contentToCheck.includes('[') && contentToCheck.includes(']')) {
      return true;
    }
    return false;
  };

  // Use prop from parent (FormBuilder flow) when available; else fall back to templateData check
  const hasPersonalizationTokenError = hasPersonalizationTokenErrorProp === true || (restrictPersonalization && hasPersonalizationTokens());

  return (
    <div className="template-footer-width">
      {shouldShowErrorInfoNote && (
        <ErrorInfoNote
          errorMessages={errorMessages}
          currentTab={currentTab?.toUpperCase()}
          useLegacyDisplay // Use simple list display for BEE Editor (not tabbed interface)
        />
      )}
      <div>
        {shouldShowDoneFooter() && (
          <div>
            {isFullMode && isTemplateNameEmpty && (
              <CapError type="error">
                <FormattedMessage {...messages.templateNameEmpty} />
              </CapError>
            )}
            <CapRow>
              <CapButton
                onClick={onSave}
                disabled={isTemplateNameEmpty || fetchingCmsData || shouldDisableButtons || hasPersonalizationTokenError}
              >
                {isFullMode ? (
                  getFullModeSaveBtn(slidBoxContent, isCreatingTemplate)
                ) : (
                  <FormattedMessage {...messages.creativesTemplatesSave} />
                )}
              </CapButton>
              {showTestAndPreviewButton && (
                <CapButton
                  type="secondary"
                  onClick={onTestAndPreview}
                  disabled={shouldDisableButtons || hasPersonalizationTokenError}
                  style={{ marginLeft: '8px' }}
                >
                  <FormattedMessage {...messages.testAndPreview} />
                </CapButton>
              )}
            </CapRow>
            {/* {isFullMode && <CapButton type="secondary" onClick={onDiscard}><FormattedMessage {...messages.creativesTemplatesDiscard}/></CapButton>} */}
          </div>
        )}
        {shouldShowContinueFooter() && (
          <CapButton
            onClick={onCreateNextStep}
            disabled={isContinueButtonDisabled || false}
          >
            <FormattedMessage {...(continueButtonLabel || messages.continue)} />
          </CapButton>
        )}
        {slidBoxContent === PREVIEW && !isTemplateArchived && (
          <CapButton onClick={onEditTemplate} type="secondary">
            <FormattedMessage {...messages.creativesTemplatesEdit} />
          </CapButton>
        )}
      </div>
    </div>
  );
}
SlideBoxFooter.propTypes = {
  slidBoxContent: PropTypes.node,
  onSave: PropTypes.func,
  onEditTemplate: PropTypes.func,
  isTemplateArchived: PropTypes.bool,
  onCreateNextStep: PropTypes.func,
  shouldShowContinueFooter: PropTypes.func,
  shouldShowDoneFooter: PropTypes.func,
  isFullMode: PropTypes.bool,
  fetchingCmsData: PropTypes.bool,
  isTemplateNameEmpty: PropTypes.bool,
  errorMessages: PropTypes.array,
  isLiquidValidationError: PropTypes.bool,
  currentTab: PropTypes.string,
  onTestAndPreview: PropTypes.func,
  isEmptyContent: PropTypes.bool,
  showTestAndPreviewButton: PropTypes.bool,
  isContinueButtonDisabled: PropTypes.bool,
  continueButtonLabel: PropTypes.object,
  htmlEditorValidationState: PropTypes.shape({
    isContentEmpty: PropTypes.bool,
    issueCounts: PropTypes.shape({
      html: PropTypes.number,
      label: PropTypes.number,
      liquid: PropTypes.number,
      total: PropTypes.number,
    }),
    validationComplete: PropTypes.bool,
    /** Only Rule Group #1 (Input & Sanitization) blocks; warnings do not block */
    hasErrors: PropTypes.bool,
  }),
  isCreatingTemplate: PropTypes.bool,
  currentChannel: PropTypes.string,
  emailCreateMode: PropTypes.string,
  selectedEmailCreateMode: PropTypes.string,
  restrictPersonalization: PropTypes.bool,
  isAnonymousType: PropTypes.bool,
  templateData: PropTypes.object,
  formData: PropTypes.array,
  hasPersonalizationTokenError: PropTypes.bool,
};

SlideBoxFooter.defaultProps = {
  slidBoxContent: '',
  onSave: () => {},
  onEditTemplate: () => {},
  onCreateNextStep: () => {},
  shouldShowContinueFooter: () => {},
  shouldShowDoneFooter: () => {},
  isFullMode: false,
  fetchingCmsData: false,
  isTemplateNameEmpty: false,
  errorMessages: [],
  isLiquidValidationError: false,
  currentTab: '',
  onTestAndPreview: () => {},
  isEmptyContent: false,
  showTestAndPreviewButton: false,
  isContinueButtonDisabled: false,
  continueButtonLabel: {},
  htmlEditorValidationState: {},
  isCreatingTemplate: false,
  currentChannel: '',
  emailCreateMode: '',
  selectedEmailCreateMode: '',
  formData: [],
  hasPersonalizationTokenError: false,
};
export default SlideBoxFooter;
