import React, {
  useCallback,
  useState,
  useEffect,
  useRef,
} from "react";
import PropTypes from "prop-types";
import { FormattedMessage } from "react-intl";
import CapButton from "@capillarytech/cap-ui-library/CapButton";
import CapCard from "@capillarytech/cap-ui-library/CapCard";
import CapColumn from "@capillarytech/cap-ui-library/CapColumn";
import CapDivider from "@capillarytech/cap-ui-library/CapDivider";
import CapHeading from "@capillarytech/cap-ui-library/CapHeading";
import CapIcon from "@capillarytech/cap-ui-library/CapIcon";
import CapRadioGroup from "@capillarytech/cap-ui-library/CapRadioGroup";
import CapRow from "@capillarytech/cap-ui-library/CapRow";
import CapTab from "@capillarytech/cap-ui-library/CapTab";
import CapCheckbox from "@capillarytech/cap-ui-library/CapCheckbox";
import CapLabel from "@capillarytech/cap-ui-library/CapLabel";
import CapSelect from "@capillarytech/cap-ui-library/CapSelect";
import CapInput from "@capillarytech/cap-ui-library/CapInput";
import CapError from "@capillarytech/cap-ui-library/CapError";
import CapImageUpload from "../../../v2Components/CapImageUpload";
import CapVideoUpload from "../../../v2Components/CapVideoUpload";
import {
  ALLOWED_IMAGE_EXTENSIONS_REGEX,
  MPUSH_IMG_SIZE,
  MPUSH_IMG_MAX_WIDTH,
  MPUSH_IMG_MAX_HEIGHT,
  ALLOWED_EXTENSIONS_VIDEO_REGEX,
  MPUSH_VIDEO_SIZE,
  ALLOWED_GIF_REGEX,
  MPUSH_GIF_SIZE,
  MOBILE_PUSH_CHANNEL,
  ANDROID,
  GIF,
  IMAGE,
  VIDEO,
  LINK_TYPE_OPTIONS,
  DEEP_LINK,
  EXTERNAL_LINK,
  CAROUSEL,
} from "../constants";
import messages from "../messages";
import { validateExternalLink, validateDeepLink } from "../utils";
import TagList from "../../TagList";

// Initial carousel data structure
const CAROUSEL_INITIAL_DATA = {
  mediaType: IMAGE.toLowerCase(),
  imageUrl: '',
  videoSrc: '',
  buttons: [{
    actionOnClick: false,
    linkType: DEEP_LINK,
    deepLinkValue: '',
    deepLinkKeys: [],
    externalLinkValue: '',
  }],
};

// Maximum number of carousel cards allowed
const MAX_CAROUSEL_ALLOWED = 10;

// Helper function to find selected deep link with fallback to base URL
const findSelectedDeepLink = (links, value) => {
  if (!links || !value) return undefined;
  
  // Try to find exact match first
  let selectedDeepLink = links.find((link) => link?.value === value);
  
  // If no exact match and value contains query parameters, try base URL match
  if (!selectedDeepLink && value?.includes('?')) {
    const baseDeepLinkValue = value.split('?')[0];
    selectedDeepLink = links.find((link) => link?.value === baseDeepLinkValue);
  }
  
  return selectedDeepLink;
};

