/**
 * InAppPreviewContent Component
 *
 * Renders InApp message preview on Android and iOS device mockups
 * Uses the same device structure as SMS preview
 * Content structure based on TemplatePreview InApp 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 CapButton from '@capillarytech/cap-ui-library/CapButton';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import isEmpty from 'lodash/isEmpty';
import { ANDROID, IOS, LAYOUT_TYPE_POPUP, ANDROID_DEVICE_NAME, IOS_DEVICE_NAME, LAYOUT_TYPE_FOOTER, CHANNELS } from '../constants';
import messages from '../messages';

// Import device mockup images (same as SMS)
const smsMobileAndroid = require('../../../assets/Android.png');
const smsMobileIos = require('../../../assets/iOS.png');

const InAppPreviewContent = ({
  content,
  device,
  isUpdating,
  error,
  formatMessage,
  templateLayoutType,
  showHeader,
}) => {
  // Get device image based on device type (same as SMS)
  const deviceImage = device === ANDROID ? smsMobileAndroid : smsMobileIos;
  const deviceName = device === ANDROID ? ANDROID_DEVICE_NAME : IOS_DEVICE_NAME;

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

  // Extract content fields
  const {
    mediaPreview = {},
    templateTitle = '',
    templateMsg = '',
    ctaData = [],
    templateLayoutType: deviceLayoutType = templateLayoutType || LAYOUT_TYPE_POPUP,
  } = deviceContent || {};


  // 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 inapp-content-overlay-height">
          <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 inapp-content-overlay-height">
          <CapRow useLegacy className="sms-error-container">
            <CapIcon type="exclamation-circle" style={{ fontSize: '48px', color: '#ff4d4f' }} />
            <CapRow useLegacy className="sms-error-text">
              {formatMessage(messages.previewError)}
            </CapRow>
            <CapRow useLegacy className="sms-error-message">{error}</CapRow>
          </CapRow>
        </CapRow>
      </CapRow>
    );
  }

  // Render InApp content
  // Use SMS device structure (device frame) but TemplatePreview's InApp content structure inside
  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 - Use TemplatePreview's InApp structure (lines 1409-1486) */}
      <CapRow useLegacy className={`sms-content-overlay inapp-content-overlay-height ${!showHeader ? 'inapp-content-overlay' : ''} sms-${device}`}>
        {/* TemplatePreview InApp structure - shell-v2 wrapper */}
        <CapRow useLegacy className={`inapp-shell-v2 inapp-${device}`}>
          {/* preview-image div wrapper */}
          {/* inapp-message-container with layout type and device */}
          <CapRow
            useLegacy
            className={`inapp-message-container-${deviceLayoutType || LAYOUT_TYPE_POPUP} ${!showHeader && deviceLayoutType === LAYOUT_TYPE_FOOTER ? 'inapp-message-container-FOOTER-no-header' : ''} ${CHANNELS.SMS.toLowerCase()}`}
          >
            {/* preview-inapp-screen - content container */}
            <CapRow useLegacy className="preview-inapp-screen">
              {/* Title - Same as TemplatePreview (line 1420-1435) */}
              <CapLabel
                type="label16"
                className={`inapp-title-${deviceLayoutType || LAYOUT_TYPE_POPUP} ${
                    mediaPreview?.inAppImageSrcAndroid || mediaPreview?.inAppImageSrcIos
                      ? ''
                      : `without-image-title-${deviceLayoutType || LAYOUT_TYPE_POPUP}`
                }`}
              >
                {/* eslint-disable-next-line no-unneeded-ternary */}
                {templateTitle ? templateTitle : ' '}
                {/* this ternary is required here for preview */}
              </CapLabel>

              {/* Image - Same as TemplatePreview (line 1437-1447) */}
              {mediaPreview && (mediaPreview?.inAppImageSrcAndroid || mediaPreview?.inAppImageSrcIos) && (
                <CapImage
                  src={
                    device.toLowerCase() === ANDROID
                      ? mediaPreview?.inAppImageSrcAndroid
                      : mediaPreview?.inAppImageSrcIos
                  }
                  className={`inapp-image-${deviceLayoutType || LAYOUT_TYPE_POPUP}`}
                  alt={formatMessage(messages.previewGenerated)}
                />
              )}

              {/* Message Content - Same as TemplatePreview (line 1448-1464) */}
              <CapLabel
                type="label2"
                className={`align-left inapp-content-${deviceLayoutType || LAYOUT_TYPE_POPUP} ${
                    mediaPreview?.inAppImageSrcAndroid || mediaPreview?.inAppImageSrcIos
                      ? ''
                      : `without-image-content-${deviceLayoutType || LAYOUT_TYPE_POPUP}`
                }`}
              >
                {/* eslint-disable-next-line no-unneeded-ternary */}
                {templateMsg ? templateMsg : ' '}
                {/* this ternary is required here for preview */}
              </CapLabel>

              {/* CTA Button - Same as TemplatePreview (line 1465-1482) */}
              {ctaData
                && !isEmpty(ctaData)
                && (ctaData[0]?.text || ctaData[0]?.actionText) && (
                <CapButton
                  type="primary"
                  className={`inapp-button-${deviceLayoutType || LAYOUT_TYPE_POPUP} ${
                    mediaPreview?.inAppImageSrcAndroid || mediaPreview?.inAppImageSrcIos
                      ? ''
                      : `without-image-button-${deviceLayoutType || LAYOUT_TYPE_POPUP}`
                  }`}
                >
                  {ctaData[0]?.text || ctaData[0]?.actionText}
                </CapButton>
              )}
            </CapRow>
          </CapRow>
        </CapRow>
      </CapRow>
    </CapRow>
  );
};

