/**
 * MobilePushPreviewContent Component
 *
 * Renders Mobile Push notification preview on Android and iOS device mockups
 * Uses the same device structure as SMS preview
 * Content structure based on TemplatePreview MobilePush rendering
 */

import React from 'react';
import PropTypes from 'prop-types';
import CapIcon from '@capillarytech/cap-ui-library/CapIcon';
import CapLabel from '@capillarytech/cap-ui-library/CapLabel';
import CapSpin from '@capillarytech/cap-ui-library/CapSpin';
import CapImage from '@capillarytech/cap-ui-library/CapImage';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import CapColumn from '@capillarytech/cap-ui-library/CapColumn';
import { ANDROID, IOS, MEDIA_TYPE_IMAGE, MEDIA_TYPE_VIDEO, ANDROID_DEVICE_NAME, IOS_DEVICE_NAME } from '../constants';
import messages from '../messages';

// Import device mockup images (MobilePush specific with date and time)
const androidPushMessagePhone = require('../../TemplatePreview/assets/images/Android_With_date_and_time.svg');
const iPhonePushMessagePhone = require('../../TemplatePreview/assets/images/iOS_With_date_and_time.svg');

// Import video play icon for carousel
const videoPlay = require('../../../assets/videoPlay.svg');

const MobilePushPreviewContent = ({
  content,
  device,
  isUpdating,
  error,
  formatMessage,
}) => {
  // Get device image based on device type (MobilePush specific with date and time)
  const deviceImage = device === ANDROID ? androidPushMessagePhone : iPhonePushMessagePhone;
  const deviceName = device === ANDROID ? ANDROID_DEVICE_NAME : IOS_DEVICE_NAME;

  // Extract MobilePush content structure
  // Content can be: { androidContent: {...}, iosContent: {...} } or direct content object
  const deviceContent = device === ANDROID
    ? (content?.androidContent || content)
    : (content?.iosContent || content);

  // Render loading state
  if (isUpdating) {
    return (
      <CapRow type='flex' align='middle' justify='center' className="sms-device-container">
        <CapImage
          className="sms-device-image"
          src={deviceImage}
          alt={`${deviceName} Device`}
        />
        <CapRow useLegacy className="sms-content-overlay">
          <CapRow type='flex' vertical noWrap align='middle' justify='center' className="sms-loading-container">
            <CapSpin size="large" />
            <CapRow useLegacy className="sms-loading-text">
              {formatMessage(messages.updatingPreview)}
            </CapRow>
          </CapRow>
        </CapRow>
      </CapRow>
    );
  }

  // Render error state
  if (error) {
    return (
      <CapRow type='flex' align='middle' justify='center' className="sms-device-container">
        <CapImage
          className="sms-device-image"
          src={deviceImage}
          alt={`${deviceName} Device`}
        />
        <CapRow useLegacy className="sms-content-overlay">
          <CapRow useLegacy className="sms-error-container">
            <CapIcon type="exclamation-circle" className="exclamation-circle" />
            <CapRow useLegacy className="sms-error-text">
              {formatMessage(messages.previewError)}
            </CapRow>
            <CapRow useLegacy className="sms-error-message">{error}</CapRow>
          </CapRow>
        </CapRow>
      </CapRow>
    );
  }

  // Render MobilePush carousel (based on TemplatePreview renderMobilePushCarousel)
  const renderMobilePushCarousel = (contentData) => {
    if (!contentData?.carouselData || contentData?.carouselData?.length === 0) {
      return null;
    }

    return (
      <CapRow type="flex" vertical noWrap className="msg-container-carousel mobile-push-carousel-container">
        <CapRow useLegacy className="scroll-container mobile-push-scroll-container">
          {contentData?.carouselData?.map((item, idx) => (
            <CapColumn
              key={`carousel-card-${idx}`}
              className="mobile-push-carousel-card message-pop align-left message-pop-carousel"
            >
              {item?.mediaType?.toLowerCase() === MEDIA_TYPE_IMAGE.toLowerCase() && (item?.imageUrl || item?.url) && (
                <CapImage
                  src={item?.imageUrl || item?.url}
                  alt="carousel-img"
                  className="carousel-image"
                />
              )}
              {item?.mediaType?.toLowerCase() === MEDIA_TYPE_VIDEO.toLowerCase() && item?.videoPreviewImg && (
                <CapRow className="video-preview">
                  <CapImage
                    src={item?.videoPreviewImg || item?.url}
                    alt="carousel-video-preview"
                    className="carousel-video-preview"
                  />
                  <CapRow className="icon-position">
                    <CapImage className="video-icon" src={videoPlay} alt="Play" />
                  </CapRow>
                </CapRow>
              )}
              <CapRow className="carousel-content">
                <CapLabel className="carousel-title">
                  {item?.title || item?.header || ''}
                </CapLabel>
                <CapLabel className="carousel-message">
                  {item?.message || item?.bodyText || ''}
                </CapLabel>
              </CapRow>
            </CapColumn>
          ))}
        </CapRow>
      </CapRow>
    );
  };

  // Check if content has any data to render
  const hasContent = !!(deviceContent?.header
    || deviceContent?.bodyText
    || deviceContent?.bodyImage
    || deviceContent?.bodyVideo?.videoSrc
    || deviceContent?.bodyGif);

  // Render MobilePush notification preview
  // Structure based on TemplatePreview MobilePush rendering (lines 790-928)
  return (
    <CapRow type='flex' align='middle' justify='center' className="sms-device-container">
      {/* Device Background Image - Same as SMS */}
      <CapImage
        className="sms-device-image"
        src={deviceImage}
        alt={`${deviceName} Device`}
      />

      {/* Content Overlay - MobilePush notification structure */}
      <CapRow useLegacy className="sms-content-overlay">
        {/* MobilePush notification container */}
        {hasContent && (
          <CapRow
            useLegacy
            className={`${
              device === IOS ? 'iphone' : device
            }-push-message-Container`}
          >
            {/* Notification message pop */}
            <CapRow useLegacy className="message-pop align-left">
              {/* App Header */}

              {/* Body Text */}
              <CapRow type='flex' align='middle' justify='start' className="app-header">
                <CapRow type='flex' align='middle' justify='start' className="app-header-left">
                  <span className="app-icon">{""}</span>
                  <CapLabel type="label16" className="title">{deviceContent?.header || ''}</CapLabel>
                </CapRow>
                <CapRow useLegacy className="app-header-right">
                  <CapLabel type="label11">2:29 PM</CapLabel>
                </CapRow>
                </CapRow>
              {deviceContent?.bodyText && (
                <CapLabel type="label1" className="body-text">{deviceContent.bodyText}</CapLabel>
              )}

              {/* Body Image/Video/GIF */}
              {(deviceContent?.bodyImage || deviceContent?.bodyVideo?.videoSrc || deviceContent?.bodyGif) && (
                <CapRow useLegacy className="body-image">
                  {(() => {
                    if (deviceContent?.bodyVideo?.videoSrc && !deviceContent?.bodyImage && !deviceContent?.bodyGif) {
                      return (
                        <video
                          key={`${device}-video-${deviceContent.bodyVideo.videoSrc}`}
                          controls
                          className="mpush-video-preview"
                          poster={deviceContent?.bodyVideo?.videoPreview || undefined}
                        >
                          <source src={deviceContent.bodyVideo.videoSrc} type="video/mp4" />
                        </video>
                      );
                    } else if (deviceContent?.bodyGif) {
                      return (
                        <img
                          src={deviceContent?.bodyGif}
                          alt="GIF preview"
                          className="mpush-gif-preview"
                          key={`${device}-gif-${deviceContent?.bodyGif}`}
                        />
                      );
                    } else {
                      return (
                        <CapImage
                          src={deviceContent?.bodyImage || deviceContent?.bodyVideo?.videoPreview}
                          alt=""
                        />
                      );
                    }
                  })()}
                </CapRow>
              )}

              {/* Action Buttons */}
              {(deviceContent?.actions || []).filter((action) => action?.label || action?.actionText).length > 0
                && deviceContent?.carouselData?.length === 0 && (
                <CapRow useLegacy className="actions">
                  {(deviceContent?.actions || []).map((action) => (
                    (action?.label || action?.actionText) && (
                      <span
                        className="action"
                        key={`action-${action?.label || action?.actionText}`}
                        title={action?.url || action?.actionLink || ''}
                      >
                        {action?.label?.toUpperCase() || action?.actionText?.toUpperCase()}
                      </span>
                    )
                  ))}
                </CapRow>
              )}

              {/* Carousel */}
              {deviceContent?.carouselData && deviceContent?.carouselData?.length > 0 && (
                renderMobilePushCarousel(deviceContent)
              )}
            </CapRow>
          </CapRow>
        )}

        {/* No content state */}
        {!hasContent && (
          <CapRow type='flex' vertical noWrap align='middle' justify='center' className="sms-loading-container">
            <CapRow useLegacy className="sms-loading-text">
              {formatMessage({ id: 'app.components.CommonTestAndPreview.noContent', defaultMessage: 'No content to preview' })}
            </CapRow>
          </CapRow>
        )}
      </CapRow>
    </CapRow>
  );
};