const MediaUploaders = ({
  mediaType,
  activeTab,
  imageSrc,
  uploadMpushAsset,
  isFullMode,
  setUpdateMpushImageSrc,
  updateOnMpushImageReUpload,
  imageData,
  videoAssetList,
  gifAssetList,
  setUpdateMpushVideoSrc,
  videoDataForVideo,
  videoDataForGif,
  videoSrc, // Add videoSrc prop for content state fallback
  formatMessage,
  linkProps,
  clearImageDataByMediaType,
  carouselData = [], // Carousel data from content state
  onCarouselDataChange, // Callback to update carousel data in parent
  mobilePushActions, // Mobile push actions for clearing assets
  carouselActiveTabIndex,
  setCarouselActiveTabIndex,
  carouselLinkErrors = {}, // Carousel link errors from parent
  updateCarouselLinkError, // Function to update carousel link errors in parent
  location,
  tags,
  injectedTags,
  selectedOfferDetails,
  handleOnTagsContextChange,
}) => {
  // Carousel state management - separate for Android and iOS
  const [carouselMediaType, setCarouselMediaType] = useState(IMAGE.toLowerCase());

  // Track re-upload mode to prevent automatic restoration during re-upload
  const [isReUploading, setIsReUploading] = useState(false);

  // Track which card is currently uploading to handle completion properly
  const [uploadingCardIndex, setUploadingCardIndex] = useState(null);
  
  // Track upload ID to prevent processing stale Redux data
  const [currentUploadId, setCurrentUploadId] = useState(null);
  const uploadIdRef = useRef(0); // Counter for generating unique upload IDs
  
  // Track previous upload data to detect when a new upload completes
  const previousUploadDataRef = useRef(null);

  // Track previous media type to handle transitions
  const previousMediaTypeRef = useRef(mediaType);

  // Extract link props
  const { deepLink } = linkProps || {};

  // Get current carousel data based on active tab
  const getCurrentCarouselData = useCallback(() => carouselData || [], [carouselData]);

  // Set current carousel data based on active tab
  const setCurrentCarouselData = useCallback((newData) => {
    if (onCarouselDataChange) {
      onCarouselDataChange(activeTab, newData);
    }
  }, [activeTab, onCarouselDataChange]);

  // Move updateCarouselCard to top level so useEffect can access it
  const updateCarouselCard = useCallback((index, fields) => {
    const currentData = getCurrentCarouselData();
    setCurrentCarouselData(currentData?.map((card, i) => (
      i === index ? { ...card, ...fields } : card
    )));
  }, [getCurrentCarouselData, setCurrentCarouselData]);

  // Create carousel button tag select callback at component level to avoid hooks violation
  const createCarouselButtonTagSelectCallback = useCallback((cardIndex) => {
    return (value) => {
      const currentData = getCurrentCarouselData();
      const card = currentData[cardIndex];
      const button = card?.buttons?.[0];
      if (button) {
        const newUrl = `${button?.externalLinkValue}{{${value}}}`;
        // Update carousel card directly using updateCarouselCard
        const updatedButtons = [...card?.buttons];
        updatedButtons[0] = { ...updatedButtons[0], externalLinkValue: newUrl };
        updateCarouselCard(cardIndex, { buttons: updatedButtons });
      }
    };
  }, [getCurrentCarouselData, updateCarouselCard]);

  // Clear previous media data when switching media types
  useEffect(() => {
    // Clear carousel data when switching to non-carousel media types
    if (mediaType !== CAROUSEL) {
      setCurrentCarouselData([]);
      setCarouselActiveTabIndex(0);
      
      // Reset carousel upload tracking
      setUploadingCardIndex(null);
      setCurrentUploadId(null);
      previousUploadDataRef.current = null;
    }

    // Clear image data when switching away from IMAGE media type
    if (mediaType !== IMAGE) {
      clearImageDataByMediaType(IMAGE);
    }

    // Clear image data when switching FROM CAROUSEL TO IMAGE
    // This prevents carousel images from appearing in IMAGE media type
    if (previousMediaTypeRef.current === CAROUSEL && mediaType === IMAGE) {
      clearImageDataByMediaType(IMAGE);
    }

    // Reset re-upload mode when switching media types
    setIsReUploading(false);

    // Update the previous media type ref
    previousMediaTypeRef.current = mediaType;
  }, [mediaType, clearImageDataByMediaType, setCurrentCarouselData]);

  // Handle platform tab changes for carousel data
  useEffect(() => {
    // Reset active tab index when switching platforms
    setCarouselActiveTabIndex(0);
    
    // Reset upload tracking when switching platforms to prevent cross-platform conflicts
    if (mediaType === CAROUSEL) {
      setUploadingCardIndex(null);
      setCurrentUploadId(null);
      previousUploadDataRef.current = null;
    }
  }, [activeTab, mediaType]);

  // Initialize carousel data if empty
  useEffect(() => {
    if (mediaType === CAROUSEL && (!carouselData || carouselData?.length === 0)) {
      setCurrentCarouselData([CAROUSEL_INITIAL_DATA]);
    }
  }, [mediaType, carouselData, activeTab, setCurrentCarouselData]);

  // Note: Carousel images use standard platform indices (0/1) and are handled 
  // by the updateImageSrc callback with CAROUSEL mediaType for proper separation

  const renderImageComponent = useCallback(() => {
    let imageSource = '';

    // Use platform-specific image source
    const platformKey = activeTab === ANDROID ? "androidImageSrc" : "iosImageSrc";
    imageSource = imageSrc[platformKey] || '';

    return (
      <CapImageUpload
        style={{ paddingTop: "20px" }}
        allowedExtensionsRegex={ALLOWED_IMAGE_EXTENSIONS_REGEX}
        imgSize={MPUSH_IMG_SIZE}
        imgWidth={MPUSH_IMG_MAX_WIDTH}
        imgHeight={MPUSH_IMG_MAX_HEIGHT}
        uploadAsset={uploadMpushAsset}
        isFullMode={isFullMode}
        imageSrc={imageSource}
        updateImageSrc={(src) => setUpdateMpushImageSrc(src, activeTab === ANDROID ? 0 : 1, IMAGE)}
        updateOnReUpload={updateOnMpushImageReUpload}
        index={activeTab === ANDROID ? 0 : 1}
        className="cap-custom-image-upload"
        key="mpush-uploaded-image"
        imageData={imageData}
        channel={MOBILE_PUSH_CHANNEL}
        showReUploadButton
        errorMessage={formatMessage(messages.imageErrorMessage)}
      />
    );
  }, [
    activeTab,
    imageSrc,
    uploadMpushAsset,
    isFullMode,
    setUpdateMpushImageSrc,
    updateOnMpushImageReUpload,
    imageData,
    formatMessage,
  ]);

  const renderVideoComponent = useCallback(() => {
    // Apply same platform isolation logic as images
    let platformVideoData = {};
    const currentIndex = activeTab === ANDROID ? 0 : 1;

    // Use platform-specific video data
    if (videoDataForVideo && videoDataForVideo[`uploadedAssetData${currentIndex}`] && Object.keys(videoDataForVideo[`uploadedAssetData${currentIndex}`]).length > 0) {
      // ONLY include the current platform's uploadedAssetData to prevent cross-platform bleeding
      platformVideoData = {
        [`uploadedAssetData${currentIndex}`]: videoDataForVideo[`uploadedAssetData${currentIndex}`],
      };
    } else {
      // No platform-specific video data in Redux - check if video exists in content state (like images do)
      // This handles initialization from edit data where video is in content but not yet in Redux
      platformVideoData = {};
    }

    // Add videoSrc content state as additional source for the component
    let videoSource = '';
    videoSource = activeTab === ANDROID ? videoSrc?.androidVideoSrc || '' : videoSrc?.iosVideoSrc || '';

    return (
      <CapVideoUpload
        key="mpush-video-upload"
        index={currentIndex}
        allowedExtensionsRegex={ALLOWED_EXTENSIONS_VIDEO_REGEX}
        videoSize={MPUSH_VIDEO_SIZE}
        isFullMode={isFullMode}
        uploadAsset={uploadMpushAsset}
        uploadedAssetList={videoAssetList || {}}
        onVideoUploadUpdateAssestList={setUpdateMpushVideoSrc}
        videoData={platformVideoData}
        videoSrc={videoSource} // Pass video content state as additional source
        className="cap-custom-video-upload"
        formClassName="mpush-video-upload"
        channel={MOBILE_PUSH_CHANNEL}
        errorMessage={formatMessage(messages.videoErrorMessage)}
        showVideoNameAndDuration={false}
        showReUploadButton
        mediaType="video"
      />
    );
  }, [
    activeTab,
    isFullMode,
    uploadMpushAsset,
    videoAssetList,
    setUpdateMpushVideoSrc,
    videoDataForVideo,
    videoSrc,
    formatMessage,
  ]);

  const renderGifComponent = useCallback(() => {
    // Apply same platform isolation logic as images
    let platformGifData = {};
    const currentIndex = activeTab === ANDROID ? 0 : 1;

    // Use platform-specific GIF data
    if (videoDataForGif && videoDataForGif[`uploadedAssetData${currentIndex}`] && Object.keys(videoDataForGif[`uploadedAssetData${currentIndex}`]).length > 0) {
      // ONLY include the current platform's uploadedAssetData to prevent cross-platform bleeding
      platformGifData = {
        [`uploadedAssetData${currentIndex}`]: videoDataForGif[`uploadedAssetData${currentIndex}`],
      };
    } else {
      // No platform-specific GIF data in Redux - check if GIF exists in content state (like images do)
      // This handles initialization from edit data where GIF is in content but not yet in Redux
      platformGifData = {};
    }
    // Add videoSrc content state as additional source for the component
    const gifSource = activeTab === ANDROID ? videoSrc?.androidVideoSrc || '' : videoSrc?.iosVideoSrc || '';

    return (
      <CapVideoUpload
        key="mpush-gif-upload"
        index={currentIndex}
        allowedExtensionsRegex={ALLOWED_GIF_REGEX}
        videoSize={MPUSH_GIF_SIZE}
        isFullMode={isFullMode}
        uploadAsset={uploadMpushAsset}
        uploadedAssetList={gifAssetList || {}}
        onVideoUploadUpdateAssestList={setUpdateMpushVideoSrc}
        videoData={platformGifData}
        videoSrc={gifSource} // Pass GIF content state as additional source
        className="cap-custom-gif-upload"
        formClassName="mpush-gif-upload"
        channel={MOBILE_PUSH_CHANNEL}
        errorMessage={formatMessage(messages.gifErrorMessage)}
        showVideoNameAndDuration={false}
        showReUploadButton
        mediaType={GIF.toLowerCase()}
      />
    );
  }, [
    activeTab,
    uploadMpushAsset,
    gifAssetList,
    setUpdateMpushVideoSrc,
    videoDataForGif,
    videoSrc,
  ]);

  const renderCarouselComponent = useCallback(() => {
    const handleCarouselMediaOptions = ({ target: { value = '' } = {} }) => {
      setCarouselMediaType(value);
      const currentData = getCurrentCarouselData();
      setCurrentCarouselData(currentData.map((card) => ({
        ...card,
        mediaType: value,
        imageUrl: value === IMAGE.toLowerCase() ? card.imageUrl : '',
        videoSrc: value === VIDEO.toLowerCase() ? card.videoSrc : '',
        buttons: card.buttons || [{
          actionOnClick: false,
          linkType: DEEP_LINK,
          deepLinkValue: '',
          externalLinkValue: '',
        }],
      })));
    };

    const onTabChange = (index) => {
      setCarouselActiveTabIndex(index);
    };

    const addCarouselCard = () => {
      const currentData = getCurrentCarouselData();
      if (currentData?.length < MAX_CAROUSEL_ALLOWED) {
        setCurrentCarouselData([
          ...currentData,
          { ...CAROUSEL_INITIAL_DATA, mediaType: carouselMediaType },
        ]);
      }
    };

    const deleteCarouselCard = (index) => {
      const currentData = getCurrentCarouselData();
      if (currentData?.length > 1) {
        setCurrentCarouselData(currentData.filter((_, i) => i !== index));
        if (carouselActiveTabIndex >= currentData?.length - 1) {
          setCarouselActiveTabIndex(Math.max(0, currentData?.length - 2));
        }
      }
    };

    // updateCarouselCard moved to top level to be accessible by useEffect

    const handleCarouselImageChange = (image, cardIndex) => {
      // Update the specific card that uploaded the image, not the active card
      updateCarouselCard(cardIndex, { imageUrl: image });
    };

    // Carousel-specific re-upload handler that clears both Redux and component state for specific card
    const handleCarouselImageReUpload = (cardIndex) => {
      // Set re-upload mode to prevent automatic restoration
      setIsReUploading(true);

      // Clear Redux state (same as updateOnMpushImageReUpload)
      updateOnMpushImageReUpload();

      // Clear Redux uploadedAssetData to prevent automatic restoration using standard platform index
      const platformIndex = activeTab === ANDROID ? 0 : 1;
      mobilePushActions.clearAsset(platformIndex);

      // Clear carousel component state for the specific card
      const currentData = getCurrentCarouselData();
      if (currentData?.length > cardIndex) {
        const updatedData = [...currentData];
        updatedData[cardIndex] = {
          ...updatedData[cardIndex],
          imageUrl: '',
        };
        setCurrentCarouselData(updatedData);
      }

      // Reset re-upload mode after a delay
      setTimeout(() => {
        setIsReUploading(false);
      }, 100);
    };

    // Action link handlers for carousel cards
    const handleCarouselActionOnClickChange = (cardIndex, checked) => {
      const currentData = getCurrentCarouselData();
      const card = currentData[cardIndex];
      const updatedButtons = [...card?.buttons];
      updatedButtons[0] = { ...updatedButtons[0], actionOnClick: checked };
      updateCarouselCard(cardIndex, { buttons: updatedButtons });
    };

    const handleCarouselLinkTypeChange = (cardIndex, value) => {
      const currentData = getCurrentCarouselData();
      const card = currentData[cardIndex];
      const updatedButtons = [...card?.buttons];
      updatedButtons[0] = { 
        ...updatedButtons[0], 
        linkType: value,
        deepLinkValue: '',
        externalLinkValue: '',
        deepLinkKeys: []
      };
      updateCarouselCard(cardIndex, { buttons: updatedButtons });
      // Clear errors when link type changes
      updateCarouselLinkError(cardIndex, 'deepLink', null);
      updateCarouselLinkError(cardIndex, 'externalLink', null);
      updateCarouselLinkError(cardIndex, 'deepLinkKeys', null);
    };

    const handleCarouselDeepLinkChange = (cardIndex, value) => {
      const currentData = getCurrentCarouselData();
      const card = currentData[cardIndex];
      const updatedButtons = [...card?.buttons];
      updatedButtons[0] = { 
        ...updatedButtons[0], 
        deepLinkValue: value,
        // Clear deep link keys when deep link changes
        deepLinkKeys: []
      };
      updateCarouselCard(cardIndex, { buttons: updatedButtons });
      // Validate deep link
      const error = validateDeepLink(value, formatMessage, messages);
      updateCarouselLinkError(cardIndex, 'deepLink', error);
    };

    const handleCarouselExternalLinkChange = (cardIndex, value) => {
      const currentData = getCurrentCarouselData();
      const card = currentData[cardIndex];
      const updatedButtons = [...card?.buttons];
      updatedButtons[0] = { ...updatedButtons[0], externalLinkValue: value };
      updateCarouselCard(cardIndex, { buttons: updatedButtons });
      // Validate external link
      const error = validateExternalLink(value, formatMessage, messages);
      updateCarouselLinkError(cardIndex, 'externalLink', error);
    };

    const handleCarouselDeepLinkKeysChange = (cardIndex, value) => {
      const currentData = getCurrentCarouselData();
      const card = currentData[cardIndex];
      const updatedButtons = [...card?.buttons];
      // Parse comma-separated values into array
      const keysArray = value?.split(',')?.map((key) => key?.trim())?.filter((key) => key?.length > 0);
      updatedButtons[0] = { ...updatedButtons[0], deepLinkKeys: keysArray };
      updateCarouselCard(cardIndex, { buttons: updatedButtons });
      // Validate deep link keys
      const error = keysArray?.length === 0 ? formatMessage(messages.deepLinkKeysRequired) : null;
      updateCarouselLinkError(cardIndex, 'deepLinkKeys', error);
    };

    const renderCarouselImageComponent = (cardIndex) => {
      const currentData = getCurrentCarouselData();
      const card = currentData[cardIndex];

      // Each carousel card maintains its own imageUrl
      const imageSource = card?.imageUrl || '';

      // Custom upload function that tracks which card is uploading
      const handleCarouselUpload = (file, assetType, fileParams, index) => {
        // Generate unique upload ID to track this specific upload
        uploadIdRef.current += 1;
        const uploadId = uploadIdRef.current;
        
        setUploadingCardIndex(cardIndex);
        setCurrentUploadId(uploadId);
        return uploadMpushAsset(file, assetType, fileParams, index);
      };

      return (
        <CapImageUpload
          style={{ paddingTop: "20px" }}
          allowedExtensionsRegex={ALLOWED_IMAGE_EXTENSIONS_REGEX}
          imgSize={MPUSH_IMG_SIZE}
          imgWidth={MPUSH_IMG_MAX_WIDTH}
          imgHeight={MPUSH_IMG_MAX_HEIGHT}
          uploadAsset={handleCarouselUpload}
          isFullMode={isFullMode}
          imageSrc={imageSource}
          updateImageSrc={(src) => {
            // For gallery uploads (direct URL), update immediately  
            if (src && src?.includes('http')) {
              handleCarouselImageChange(src, cardIndex);
            }          
            // Always call setUpdateMpushImageSrc for Redux state management
            setUpdateMpushImageSrc(src, activeTab === ANDROID ? 0 : 1, CAROUSEL);
          }}
          updateOnReUpload={() => handleCarouselImageReUpload(cardIndex)}
          index={activeTab === ANDROID ? 0 : 1}
          className="cap-custom-image-upload"
          key={`carousel-image-${activeTab}-${cardIndex}`}
          imageData={imageData}
          channel={MOBILE_PUSH_CHANNEL}
          showReUploadButton
          errorMessage={formatMessage(messages.imageErrorMessage)}
          disableAutoRestore // Disable automatic restoration to prevent all cards from showing the same image
        />
      );
    };

    const renderCarouselVideoComponent = (cardIndex) => (
      <CapVideoUpload
        index={activeTab === ANDROID ? 0 : 1}
        allowedExtensionsRegex={ALLOWED_EXTENSIONS_VIDEO_REGEX}
        videoSize={MPUSH_VIDEO_SIZE}
        isFullMode={isFullMode}
        uploadAsset={uploadMpushAsset}
        uploadedAssetList={videoAssetList}
        onVideoUploadUpdateAssestList={(src) => updateCarouselCard(cardIndex, { videoSrc: src })}
        videoData={videoDataForVideo}
        className="cap-custom-video-upload"
        formClassName="mpush-video-upload"
        channel={MOBILE_PUSH_CHANNEL}
        errorMessage={formatMessage(messages.videoErrorMessage)}
        showVideoNameAndDuration={false}
        showReUploadButton
        mediaType="video"
      />
    );

    const renderCarouselActionLinks = (cardIndex) => {
      const currentData = getCurrentCarouselData();
      const card = currentData[cardIndex];

      // Ensure buttons array exists and has at least one element
      if (!card?.buttons || !Array.isArray(card?.buttons) || card?.buttons?.length === 0) {
        return null;
      }

      const button = card?.buttons[0]; // We're handling only one button for now

      // Use the callback creator instead of useCallback inside render function
      const onButtonTagSelect = createCarouselButtonTagSelectCallback(cardIndex);

      return (
        <>
          <CapDivider />
          <CapRow useLegacy className="creatives-mpush-actions">
            <CapRow useLegacy className="mpush-actions-main">
              <CapHeading type="h4" className="mpush-actions">
                <FormattedMessage {...messages.buttonsAndLinks} />
              </CapHeading>
              <CapLabel className="optional-text">
                <FormattedMessage {...messages.optionalText} />
              </CapLabel>
            </CapRow>
            <CapCheckbox
              checked={button.actionOnClick}
              onChange={(e) => handleCarouselActionOnClickChange(cardIndex, e.target.checked)}
              className="action-on-click-checkbox"
            >
              <FormattedMessage {...messages.actionOnClickBody} />
            </CapCheckbox>
            <CapRow useLegacy>
              <CapLabel className="action-description">
                <FormattedMessage {...messages.actionDescription} />
              </CapLabel>
            </CapRow>
            {button?.actionOnClick && (
              <CapRow style={{ display: "flex", justifyContent: "space-around" }}>
                <CapColumn span={6}>
                  <CapHeading type="h4" className="buttons-heading">
                    <FormattedMessage {...messages.linkType} />
                  </CapHeading>
                  <CapSelect.CapCustomSelect
                    options={LINK_TYPE_OPTIONS}
                    value={button.linkType}
                    onChange={(value) => handleCarouselLinkTypeChange(cardIndex, value)}
                    key={`mobile-push-link-type-${activeTab}-${cardIndex}`}
                    selectPlaceholder={formatMessage(messages.selectDeepLink)}
                  />
                </CapColumn>
                {button?.linkType === DEEP_LINK && (
                  <CapColumn span={14}>
                    <CapHeading type="h4" className="buttons-heading">
                      {formatMessage(messages.deepLink)}
                    </CapHeading>
                    <CapSelect.CapCustomSelect
                      options={(() => {
                        const options = [...(deepLink || [])];
                        // If the current value is not in the options, add it
                        if (button?.deepLinkValue && !options.find(opt => opt.value === button?.deepLinkValue)) {
                          options.push({
                            value: button?.deepLinkValue,
                            label: button?.deepLinkValue,
                          });
                        }
                        return options;
                      })()}
                      value={button?.deepLinkValue}
                      onChange={(value) => handleCarouselDeepLinkChange(cardIndex, value)}
                      key={`mobile-push-deep-link-type-${activeTab}-${cardIndex}`}
                      placeholder={formatMessage(messages.selectDeepLink)}
                      style={{ marginTop: "10px" }}
                    />
                    {carouselLinkErrors[`${cardIndex}-deepLink`] && (
                      <CapError className="mobile-push-carousel-deep-link-error">
                        {carouselLinkErrors[`${cardIndex}-deepLink`]}
                      </CapError>
                    )}
                  </CapColumn>
                )}
                {button?.linkType === EXTERNAL_LINK && (
                  <CapColumn span={14}>
                    <CapRow className="buttons-heading-container">
                      <CapHeading type="h4" className="buttons-heading">
                        {formatMessage(messages.externalLink)}
                      </CapHeading>
                      <TagList
                        moduleFilterEnabled={
                          location?.query?.type !== "embedded"
                        }
                        label={formatMessage(messages.addLabels)}
                        onTagSelect={onButtonTagSelect}
                        onContextChange={handleOnTagsContextChange}
                        location={location}
                        tags={tags}
                        injectedTags={injectedTags}
                        selectedOfferDetails={selectedOfferDetails}
                      />
                    </CapRow>
                    <CapInput
                      id={`mobile-push-external-link-input-${activeTab}-${cardIndex}`}
                      onChange={(e) => handleCarouselExternalLinkChange(cardIndex, e.target.value)}
                      placeholder={formatMessage(messages.enterExternalLink)}
                      value={button?.externalLinkValue}
                      size="default"
                      isRequired
                    />
                    {carouselLinkErrors[`${cardIndex}-externalLink`] && (
                      <CapError className="mobile-push-carousel-external-link-error">
                        {carouselLinkErrors[`${cardIndex}-externalLink`]}
                      </CapError>
                    )}
                  </CapColumn>
                )}
              </CapRow>
            )}
            {button?.linkType === DEEP_LINK && button?.deepLinkValue && button?.actionOnClick && (() => {
              const selectedDeepLink = findSelectedDeepLink(deepLink, button?.deepLinkValue);
              const deepLinkKeysFromSelection = selectedDeepLink?.keys;
              let deepLinkKeysFromSelectionArray = [];
              if (Array.isArray(deepLinkKeysFromSelection)) {
                deepLinkKeysFromSelectionArray = deepLinkKeysFromSelection;
              } else if (deepLinkKeysFromSelection) {
                deepLinkKeysFromSelectionArray = [deepLinkKeysFromSelection];
              }
              return deepLinkKeysFromSelectionArray?.length > 0;
            })() && (
              <CapRow style={{ marginTop: "10px", left: "6%", width: '115%'}}>
                <CapColumn span={14}>
                  <CapHeading type="h4" className="deep-link-keys-heading">
                    {formatMessage(messages.deepLinkKeys)}
                  </CapHeading>
                  <CapLabel type="label2" className="deep-link-keys-value">
                    {(() => {
                      const selectedDeepLink = findSelectedDeepLink(deepLink, button?.deepLinkValue);
                      const deepLinkKeysFromSelection = selectedDeepLink?.keys;
                      let deepLinkKeysArray = [];
                      if (Array.isArray(button?.deepLinkKeys)) {
                        deepLinkKeysArray = button?.deepLinkKeys;
                      } else if (button?.deepLinkKeys) {
                        deepLinkKeysArray = [button?.deepLinkKeys];
                      }
                      let deepLinkKeysFromSelectionArray = [];
                      if (Array.isArray(deepLinkKeysFromSelection)) {
                        deepLinkKeysFromSelectionArray = deepLinkKeysFromSelection;
                      } else if (deepLinkKeysFromSelection) {
                        deepLinkKeysFromSelectionArray = [deepLinkKeysFromSelection];
                      }

                      if (deepLinkKeysFromSelectionArray?.length > 0) {
                        return deepLinkKeysFromSelectionArray.join(', ');
                      }
                      if (deepLinkKeysArray?.length > 0) {
                        return deepLinkKeysArray.join(', ');
                      }
                    })()}
                  </CapLabel>
                  <CapInput
                    id={`mobile-push-carousel-deep-link-keys-input-${activeTab}-${cardIndex}`}
                    onChange={(e) => handleCarouselDeepLinkKeysChange(cardIndex, e.target.value)}
                    placeholder={formatMessage(messages.deepLinkKeysPlaceholder, {
                      key: (() => {
                        const selectedDeepLink = findSelectedDeepLink(deepLink, button?.deepLinkValue);
                        const deepLinkKeysFromSelection = selectedDeepLink?.keys;
                        let deepLinkKeysFromSelectionArray = [];
                        if (Array.isArray(deepLinkKeysFromSelection)) {
                          deepLinkKeysFromSelectionArray = deepLinkKeysFromSelection;
                        } else if (deepLinkKeysFromSelection) {
                          deepLinkKeysFromSelectionArray = [deepLinkKeysFromSelection];
                        }
                        return deepLinkKeysFromSelectionArray.join(', ') || 'deep link keys';
                      })(),
                    })}
                    value={Array.isArray(button?.deepLinkKeys) ? button?.deepLinkKeys?.join(', ') : (button?.deepLinkKeys || "")}
                    size="default"
                    style={{ marginTop: "10px" }}
                    error={carouselLinkErrors[`${cardIndex}-deepLinkKeys`]}
                  />
                </CapColumn>
              </CapRow>
            )}
          </CapRow>
        </>
      );
    };

    const getTabPanes = () => {
      const currentData = getCurrentCarouselData();
      return currentData?.map((data, index) => ({
        key: index,
        tab: index + 1,
        content: (
          <CapCard
            title={`${formatMessage(messages.card)} ${index + 1}`}
            extra={(
              <CapButton
                type="link"
                onClick={() => deleteCarouselCard(index)}
                disabled={currentData?.length === 1}
              >
                <CapIcon type="delete" />
              </CapButton>
            )}
            className="mobile-push-carousel-card"
          >
            <CapRow useLegacy>
              {carouselMediaType === IMAGE.toLowerCase() ? (
                <CapRow useLegacy>
                  <CapHeading type="h4">
                    {formatMessage(messages.mediaImage)}
                  </CapHeading>
                  {renderCarouselImageComponent(index)}
                </CapRow>
              ) : (
                <CapRow useLegacy>
                  <CapHeading type="h4">
                    {formatMessage(messages.mediaVideo)}
                  </CapHeading>
                  {renderCarouselVideoComponent(index)}
                </CapRow>
              )}
            </CapRow>
            {renderCarouselActionLinks(index)}
          </CapCard>
        ),
      }));
    };

    const operations = (
      <>
        <CapDivider type="vertical" />
        <CapButton
          onClick={addCarouselCard}
          type="link"
          className="add-carousel-content-button"
          disabled={getCurrentCarouselData()?.length >= MAX_CAROUSEL_ALLOWED}
        >
          <CapIcon type="plus" />
        </CapButton>
      </>
    );

    return (
      <div>
        <CapRow>
          <CapRow className="carousel-media-selection">
            <CapColumn className="carousel-media-selection-heading">
              <CapHeading type="h4">
                {formatMessage(messages.carouselMediaType)}
              </CapHeading>
            </CapColumn>
            <CapColumn>
              <div className="carousel-radio-wrapper">
                <CapRadioGroup
                  id="carousel-media-radio"
                  options={[
                    {
                      value: IMAGE.toLowerCase(),
                      label: formatMessage(messages.mediaImage),
                    },
                    {
                      value: VIDEO.toLowerCase(),
                      label: formatMessage(messages.mediaVideo),
                      disabled: true,
                    },
                  ]}
                  value={carouselMediaType}
                  onChange={handleCarouselMediaOptions}
                  className="mobile-push-media-radio"
                />
              </div>
            </CapColumn>
          </CapRow>
          <CapRow useLegacy className="mobile-push-carousel-tab">
            <CapTab
              defaultActiveKey="0"
              activeKey={carouselActiveTabIndex.toString()}
              tabBarExtraContent={operations}
              onChange={onTabChange}
              panes={getTabPanes()}
            />
          </CapRow>
        </CapRow>
      </div>
    );
  }, [
    carouselMediaType,
    activeTab,
    getCurrentCarouselData,
    setCurrentCarouselData,
    carouselActiveTabIndex,
    uploadMpushAsset,
    isFullMode,
    imageData,
    videoAssetList,
    setUpdateMpushVideoSrc,
    videoDataForVideo,
    formatMessage,
    mobilePushActions,
    carouselLinkErrors,
    updateCarouselLinkError,
    setCarouselActiveTabIndex,
    deepLink,
  ]);

  // Manually handle upload completion for carousel cards (since automatic restoration is disabled)
  useEffect(() => {
    if (mediaType === CAROUSEL && uploadingCardIndex !== null && currentUploadId && imageData) {
      const platformIndex = activeTab === ANDROID ? 0 : 1;
      const uploadedData = imageData[`uploadedAssetData${platformIndex}`];
      
      if (uploadedData?.metaInfo?.secure_file_path) {
        // Check if this is new upload data (different from what we processed last time)
        const currentDataKey = `${uploadedData.metaInfo.secure_file_path}_${uploadedData.metaInfo.file_name || ''}`;
        const previousDataKey = previousUploadDataRef.current;
        
        if (currentDataKey !== previousDataKey) {
          // Update the specific card that was uploading
          updateCarouselCard(uploadingCardIndex, { imageUrl: uploadedData?.metaInfo?.secure_file_path });
          
          // Store this upload data as "processed" to avoid reprocessing
          previousUploadDataRef.current = currentDataKey;
          
          // Clear the uploading state
          setUploadingCardIndex(null);
          setCurrentUploadId(null);
        }
      }
    }
  }, [mediaType, imageData, uploadingCardIndex, currentUploadId, activeTab, updateCarouselCard]);

  if (mediaType === IMAGE) return renderImageComponent();
  if (mediaType === VIDEO) return renderVideoComponent();
  if (mediaType === GIF) return renderGifComponent();
  if (mediaType === CAROUSEL) return renderCarouselComponent();
  return null;
};