InAppPreviewContent.propTypes = {
  content: PropTypes.oneOfType([
    PropTypes.shape({
      androidContent: PropTypes.shape({
        mediaPreview: PropTypes.shape({
          inAppImageSrcAndroid: PropTypes.string,
          inAppImageSrcIos: PropTypes.string,
        }),
        templateTitle: PropTypes.string,
        templateMsg: PropTypes.string,
        ctaData: PropTypes.arrayOf(PropTypes.shape({
          text: PropTypes.string,
        })),
        templateLayoutType: PropTypes.string,
      }),
      iosContent: PropTypes.shape({
        mediaPreview: PropTypes.shape({
          inAppImageSrcAndroid: PropTypes.string,
          inAppImageSrcIos: PropTypes.string,
        }),
        templateTitle: PropTypes.string,
        templateMsg: PropTypes.string,
        ctaData: PropTypes.arrayOf(PropTypes.shape({
          text: PropTypes.string,
        })),
        templateLayoutType: PropTypes.string,
      }),
      // Backward compatibility: support old inAppPreviewContent format
      inAppPreviewContent: PropTypes.shape({
        mediaPreview: PropTypes.shape({
          inAppImageSrcAndroid: PropTypes.string,
          inAppImageSrcIos: PropTypes.string,
        }),
        templateTitle: PropTypes.string,
        templateMsg: PropTypes.string,
        ctaData: PropTypes.arrayOf(PropTypes.shape({
          text: PropTypes.string,
        })),
      }),
      templateLayoutType: PropTypes.string,
    }),
    PropTypes.object,
  ]),
  device: PropTypes.oneOf([ANDROID, IOS]),
  isUpdating: PropTypes.bool,
  error: PropTypes.string,
  formatMessage: PropTypes.func.isRequired,
  templateLayoutType: PropTypes.string,
  showHeader: PropTypes.bool,
};

InAppPreviewContent.defaultProps = {
  content: {},
  device: ANDROID,
  isUpdating: false,
  error: null,
  templateLayoutType: LAYOUT_TYPE_POPUP,
  showHeader: true,
};

export default InAppPreviewContent;
