/**
 * RcsPreviewContent Component
 *
 * Renders RCS message preview on Android and iOS device mockups
 * Uses same structure and styling as SMS preview up to sms-message-container
 * Only the content inside message bubble is RCS-specific
 */

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 CapDivider from '@capillarytech/cap-ui-library/CapDivider';
import CapTooltip from '@capillarytech/cap-ui-library/CapTooltip';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import { FormattedMessage } from 'react-intl';
import {
  ANDROID,
  IOS,
  ANDROID_DEVICE_NAME,
  IOS_DEVICE_NAME,
  TIME_FORMAT_HOUR_MODULO,
  TIME_FORMAT_MINUTE_PADDING_THRESHOLD,
  TIME_FORMAT_AM,
  TIME_FORMAT_PM,
} from '../constants';
import messages from '../messages';
import { RCS_BUTTON_TYPES } from '../../../v2Containers/Rcs/constants';
import videoPlay from '../../../assets/videoPlay.svg';
import rcsImageEmptyPreview from '../../TemplatePreview/assets/images/empty_image_preview.svg';
import rcsVideoEmptyPreview from '../../TemplatePreview/assets/images/empty_video_preview.svg';

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

const RcsPreviewContent = ({
  content,
  device,
  isUpdating,
  error,
  formatMessage,
  senderId,
  showHeader,
}) => {
  // Get device image based on device type
  const deviceImage = device === ANDROID ? rcsMobileAndroid : rcsMobileIos;
  const deviceName = device === ANDROID ? ANDROID_DEVICE_NAME : IOS_DEVICE_NAME;

  // Render RCS suggestions (Quick Reply, CTA, Phone Number)
  const renderRcsSuggestionsPreview = () => {
    const renderArray = [];
    const { suggestions = [] } = content || {};

    if (suggestions.length === 0) {
      return null;
    }

    suggestions.forEach((suggestion) => {
      const { type, text } = suggestion || {};
      const suggestionKey = `${type}-${text || Math.random()}`;

      if (renderArray.length > 0) {
        renderArray.push(<CapDivider key={`divider-${suggestionKey}`} className="whatsapp-divider" />);
      }

      if (type === RCS_BUTTON_TYPES.QUICK_REPLY) {
        renderArray.push(
          <CapLabel key={suggestionKey} type="label21" className="rcs-cta-preview">
            <CapIcon type="small-link" size="xs" />
            {text}
          </CapLabel>
        );
      } else if (type === RCS_BUTTON_TYPES.CTA) {
        renderArray.push(
          <CapLabel key={suggestionKey} type="label21" className="rcs-cta-preview">
            <CapIcon type="launch" size="xs" />
            {text}
          </CapLabel>
        );
      } else if (type === RCS_BUTTON_TYPES.PHONE_NUMBER) {
        renderArray.push(
          <CapLabel key={suggestionKey} type="label21" className="rcs-cta-preview">
            <CapIcon type="call" size="xs" />
            {text}
          </CapLabel>
        );
      }
    });

    return renderArray?.length > 0 ? renderArray : null;
  };

  // Render text preview content
  const renderTextPreviewContent = () => {
    const {
      templateHeader,
      templateMessage,
      rcsTitle, // Fallback for backward compatibility
      rcsDesc, // Fallback for backward compatibility
    } = content || {};
    // Use templateHeader and templateMessage as primary fields
    const title = templateHeader || rcsTitle;
    const description = templateMessage || rcsDesc;

    return (
      <>
        {title && (
          <>
            <CapLabel
              type="label5"
              className="message-pop-item align-left rcs-content"
              fontWeight="bold"
            >
              {title}
            </CapLabel>
            <CapDivider className="whatsapp-divider" />
          </>
        )}
        {description && (
          <CapLabel
            type="label5"
            className="message-pop-item align-left rcs-desc rcs-content"
          >
            {description}
          </CapLabel>
        )}
        {renderRcsSuggestionsPreview()}
      </>
    );
  };

  // Render media preview content
  const renderMediaPreviewContent = () => {
    const { rcsImageSrc, rcsVideoSrc, rcsThumbnailSrc } = content || {};
    const hasImage = !!rcsImageSrc;
    const hasVideo = !!rcsVideoSrc;
    const thumbnailSrc = rcsThumbnailSrc || rcsVideoSrc;

    return (
      <>
        {hasImage && (
          <CapImage
            src={rcsImageSrc || rcsImageEmptyPreview}
            className="rcs-image"
            alt={formatMessage(messages.previewGenerated)}
          />
        )}
        {hasVideo && (
          <CapTooltip
            title={formatMessage(messages.videoPreviewTooltip)}
          >
            <CapRow className="video-preview">
              <CapImage
                src={thumbnailSrc || rcsVideoEmptyPreview}
                className="rcs-image"
                alt={formatMessage(messages.previewGenerated)}
              />
              <CapRow className="icon-position">
                <CapImage
                  className="video-icon"
                  src={videoPlay}
                  alt="Play"
                />
              </CapRow>
            </CapRow>
          </CapTooltip>
        )}
        {renderTextPreviewContent()}
      </>
    );
  };

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

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

  // Get current time for timestamp (same as SMS)
  const currentTime = new Date();
  const hours = currentTime.getHours();
  const minutes = currentTime.getMinutes();
  const ampm = hours >= TIME_FORMAT_HOUR_MODULO ? TIME_FORMAT_PM : TIME_FORMAT_AM;
  const displayHours = hours % TIME_FORMAT_HOUR_MODULO || TIME_FORMAT_HOUR_MODULO;
  const displayMinutes = minutes < TIME_FORMAT_MINUTE_PADDING_THRESHOLD ? `0${minutes}` : minutes;
  const timestamp = `${displayHours}:${displayMinutes} ${ampm}`;

  // Render normal RCS preview (same structure as SMS up to sms-message-container)
  const hasMedia = !!(content?.rcsImageSrc || content?.rcsVideoSrc);
  const contentToRender = hasMedia ? renderMediaPreviewContent() : renderTextPreviewContent();

  return (
    <CapRow className="sms-device-container">
      {/* Device Background Image */}
      <CapImage
        className="sms-device-image"
        src={deviceImage}
        alt={`${deviceName} Device`}
      />

      {/* Content Overlay */}
      <CapRow className={`sms-content-overlay sms-content-overlay-${device} sms-preview sms-${device}`}>
        {/* Navigation Bar - Same as SMS */}
        <CapRow className={`sms-navigation-bar ${!showHeader ? 'sms-navigation-bar-no-header' : ''}`}>
          <CapIcon type="chevron-left" className="sms-back-arrow" />
          <CapLabel type="label2" className="sms-sender-id">
            {senderId || formatMessage(messages.senderId)}
          </CapLabel>
          <CapIcon type="more" className="sms-menu-icon" />
        </CapRow>

        {/* Date Separator - Same as SMS */}
        <CapRow className="sms-date-separator">
          <FormattedMessage {...messages.timeAgo} defaultMessage="Today" />
        </CapRow>

        {/* Message Container - Same structure as SMS, only content inside is RCS-specific */}
        <CapRow className="sms-message-container">
          <CapRow className="sms-message-bubble">
            <CapRow className="sms-message-text">
              {/* RCS-specific content rendering */}
              <CapRow className="message-pop sms">
                {contentToRender}
              </CapRow>
            </CapRow>
          </CapRow>
          <CapRow className="sms-timestamp">
            {timestamp}
          </CapRow>
        </CapRow>
      </CapRow>
    </CapRow>
  );
};

RcsPreviewContent.propTypes = {
  content: PropTypes.shape({
    rcsTitle: PropTypes.string,
    rcsDesc: PropTypes.string,
    templateHeader: PropTypes.string,
    templateMessage: PropTypes.string,
    rcsImageSrc: PropTypes.string,
    rcsVideoSrc: PropTypes.string,
    rcsThumbnailSrc: PropTypes.string,
    suggestions: PropTypes.arrayOf(
      PropTypes.shape({
        type: PropTypes.string,
        text: PropTypes.string,
      })
    ),
  }),
  device: PropTypes.oneOf([ANDROID, IOS]),
  isUpdating: PropTypes.bool,
  error: PropTypes.string,
  formatMessage: PropTypes.func.isRequired,
  senderId: PropTypes.string,
  showHeader: PropTypes.bool,
};

RcsPreviewContent.defaultProps = {
  content: {},
  device: ANDROID,
  isUpdating: false,
  error: null,
  senderId: null,
  showHeader: true,
};

export default RcsPreviewContent;
