/**
 * ViberPreviewContent Component
 *
 * Renders Viber message preview on Android and iOS device mockups
 * Uses SMS device frame and navigation bar
 * Body content follows TemplatePreview Viber structure
 */

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 CapTooltip from '@capillarytech/cap-ui-library/CapTooltip';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import {
  ANDROID,
  IOS,
  ANDROID_DEVICE_NAME,
  IOS_DEVICE_NAME,
  VIBER_ACCOUNT_NAME,
  MEDIA_TYPE_CAROUSEL,
} from '../constants';
import messages from '../messages';
import videoPlay from '../../../assets/videoPlay.svg';
import ViberCarouselPreviewCards from './ViberCarouselPreviewCards';

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

const getTrimmedText = (value = '') => (value ?? '').trim();
const hasTrimmedText = (value = '') => Boolean(getTrimmedText(value));

const ViberPreviewContent = ({
  content,
  device,
  isUpdating,
  error,
  formatMessage,
  accountName,
  brandName,
  showHeader,
}) => {
  // Get device image based on device type
  const deviceImage = device === ANDROID ? smsMobileAndroid : smsMobileIos;
  const deviceName = device === ANDROID ? ANDROID_DEVICE_NAME : IOS_DEVICE_NAME;

  // Extract Viber content
  const viberContent = content?.viberPreviewContent || {};
  const {
    messageContent = '',
    imageURL = '',
    videoParams = {},
    buttonText = '',
    type = '',
    cards = [],
    showCarouselEditorPreview = false,
  } = viberContent;
  const hasCarouselContent = type === MEDIA_TYPE_CAROUSEL;

  const cardHasMeaningfulContent = (card) => {
    if (!card || typeof card !== 'object') return false;
    if (hasTrimmedText(card?.text)) return true;
    if (hasTrimmedText(card?.mediaUrl)) return true;
    const buttons = card?.buttons ?? [];
    return buttons.some((button) => hasTrimmedText(button?.title));
  };

  const hasMeaningfulCarousel =
    hasCarouselContent &&
    Array.isArray(cards) &&
    cards.length > 0 &&
    cards.some(cardHasMeaningfulContent);

  const showCarouselInPreview =
    hasCarouselContent && (Boolean(showCarouselEditorPreview) || hasMeaningfulCarousel);

  const previewCarouselCards =
    hasCarouselContent && Array.isArray(cards) && cards.length ? cards : hasCarouselContent ? [{}] : [];

  const trimmedMessageContent = getTrimmedText(messageContent);
  const trimmedButtonText = getTrimmedText(buttonText);

  // Get account name (first letter for icon)
  const accountIcon = (accountName || brandName || 'V')[0]?.toUpperCase();
  const displayBrandName = brandName || accountName || VIBER_ACCOUNT_NAME;
  // Get current time for timestamp
  const currentTime = new Date();
  const hours = currentTime.getHours();
  const minutes = currentTime.getMinutes();
  const ampm = hours >= 12 ? 'PM' : 'AM';
  const displayHours = hours % 12 || 12;
  const displayMinutes = minutes < 10 ? `0${minutes}` : minutes;
  const timestamp = `${displayHours}:${displayMinutes} ${ampm}`;
  // 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} viber-content-overlay`}>
          <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} viber-content-overlay`}>
          <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>
    );
  }

  // Check if there's any content to display (whitespace-only strings do not count)
  const hasContent = Boolean(
    trimmedMessageContent
    || hasTrimmedText(imageURL)
    || videoParams?.viberVideoSrc
    || trimmedButtonText
    || hasMeaningfulCarousel
    || (hasCarouselContent && showCarouselEditorPreview)
  );

  // Render normal Viber preview
  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} ${device === ANDROID ? 'viber-content-overlay' : ''} viber-preview viber-${device}`}>
        {/* Navigation Bar (same as SMS) */}
        <CapRow className={`sms-navigation-bar ${device === ANDROID && !showHeader ? 'viber-navigation-bar' : ''}`}>
          <CapIcon type="chevron-left" className="sms-back-arrow" />
          <CapLabel type="label16" className="sms-sender-id">
            {displayBrandName}
          </CapLabel>
          <CapIcon type="info" className="sms-menu-icon viber-menu-icon" />
        </CapRow>

        {/* Viber Message Container */}
        {hasContent && (
          <CapRow className={`viber-message-container ${device !== ANDROID ? 'viber-message-container-ios' : ''}`}>
            {/* Brand Name Display (from TemplatePreview line 1136) */}
            <CapRow className={`msg-container viber-preview ${showCarouselInPreview ? 'viber-preview-carousel' : ''}`}>
              {/* Account Icon (from TemplatePreview line 1146-1160) */}
              {!hasCarouselContent && (
                <CapRow className="viber-account-icon">
                  {accountIcon}
                </CapRow>
              )}

              {/* Message Bubble (from TemplatePreview line 1161-1223) */}
              <CapRow className={`message-pop align-left viber-message-pop ${showCarouselInPreview ? 'viber-message-pop-carousel' : ''}`}>
                {/* Text Viber preview */}
                {trimmedMessageContent && !hasCarouselContent && (
                  <CapLabel type="label15" className="viber-message-text">{messageContent}</CapLabel>
                )}

                {/* Image Viber preview */}
                {hasTrimmedText(imageURL) && (
                  <CapImage
                    src={imageURL}
                    className="viber-image-preview"
                    alt="Viber image preview"
                  />
                )}

                {/* Video Viber preview */}
                {videoParams?.viberVideoSrc && (
                  <CapTooltip
                    title={formatMessage(messages.videoPreviewTooltip)}
                  >
                    <CapRow className="video-preview">
                      <CapImage
                        src={videoParams?.viberVideoPreviewImg || videoParams?.viberVideoSrc}
                        className="viber-video-preview"
                        alt={formatMessage(messages.previewGenerated)}
                      />
                      <CapRow className="icon-position">
                        <CapImage
                          src={videoPlay}
                          alt="Play video"
                        />
                      </CapRow>
                    </CapRow>
                  </CapTooltip>
                )}

                {/* Button Viber preview */}
                {trimmedButtonText && (
                  <CapLabel className="viber-button-base">
                    <p className="viber-button-card-text">
                      {buttonText}
                    </p>
                  </CapLabel>
                )}
                {/* Carousel Viber preview */}
                {showCarouselInPreview && (
                  <>
                    <CapRow className="viber-carousel-message-pop">
                      {trimmedMessageContent ? (
                        <CapLabel
                          type="label15"
                          className="message-pop-item align-left viber-message-text viber-carousel-message-box-text"
                        >
                          {messageContent}
                        </CapLabel>
                      ) : (
                        <CapRow className="viber-carousel-message-box-placeholder" />
                      )}
                      <CapLabel type="label1" className="viber-carousel-message-timestamp">
                        {timestamp}
                      </CapLabel>
                    </CapRow>

                    <CapRow className="viber-carousel-cards-pop">
                      <ViberCarouselPreviewCards cards={previewCarouselCards} />
                    </CapRow>
                  </>
                )}
                {!showCarouselInPreview && (
                  <CapLabel type="label1" className="viber-timestamp">
                    {timestamp}
                  </CapLabel>
                )}
                <CapRow className="empty-placeholder" />
              </CapRow>

            </CapRow>

          </CapRow>
        )}

        {/* No Content State */}
        {!hasContent && (
          <CapRow className="viber-message-container">
            <CapRow className="sms-message-bubble">
              <CapRow className="sms-message-text">
                {formatMessage(messages.noContent)}
              </CapRow>
            </CapRow>
          </CapRow>
        )}
      </CapRow>
    </CapRow>
  );
};

