import React, {
  useState, useEffect, useMemo, useCallback, useRef,
} from 'react';
import isEmpty from 'lodash/isEmpty';
import find from 'lodash/find';
import get from 'lodash/get';
import { GA } from '@capillarytech/cap-ui-utils';
import CapNotification from '@capillarytech/cap-ui-library/CapNotification';
import CapIcon from '@capillarytech/cap-ui-library/CapIcon';
import { CHANNEL_CREATE_TRACK_MAPPING, BEE_PLUGIN } from '../../App/constants';
import { gtmPush } from '../../../utils/gtmTrackers';
import { EMAIL } from '../../CreativesContainer/constants';
import messages from '../messages';
import { STEPS, EMAIL_CREATE_MODES } from '../constants';
import { containsBase64Images } from '../../../utils/content';
import { hasSupportCKEditor } from '../../../utils/common';


/**
 * Custom hook to handle EmailWrapper component business logic
 */
const useEmailWrapper = ({
  intl: { formatMessage },
  onEmailModeChange,
  emailCreateMode,
  step,
  EmailLayout,
  CmsTemplates,
  SelectedEdmDefaultTemplate,
  isUploading,
  templatesActions,
  showNextStep,
  onResetStep,
  onEnterTemplateName,
  onRemoveTemplateName,
  getCmsTemplatesInProgress,
  // Props for Email component
  setIsLoadingContent,
  isGetFormData,
  getFormdata,
  type,
  isFullMode,
  cap,
  showTemplateName,
  showLiquidErrorInFooter,
  onValidationFail,
  forwardedTags,
  selectedOfferDetails,
  onPreviewContentClicked,
  onTestContentClicked,
  editor,
  moduleType,
  eventContextTags,
  waitEventContextTags,
  isLoyaltyModule,
  // Props for CmsTemplates component
  cmsTemplatesLoader,
  currentOrgDetails,
  // Props for Test and Preview Slidebox
  showTestAndPreviewSlidebox,
  handleTestAndPreview,
  handleCloseTestAndPreview,
  isTestAndPreviewMode,
  // Props for BEE enabled check
  location,
  emailActions,
  Email,
  templateData,
  params,
  isEditEmail = true,
}) => {
  // State management
  const [templateName, setTemplateName] = useState('');
  const [isTemplateNameEmpty, setIsTemplateNameEmpty] = useState(true);
  const [selectedCreateMode, setSelectedCreateMode] = useState('');
  const [modeContent, setModeContent] = useState({});
  const [isBeeEditorEnabled, setIsBeeEditorEnabled] = useState(null); // null = not checked yet, true/false = checked
  const beeStatusCheckRef = useRef(false); // Track if we've made the API call for current step
  const defaultTemplatesFetchedRef = useRef(false);
  const beeTemplateSetRef = useRef(false); // Track if we've set BEETemplate for current template
  const [routeParams] = useState({
    pathname: `/email/create`,
    query: { module: 'library', type: 'embedded' },
  });

  // Cleanup effect
  useEffect(() => () => {
    onResetStep();
    templatesActions.resetTemplateData();
  }, [onResetStep, templatesActions]);

  // Event handlers
  const onTemplateNameChange = useCallback(({ target: { value } }) => {
    const isEmptyTemplateName = !value?.trim();
    setTemplateName(value);
    setIsTemplateNameEmpty(isEmptyTemplateName);

    if (value && onEnterTemplateName) {
      onEnterTemplateName();
    } else if (onRemoveTemplateName) {
      onRemoveTemplateName();
    }
  }, [onEnterTemplateName, onRemoveTemplateName]);

  useEffect(() => () => {
    emailActions.clearStoreValues();
  }, []);

  // Check BEE enabled status from API response
  // BEE is enabled if isDragDrop is true in the API response
  // This should work for both full mode and library mode
  const checkBeeEditorEnabled = useCallback(() => {
    // IMPORTANT: Always use API response when available, regardless of mode
    // This ensures consistent behavior across full mode and library mode
    // The API response represents whether BEE is enabled for the organization
    if (isBeeEditorEnabled !== null) {
      return isBeeEditorEnabled;
    }
    // If we haven't checked yet, return false (disabled) until API responds
    // Note: In full mode, BEE might still be allowed for UI purposes (editor selection),
    // but for API calls (isBEEAppEnable), we should use the actual org setting
    return false;
  }, [isBeeEditorEnabled]);

  // Helper function to convert numeric templateStep to string step
  const getStepFromTemplateStep = useCallback((templateStepValue) => {
    // templateStep is numeric: 1 = modeSelection, 2 = templateSelection, 3 = createTemplateContent
    if (typeof templateStepValue === 'number') {
      switch (templateStepValue) {
        case 1:
          return STEPS.MODE_SELECTION;
        case 2:
          return STEPS.TEMPLATE_SELECTION;
        case 3:
          return STEPS.CREATE_TEMPLATE_CONTENT;
        default:
          return STEPS.MODE_SELECTION;
      }
    }
    // If it's already a string, return as-is
    return templateStepValue || STEPS.MODE_SELECTION;
  }, []);

  // Convert step to string format if it's numeric
  const currentStep = useMemo(() => getStepFromTemplateStep(step), [step, getStepFromTemplateStep]);

  // Effect to check BEE enabled status via new API when entering MODE_SELECTION step or edit mode
  useEffect(() => {
    const supportCKEditor = hasSupportCKEditor();
    // Only check BEE enabled status for new flow (when supportCKEditor is false)
    // Reset the ref when step changes to MODE_SELECTION to allow API call
    if (currentStep === STEPS.MODE_SELECTION) {
      beeStatusCheckRef.current = false;
    }

    // Check if we're in edit mode (need to check BEE status for editor selection)
    const hasParamsId = params?.id || location?.query?.id || location?.params?.id || location?.pathname?.includes('/edit/');
    const isEditMode = hasParamsId;

    // Only check BEE enabled status for new flow (when supportCKEditor is false)
    // Call API in MODE_SELECTION step OR in edit mode (if not already called)
    // Check all conditions
    const shouldMakeCall = !supportCKEditor
      && (currentStep === STEPS.MODE_SELECTION || isEditMode)
      && !beeStatusCheckRef.current
      && emailActions;

    if (shouldMakeCall) {
      // Mark that we've made the API call
      beeStatusCheckRef.current = true;

      // Make API call to check BEE enabled status using new endpoint
      emailActions.getCmsAccounts('BEE_PLUGIN');
    }
  }, [currentStep, emailActions, params?.id, location?.query?.id, location?.params?.id, location?.pathname]);

  // Effect to update isBeeEditorEnabled based on new API response
  // This effect watches for isBeeEnabled from the new API response
  useEffect(() => {
    // Process API response regardless of step (needed for edit mode editor selection)
    // Also check if we've made the API call (beeStatusCheckRef.current === true)
    if (beeStatusCheckRef.current) {
      // Use isBeeEnabled from the new API response
      if (Email?.isBeeEnabled !== undefined && Email?.isBeeEnabled !== null) {
        setIsBeeEditorEnabled(Email.isBeeEnabled);
      }
    }
    // If API call fails, treat as disabled
    if (Email?.fetchingCmsAccountsError && beeStatusCheckRef.current) {
      setIsBeeEditorEnabled(false);
    }
  }, [Email?.isBeeEnabled, Email?.fetchingCmsAccountsError]);

  // Effect to fetch template details when in edit mode
  // This ensures template data is loaded so editor type can be determined correctly
  useEffect(() => {
    const supportCKEditor = hasSupportCKEditor();
    if (supportCKEditor) {
      // Legacy flow: Email component handles getTemplateDetails
      return;
    }

    // New flow: Fetch template details only when editing (not when creating)
    if (!isEditEmail) {
      return;
    }
    const hasParamsId = params?.id || location?.query?.id || location?.params?.id || location?.pathname?.includes('/edit/');
    const hasTemplateDetails = Email?.templateDetails && !isEmpty(Email.templateDetails);
    const hasTemplateDataProp = templateData && !isEmpty(templateData);
    const isTemplateLoading = Email?.getTemplateDetailsInProgress;

    // Only fetch if we have an ID, don't have template data yet, and not already loading
    if (hasParamsId && !hasTemplateDetails && !hasTemplateDataProp && !isTemplateLoading && emailActions?.getTemplateDetails) {
      let templateId = params?.id || location?.query?.id || location?.params?.id;
      if (!templateId && location?.pathname?.includes('/edit/')) {
        const [, extractedId] = location.pathname.match(/\/edit\/([^/]+)/) || [];
        if (extractedId) templateId = extractedId;
      }
      if (templateId) {
        emailActions.getTemplateDetails(templateId, 'email');
      }
    }
  }, [isEditEmail, params?.id, location?.query?.id, location?.params?.id, location?.pathname, Email?.templateDetails, Email?.getTemplateDetailsInProgress, templateData, emailActions]);

  // Effect to set BEETemplate when template details are loaded for BEE templates
  // This ensures Email component can properly initialize BEE editor
  useEffect(() => {
    const supportCKEditor = hasSupportCKEditor();
    if (supportCKEditor) {
      // Legacy flow: Email component handles this
      return;
    }

    // New flow: When template details are loaded and it's a BEE template, set it in Templates.BEETemplate
    // This allows Email component to properly initialize and call getCmsSetting
    const hasTemplateDetails = Email?.templateDetails && !isEmpty(Email.templateDetails);
    // Note: We check Email?.BEETemplate as a proxy, but the actual BEETemplate is in Templates reducer
    // The Email component will detect it via this.props.Templates.BEETemplate
    const hasBEETemplate = Email?.BEETemplate && !isEmpty(Email.BEETemplate);

    if (hasTemplateDetails && !hasBEETemplate && templatesActions?.setBEETemplate && !beeTemplateSetRef.current) {
      // Check if it's a BEE template
      const editTemplateData = Email.templateDetails;
      const getIsDragDrop = (data) => {
        if (!data) return false;
        const baseDragDrop = get(data, 'versions.base.is_drag_drop', false);
        if (baseDragDrop === true || baseDragDrop === 1) return true;
        const activeTab = get(data, 'versions.base.activeTab', 'en');
        const activeTabDragDrop = get(data, `versions.base.${activeTab}.is_drag_drop`, false);
        if (activeTabDragDrop === true || activeTabDragDrop === 1) return true;
        const baseLevelDragDrop = get(data, 'base.is_drag_drop', false);
        if (baseLevelDragDrop === true || baseLevelDragDrop === 1) return true;
        const rootDragDrop = get(data, 'is_drag_drop', false);
        if (rootDragDrop === true || rootDragDrop === 1) return true;
        return false;
      };

      const isDragDrop = getIsDragDrop(editTemplateData);
      // If it's a BEE template, set it in Templates.BEETemplate
      if (isDragDrop) {
        beeTemplateSetRef.current = true;
        templatesActions.setBEETemplate(editTemplateData);

        // Also call getCmsSetting directly as a fallback if Email component doesn't detect it
        // Extract drag_drop_id - check multiple possible paths
        const activeTab = get(editTemplateData, 'versions.base.activeTab', 'en');
        const activeTabData = get(editTemplateData, `versions.base.${activeTab}`, {});
        const dragDropId = activeTabData.drag_drop_id
          || activeTabData.id
          || get(editTemplateData, 'versions.base.drag_drop_id')
          || get(editTemplateData, 'versions.base.id')
          || editTemplateData._id;

        const isBEESupport = (location?.query?.isBEESupport !== "false") || false;
        // IMPORTANT: isBEEAppEnable should be consistent across full mode and library mode
        // It represents whether BEE is enabled for the organization, not the mode
        // This ensures the same template behaves the same way in both modes
        const isBEEAppEnable = checkBeeEditorEnabled();
        // Check if we're in edit mode - check multiple sources for id
        const hasParamsId = params?.id
          || location?.query?.id
          || location?.params?.id
          || (location?.pathname && location.pathname.includes('/edit/'));
        const cmsMode = hasParamsId ? 'open' : 'create';
        // Extract langId from active tab
        const activeTabForLang = get(editTemplateData, 'versions.base.activeTab', 'en');

        // Call getCmsSetting if emailActions is available
        // Note: This is a fallback - the Email component should also call it in componentWillReceiveProps
        if (emailActions?.getCmsSetting) {
          emailActions.getCmsSetting(BEE_PLUGIN, dragDropId, cmsMode, activeTabForLang, isBEESupport, isBEEAppEnable);
        } else {
          console.warn('[useEmailWrapper] emailActions.getCmsSetting not available');
        }
      }
    }

    // Reset ref when template changes (template details cleared)
    if (!hasTemplateDetails && beeTemplateSetRef.current) {
      beeTemplateSetRef.current = false;
    }
  }, [Email?.templateDetails, Email?.BEETemplate, Email?.getTemplateDetailsInProgress, Email?.fetchingCmsSettings, templatesActions, emailActions, params?.id, location?.query, checkBeeEditorEnabled, isFullMode]);

  const onChange = useCallback((e) => {
    const { target: { value } } = e;
    // Prevent selection if Drag & Drop is selected but BEE editor is not enabled
    if (value === EMAIL_CREATE_MODES.DRAG_DROP && !checkBeeEditorEnabled()) {
      return; // Ignore selection if BEE editor is disabled
    }

    // CRITICAL: When DRAG_DROP is selected, set selectedCreateMode to DRAG_DROP
    // This ensures emailProps will have editor: 'BEE' and selectedEditorMode: null
    if (value === EMAIL_CREATE_MODES.DRAG_DROP) {
      setSelectedCreateMode(EMAIL_CREATE_MODES.DRAG_DROP);
    } else {
      setSelectedCreateMode(value);
    }

    const supportCKEditor = hasSupportCKEditor();

    // Map new modes to existing modes for backwards compatibility
    let mappedValue = value;

    if (!supportCKEditor) {
      // New flow: Handle HTML Editor, Drag & Drop, and Upload Zip
      // Don't auto-navigate - wait for Next button click
      if (value === EMAIL_CREATE_MODES.HTML_EDITOR) {
        // HTML Editor: Map to EDITOR but skip template selection
        mappedValue = EMAIL_CREATE_MODES.EDITOR;
        setModeContent({ skipTemplateSelection: true });
      } else if (value === EMAIL_CREATE_MODES.DRAG_DROP) {
        // Drag & Drop: Map to EDITOR and show template selection
        mappedValue = EMAIL_CREATE_MODES.EDITOR;
      } else if (value === EMAIL_CREATE_MODES.UPLOAD) {
        // Upload Zip: Keep as UPLOAD
        mappedValue = EMAIL_CREATE_MODES.UPLOAD;
      }
    }
    // Legacy (CK editor) flow: do not auto-navigate; user must enter template name and click Continue in footer

    onEmailModeChange(mappedValue, value); // Pass both mapped value and original selected mode
  }, [onEmailModeChange, checkBeeEditorEnabled]);

  const handleZipUploadError = useCallback(() => {
    const message = {
      key: "email-upload-error",
      message: formatMessage(messages.invalidUploadFileError2),
      description: formatMessage(messages.invalidUploadFileErrorDesc2),
    };
    CapNotification.error(message);
  }, [formatMessage]);

  const stopTimerGA = useCallback(() => {
    const timeTaken = GA.timeTracker.stopTimer(CHANNEL_CREATE_TRACK_MAPPING.email, {
      category: 'Creatives',
      action: 'Create',
      label: 'uploadZip',
    });
    gtmPush('creativeDetails', {
      channel: EMAIL,
      timeTaken,
      mode: 'uploadZip',
    });
  }, [formatMessage]);

  const handleFileUpload = useCallback((file = {}) => {
    if (!isUploading) {
      // Validate file object
      if (!file || !file.name) {
        const message = {
          key: "email-upload-error",
          message: formatMessage(messages.invalidUploadFileError),
          description: formatMessage(messages.invalidUploadFileErrorDesc3),
        };
        CapNotification.error(message);
        return;
      }

      const fileExtension = (file.name || '').split('.').pop().toLowerCase();
      const supportedZipFormats = ['zip'];

      // Converted file size to MB - added defensive check
      const fileSize = file && file.size ? (file.size / (1024 * 1024)) : 0;

      // Here fileSize is in MB
      if (fileSize > 5) {
        const message = {
          key: "email-upload-error",
          message: formatMessage(messages.invalidUploadFileError),
          description: formatMessage(messages.invalidUploadFileErrorDesc3),
        };
        CapNotification.error(message);
      } else if (supportedZipFormats.includes(fileExtension)) {
        // Verify originFileObj exists
        if (!file.originFileObj) {
          handleZipUploadError();
          return;
        }

        templatesActions.handleZipUpload(file.originFileObj, () => { // Handle upload success
          stopTimerGA();
          setModeContent({ file });
          // Do not auto-advance; user must enter template name and click Continue in footer
        }, handleZipUploadError);
      } else if (fileExtension === 'html' || fileExtension === 'htm') {
        // Verify originFileObj exists
        if (!file.originFileObj) {
          handleZipUploadError();
          return;
        }

        const reader = new FileReader();
        reader.onload = () => {
          const text = reader.result;
          // Add defensive check for empty or invalid content
          if (!text || typeof text !== 'string') {
            handleZipUploadError();
            return;
          }

          // Check for base64 images in HTML content
          containsBase64Images({content: text, CapNotification});

          setModeContent({ file });
          templatesActions.handleHtmlUpload(text);
        };
        reader.onerror = () => {
          handleZipUploadError();
        };
        reader.readAsText(file.originFileObj);
      } else {
        const message = {
          key: "email-upload-error",
          message: formatMessage(messages.invalidUploadFileError),
          description: formatMessage(messages.invalidUploadFileErrorDesc),
        };
        CapNotification.error(message);
      }
    }
  }, [isUploading, formatMessage, templatesActions, stopTimerGA, handleZipUploadError]);

  const handleEdmDefaultTemplateSelection = useCallback((id) => {
    const data = find(CmsTemplates, { _id: id });
    templatesActions.setEdmTemplate(data);
    templatesActions.setBEETemplate(data);
    // Don't override selectedCreateMode - preserve DRAG_DROP or EDITOR mode
    // Only set if not already set
    if (!selectedCreateMode) {
      setSelectedCreateMode(EMAIL_CREATE_MODES.EDITOR);
    }
  }, [CmsTemplates, templatesActions, selectedCreateMode]);

  const useFileUpload = useCallback(({ file }) => {
    setModeContent({});
    handleFileUpload(file);
  }, [handleFileUpload]);

  const useEditor = useCallback((id) => {
    setModeContent({ id });
    showNextStep();
  }, [showNextStep]);

  // Main logic effect - MOVED AFTER function declarations
  useEffect(() => {
    const supportCKEditor = hasSupportCKEditor();

    // Handle different steps
    switch (currentStep) {
      case STEPS.MODE_SELECTION:
        if (emailCreateMode === EMAIL_CREATE_MODES.UPLOAD && !EmailLayout) {
          // Commented out: document.getElementById('upload-email-template').click();
        }
        break;

      case STEPS.TEMPLATE_SELECTION: {
        // Template selection is needed for:
        // 1. Legacy EDITOR mode (when supportCKEditor is true)
        // 2. New DRAG_DROP mode (when supportCKEditor is false)
        // NOT needed for HTML_EDITOR (goes directly to editor)

        let needsTemplates = false;
        if (supportCKEditor) {
          // Legacy flow: only for EDITOR mode
          needsTemplates = emailCreateMode === EMAIL_CREATE_MODES.EDITOR
            && !CmsTemplates
            && !getCmsTemplatesInProgress;
        } else {
          // New flow: for DRAG_DROP only (not HTML_EDITOR)
          needsTemplates = selectedCreateMode === EMAIL_CREATE_MODES.DRAG_DROP
            && !CmsTemplates
            && !getCmsTemplatesInProgress;
        }

        if (needsTemplates && !defaultTemplatesFetchedRef.current) {
          templatesActions.getDefaultBeeTemplates();
          defaultTemplatesFetchedRef.current = true;
        }
        break;
      }

      case STEPS.CREATE_TEMPLATE_CONTENT: {
        if (emailCreateMode === EMAIL_CREATE_MODES.UPLOAD && !isEmpty(EmailLayout)) {
          setSelectedCreateMode(EMAIL_CREATE_MODES.UPLOAD);
        } else if (emailCreateMode === EMAIL_CREATE_MODES.EDITOR
          || emailCreateMode === EMAIL_CREATE_MODES.DRAG_DROP
          || selectedCreateMode === EMAIL_CREATE_MODES.EDITOR
          || selectedCreateMode === EMAIL_CREATE_MODES.DRAG_DROP) {
          if (!supportCKEditor && selectedCreateMode === EMAIL_CREATE_MODES.HTML_EDITOR) {
            // HTML Editor mode: Skip template selection, go directly to editor
            setSelectedCreateMode(EMAIL_CREATE_MODES.HTML_EDITOR);
          } else if (isEmpty(SelectedEdmDefaultTemplate) && modeContent.id) {
            // Legacy EDITOR or DRAG_DROP: Need template selection
            handleEdmDefaultTemplateSelection(modeContent.id);
          } else if (!supportCKEditor && selectedCreateMode === EMAIL_CREATE_MODES.DRAG_DROP) {
            // CRITICAL: Template already selected for DRAG_DROP - ensure selectedCreateMode is DRAG_DROP
            // This ensures emailProps will have editor: 'BEE' and selectedEditorMode: null
            setSelectedCreateMode(EMAIL_CREATE_MODES.DRAG_DROP);
          } else {
            // Template already selected for legacy EDITOR
            setSelectedCreateMode(EMAIL_CREATE_MODES.EDITOR);
          }
        }
        break;
      }

      default:
        // No operation for other steps
        break;
    }
  }, [
    currentStep,
    selectedCreateMode,
    emailCreateMode,
    EmailLayout,
    CmsTemplates,
    getCmsTemplatesInProgress,
    modeContent.id,
    SelectedEdmDefaultTemplate,
    templatesActions,
    handleEdmDefaultTemplateSelection,
  ]);

  // CRITICAL: Reset selectedCreateMode when templateData is cleared (new template creation)
  // This ensures that when user creates a new template after editing, selectedCreateMode is reset
  useEffect(() => {
    // If templateData is cleared/null and we're not in edit mode, reset selectedCreateMode
    const hasParamsId = params?.id
      || location?.query?.id
      || location?.params?.id
      || location?.pathname?.includes('/edit/');
    const hasTemplateData = templateData && !isEmpty(templateData);
    const isEditMode = hasParamsId || hasTemplateData;

    // If we're creating a new template (no templateData and no params.id), reset selectedCreateMode
    // BUT only if we're in MODE_SELECTION step (navigating back to start)
    // DO NOT reset in CREATE_TEMPLATE_CONTENT - that's where we need selectedCreateMode to render the editor!
    // Also DO NOT reset if emailCreateMode is set - it means user has made a selection
    if (!isEditMode && !hasTemplateData && selectedCreateMode && currentStep === STEPS.MODE_SELECTION && !emailCreateMode) {
      // Reset only when returning to MODE_SELECTION step
      // This preserves user selection while in content creation
      setSelectedCreateMode('');
    }
  }, [templateData, params?.id, location?.query?.id, location?.params?.id, location?.pathname, selectedCreateMode, templateName, currentStep, emailCreateMode]);

  // Derived state
  const supportCKEditorFlag = hasSupportCKEditor();

  // Prepare props for Email component - MOVED BEFORE isShowEmailCreate to avoid circular dependency
  const emailProps = useMemo(() => {
    // Determine editor type and mode based on selectedCreateMode
    let editorType = editor;
    let selectedEditorMode = null;

    if (!supportCKEditorFlag) {
      // CRITICAL: Check selectedCreateMode FIRST to prioritize user's explicit selection
      // This ensures DRAG_DROP selection takes precedence over edit mode detection
      // even if templateDetails persists from a previous template
      if (selectedCreateMode === EMAIL_CREATE_MODES.DRAG_DROP) {
        // CRITICAL: DRAG_DROP mode always uses BEE editor
        // This takes precedence over edit mode detection
        editorType = 'BEE';
        selectedEditorMode = null; // BEE uses existing flow (null indicates BEE editor)
      } else if (selectedCreateMode === EMAIL_CREATE_MODES.HTML_EDITOR) {
        // HTML_EDITOR mode: Always use HTML editor
        editorType = 'HTML';
        selectedEditorMode = EMAIL_CREATE_MODES.HTML_EDITOR;
      } else {
        // Check if we're editing an existing template
        // CRITICAL: Only treat as edit mode if we have params.id (actual edit URL) or templateData prop
        // Don't use templateDetails existence alone, as it might persist from previous template
        const hasParamsId = params?.id || location?.query?.id || location?.params?.id || location?.pathname?.includes('/edit/');
        const hasTemplateDataProp = templateData && !isEmpty(templateData);
        // CRITICAL: Consider it edit mode if we have params.id OR templateData prop (library mode)
        // This allows editor type determination even when template data is still loading
        const isEditMode = hasParamsId || hasTemplateDataProp;

        if (isEditMode) {
          // Edit mode: Determine editor based on template data
          // Priority: Email.templateDetails > Email.BEETemplate > templateData prop
          // Use first non-empty source (empty array/object can appear while template is loading)
          const editTemplateData = [Email?.templateDetails, Email?.BEETemplate, templateData].find(
            (d) => d && !isEmpty(d)
          ) || null;
          // Helper function to safely get is_drag_drop from various possible paths
          const getIsDragDrop = (data) => {
            if (!data || isEmpty(data)) return false;

            // Check common paths for is_drag_drop
            // Path 1: versions.base.is_drag_drop (most common)
            const baseDragDrop = get(data, 'versions.base.is_drag_drop', false);
            if (baseDragDrop === true || baseDragDrop === 1) return true;

            // Path 2: versions.base[activeTab].is_drag_drop (language-specific)
            const activeTab = get(data, 'versions.base.activeTab', 'en');
            const activeTabDragDrop = get(data, `versions.base.${activeTab}.is_drag_drop`, false);
            if (activeTabDragDrop === true || activeTabDragDrop === 1) return true;

            // Path 3: base.is_drag_drop (alternative structure)
            const baseLevelDragDrop = get(data, 'base.is_drag_drop', false);
            if (baseLevelDragDrop === true || baseLevelDragDrop === 1) return true;

            // Path 4: is_drag_drop (root level)
            const rootDragDrop = get(data, 'is_drag_drop', false);
            if (rootDragDrop === true || rootDragDrop === 1) return true;

            // Path 5: Check all language tabs in versions.base
            const baseVersions = get(data, 'versions.base', {});
            if (baseVersions && typeof baseVersions === 'object') {
              for (const key in baseVersions) {
                if (key !== 'activeTab' && typeof baseVersions[key] === 'object') {
                  const langDragDrop = get(baseVersions[key], 'is_drag_drop', false);
                  if (langDragDrop === true || langDragDrop === 1) return true;
                }
              }
            }

            return false;
          };

          // When template data is still loading (editTemplateData empty), trust editor prop so BEE templates open in BEE
          const hasMeaningfulTemplateData = editTemplateData && !isEmpty(editTemplateData);
          const isDragDrop = getIsDragDrop(editTemplateData)
            || (!hasMeaningfulTemplateData && editor === 'BEE');
          // Check if BEE is enabled for org (equivalent to checkBeeEditorAllowedForLibrary)
          // For editor selection:
          // - In full mode: BEE is always enabled
          // - In library mode: Check API response, but if API hasn't responded yet and template is BEE, allow BEE (optimistic)
          // - Also check if editor prop is explicitly "BEE"
          const beeEnabledFromAPI = checkBeeEditorEnabled();
          const isAPIResponsePending = isBeeEditorEnabled === null;
          const isBeeEnabled = isFullMode
            || (editor === "BEE" && !isFullMode)
            || beeEnabledFromAPI
            || (isAPIResponsePending && isDragDrop && !isFullMode); // Optimistic: if template is BEE and API pending, allow BEE
          // If template was created in BEE AND BEE is enabled → open in BEE editor
          // Otherwise → open in HTML editor (fallback)
          // IMPORTANT: When supportCKEditor is false, default to HTML editor unless explicitly BEE
          if ((isDragDrop && isBeeEnabled)) {
            editorType = 'BEE';
            selectedEditorMode = null; // BEE uses existing flow
          } else {
            // Fallback to HTML editor if BEE not enabled or template not created in BEE
            // This ensures HTML editor is used when supportCKEditor is false
            editorType = 'HTML';
            selectedEditorMode = EMAIL_CREATE_MODES.HTML_EDITOR;
          }
        } else if (selectedCreateMode === EMAIL_CREATE_MODES.EDITOR) {
          // EDITOR mode: Check if selected template is a BEE template
          // When a default template is selected, it's stored in Templates.BEETemplate
          const beeTemplate = Email?.BEETemplate || SelectedEdmDefaultTemplate;
          const isBEETemplate = beeTemplate && (
            get(beeTemplate, 'versions.base.is_drag_drop') === true
            || get(beeTemplate, 'base.is_drag_drop') === true
            || beeTemplate.is_drag_drop === true
          );

          if (isBEETemplate && checkBeeEditorEnabled()) {
            // Template is BEE and BEE is enabled → use BEE editor
            editorType = 'BEE';
            selectedEditorMode = null; // BEE uses existing flow
          } else {
            // Template is not BEE or BEE is disabled → use HTML editor
            editorType = 'HTML';
            selectedEditorMode = EMAIL_CREATE_MODES.HTML_EDITOR;
          }
        } else {
          // Default: When supportCKEditor is false and no mode selected, use HTML editor
          editorType = 'HTML';
          selectedEditorMode = EMAIL_CREATE_MODES.HTML_EDITOR;
        }
      }
      // UPLOAD mode uses existing editor prop
    }
    // Legacy flow (supportCKEditor is true): Use existing editor prop as-is - no changes

    // Determine template name for edit mode
    let finalTemplateName = templateName;
    if (Email?.templateDetails?.name) {
      finalTemplateName = Email.templateDetails.name;
    } else if (templateData?.name) {
      finalTemplateName = templateData.name;
    }

    // Determine params - include id for edit mode
    const emailParams = {};
    if (params?.id) {
      emailParams.id = params.id;
    } else if (location?.query?.id) {
      emailParams.id = location.query.id;
    } else if (location?.params?.id) {
      emailParams.id = location.params.id;
    } else if (location?.pathname?.includes('/edit/')) {
      // Extract id from pathname if it's in the format /edit/:id
      const match = location.pathname.match(/\/edit\/([^/]+)/);
      // Reject sentinel strings that come from unguarded template literals
      // (e.g. `/edit/${maybeUndefined}` → "/edit/undefined"), so they don't
      // get treated as real template ids downstream.
      if (match && match[1] && match[1] !== 'undefined' && match[1] !== 'null') {
        emailParams.id = match[1];
      }
    }

    return {
      setIsLoadingContent,
      key: "email-create-template",
      location: routeParams,
      route: { name: 'email' },
      params: emailParams,
      isGetFormData,
      getFormdata,
      getFormSubscriptionData: getFormdata,
      getDefaultTags: type,
      isFullMode,
      defaultData: { 'template-name': finalTemplateName },
      cap,
      showTemplateName,
      showLiquidErrorInFooter,
      onValidationFail,
      forwardedTags,
      selectedOfferDetails,
      onPreviewContentClicked,
      onTestContentClicked,
      editor: editorType,
      selectedEditorMode, // Pass selected mode to Email component (only for HTML_EDITOR)
      moduleType,
      eventContextTags,
      waitEventContextTags,
      isLoyaltyModule,
      showTestAndPreviewSlidebox,
      handleTestAndPreview,
      handleCloseTestAndPreview,
      isTestAndPreviewMode,
    };
  }, [
    setIsLoadingContent,
    routeParams,
    Email?.BEETemplate,
    Email?.templateDetails, // Include templateDetails so editor type recalculates when template loads
    SelectedEdmDefaultTemplate,
    checkBeeEditorEnabled,
    isGetFormData,
    getFormdata,
    type,
    isFullMode,
    templateName,
    cap,
    showTemplateName,
    showLiquidErrorInFooter,
    onValidationFail,
    forwardedTags,
    selectedOfferDetails,
    onPreviewContentClicked,
    onTestContentClicked,
    editor,
    moduleType,
    eventContextTags,
    waitEventContextTags,
    isLoyaltyModule,
    showTestAndPreviewSlidebox,
    handleTestAndPreview,
    handleCloseTestAndPreview,
    isTestAndPreviewMode,
    selectedCreateMode,
    supportCKEditorFlag,
    checkBeeEditorEnabled,
    isBeeEditorEnabled, // Include to recalculate when API response arrives
    Email,
    location,
    params,
    editor,
    isFullMode,
    templateData,
    templateName,
  ]);

  const isShowEmailCreate = useMemo(() => {
    // Check if we're in edit mode (templateDetails or BEETemplate exists, or params.id exists)
    const hasTemplateDetails = Email?.templateDetails && !isEmpty(Email.templateDetails);
    const hasBEETemplate = Email?.BEETemplate && !isEmpty(Email.BEETemplate);
    const hasParamsId = params?.id || location?.query?.id || location?.params?.id || location?.pathname?.includes('/edit/');
    const isEditMode = hasTemplateDetails || hasBEETemplate || hasParamsId;

    // In edit mode (when supportCKEditor is false), always show editor
    if (!supportCKEditorFlag && isEditMode) {
      // Check if it's explicitly BEE editor
      // Show editor for both BEE and HTML in edit mode
      return true;
    }

    if (!selectedCreateMode) return false;

    // For HTML Editor (new flow): Always show editor directly without template selection
    // This takes precedence over step check to ensure HTML Editor is shown even if step is temporarily TEMPLATE_SELECTION
    if (!supportCKEditorFlag && selectedCreateMode === EMAIL_CREATE_MODES.HTML_EDITOR) {
      return true;
    }

    // CRITICAL: For DRAG_DROP mode, show template selection first (CmsTemplatesComponent)
    // Only show editor (Email component with BEE) after template is selected
    if (emailCreateMode === EMAIL_CREATE_MODES.DRAG_DROP || selectedCreateMode === EMAIL_CREATE_MODES.DRAG_DROP) {
      // If we're in TEMPLATE_SELECTION step, show template selection (not email editor)
      if (currentStep === STEPS.TEMPLATE_SELECTION) {
        return false;
      }
      // After template selection, show editor when template is selected
      return !isEmpty(SelectedEdmDefaultTemplate);
    }

    // If we're in TEMPLATE_SELECTION step, show template selection (not email editor)
    // This applies to legacy Editor modes
    if (currentStep === STEPS.TEMPLATE_SELECTION) {
      return false;
    }

    // For Upload: Show editor when EmailLayout exists
    if (emailCreateMode === EMAIL_CREATE_MODES.UPLOAD) {
      return !isEmpty(EmailLayout);
    }

    // For Editor: Show editor when template is selected
    return !isEmpty(SelectedEdmDefaultTemplate);
  }, [currentStep, selectedCreateMode, supportCKEditorFlag, emailCreateMode, EmailLayout, SelectedEdmDefaultTemplate, Email?.templateDetails, Email?.BEETemplate, params?.id, location?.query?.id, location?.params?.id, location?.pathname, emailProps?.editor, emailProps?.selectedEditorMode]);

  // Memoize static data
  const modes = useMemo(() => {
    const supportCKEditor = hasSupportCKEditor();
    const isBeeEditorEnabledValue = checkBeeEditorEnabled();

    if (supportCKEditor) {
      // Legacy flow: Show only 2 options (Upload Zip, Use Editor)
      return [
        {
          title: formatMessage(messages.zipUpload),
          content: formatMessage(messages.zipUploadDesc),
          value: EMAIL_CREATE_MODES.UPLOAD,
        },
        {
          title: formatMessage(messages.useEditor),
          content: formatMessage(messages.useEditorDesc),
          value: EMAIL_CREATE_MODES.EDITOR,
        },
      ];
    }

    // New flow: Show 3 options (HTML Editor, Drag & Drop, Upload Zip)
    return [
      {
        title: formatMessage(messages.htmlEditorTitle),
        content: formatMessage(messages.htmlEditorDesc),
        value: EMAIL_CREATE_MODES.HTML_EDITOR,
        icon: <CapIcon type="code" />,
      },
      {
        title: formatMessage(messages.dragDropEditorTitle),
        content: formatMessage(messages.dragDropEditorDesc),
        value: EMAIL_CREATE_MODES.DRAG_DROP,
        icon: <CapIcon type="draggable" svgProps={{ fill: 'currentColor' }} />,
        disabled: !isBeeEditorEnabledValue,
        tooltipProps: !isBeeEditorEnabledValue ? {
          title: formatMessage(messages.beeEditorDisabledTooltip),
          placement: 'top',
        } : undefined,
      },
      {
        title: formatMessage(messages.uploadZipTitle),
        content: formatMessage(messages.uploadZipDesc),
        value: EMAIL_CREATE_MODES.UPLOAD,
        icon: <CapIcon type="file" />,
      },
    ];
  }, [formatMessage, checkBeeEditorEnabled]);

  // Prepare props for CmsTemplatesComponent
  const cmsTemplatesProps = useMemo(() => ({
    cmsTemplates: CmsTemplates,
    handleEdmDefaultTemplateSelection: useEditor,
    cmsTemplatesLoader,
    currentOrgDetails: currentOrgDetails || cap?.currentOrgDetails,
  }), [CmsTemplates, useEditor, cmsTemplatesLoader, currentOrgDetails, cap]);

  // Upload button label
  const uploadButtonLabel = formatMessage(messages.upload);

  return {
    // State
    templateName,
    isTemplateNameEmpty,
    modeContent,

    // Derived values
    modes,
    isShowEmailCreate,
    emailProps,
    cmsTemplatesProps,
    uploadButtonLabel,

    // Event handlers
    onTemplateNameChange,
    onChange,
    useFileUpload,
  };
};

export default useEmailWrapper;