MobilePushPreviewContent.propTypes = {
  content: PropTypes.oneOfType([
    PropTypes.shape({
      androidContent: PropTypes.shape({
        header: PropTypes.string,
        bodyText: PropTypes.string,
        bodyImage: PropTypes.string,
        bodyVideo: PropTypes.shape({
          videoSrc: PropTypes.string,
          videoPreview: PropTypes.string,
        }),
        bodyGif: PropTypes.string,
        actions: PropTypes.arrayOf(PropTypes.shape({
          label: PropTypes.string,
          url: PropTypes.string,
        })),
        carouselData: PropTypes.array,
      }),
      iosContent: PropTypes.shape({
        header: PropTypes.string,
        bodyText: PropTypes.string,
        bodyImage: PropTypes.string,
        bodyVideo: PropTypes.shape({
          videoSrc: PropTypes.string,
          videoPreview: PropTypes.string,
        }),
        bodyGif: PropTypes.string,
        actions: PropTypes.arrayOf(PropTypes.shape({
          label: PropTypes.string,
          url: PropTypes.string,
        })),
        carouselData: PropTypes.array,
      }),
    }),
    PropTypes.shape({
      header: PropTypes.string,
      bodyText: PropTypes.string,
      bodyImage: PropTypes.string,
      bodyVideo: PropTypes.shape({
        videoSrc: PropTypes.string,
        videoPreview: PropTypes.string,
      }),
      bodyGif: PropTypes.string,
      actions: PropTypes.array,
      carouselData: PropTypes.array,
    }),
  ]),
  device: PropTypes.oneOf([ANDROID, IOS]),
  isUpdating: PropTypes.bool,
  error: PropTypes.string,
  formatMessage: PropTypes.func.isRequired,
};

MobilePushPreviewContent.defaultProps = {
  content: {},
  device: ANDROID,
  isUpdating: false,
  error: null,
};

export default MobilePushPreviewContent;