ViberPreviewContent.propTypes = {
  content: PropTypes.shape({
    viberPreviewContent: PropTypes.shape({
      messageContent: PropTypes.string,
      imageURL: PropTypes.string,
      videoParams: PropTypes.shape({
        viberVideoSrc: PropTypes.string,
        viberVideoPreviewImg: PropTypes.string,
      }),
      buttonText: PropTypes.string,
      type: PropTypes.string,
      cards: PropTypes.arrayOf(PropTypes.shape({
        text: PropTypes.string,
        mediaUrl: PropTypes.string,
        buttons: PropTypes.arrayOf(PropTypes.shape({
          title: PropTypes.string,
          action: PropTypes.string,
        })),
      })),
      showCarouselEditorPreview: PropTypes.bool,
    }),
  }),
  device: PropTypes.oneOf([ANDROID, IOS]),
  isUpdating: PropTypes.bool,
  error: PropTypes.string,
  formatMessage: PropTypes.func.isRequired,
  accountName: PropTypes.string,
  brandName: PropTypes.string,
  showHeader: PropTypes.bool,
};

ViberPreviewContent.defaultProps = {
  content: {},
  device: ANDROID,
  isUpdating: false,
  error: null,
  accountName: null,
  brandName: null,
  showHeader: true,
};

export default ViberPreviewContent;