MediaUploaders.propTypes = {
  mediaType: PropTypes.string.isRequired,
  activeTab: PropTypes.string.isRequired,
  imageSrc: PropTypes.object.isRequired,
  uploadMpushAsset: PropTypes.func.isRequired,
  isFullMode: PropTypes.bool.isRequired,
  setUpdateMpushImageSrc: PropTypes.func.isRequired,
  updateOnMpushImageReUpload: PropTypes.func.isRequired,
  imageData: PropTypes.object.isRequired,
  videoAssetList: PropTypes.object.isRequired,
  gifAssetList: PropTypes.object.isRequired,
  setUpdateMpushVideoSrc: PropTypes.func.isRequired,
  videoDataForVideo: PropTypes.object.isRequired,
  videoDataForGif: PropTypes.object.isRequired,
  videoSrc: PropTypes.object, // Add videoSrc prop for content state fallback
  formatMessage: PropTypes.func.isRequired,
  linkProps: PropTypes.object,
  clearImageDataByMediaType: PropTypes.func.isRequired,
  carouselData: PropTypes.array,
  onCarouselDataChange: PropTypes.func,
  mobilePushActions: PropTypes.object.isRequired,
  carouselActiveTabIndex: PropTypes.number.isRequired,
  setCarouselActiveTabIndex: PropTypes.func.isRequired,
  carouselLinkErrors: PropTypes.object,
  updateCarouselLinkError: PropTypes.func,
};

export default MediaUploaders;
