/**
 * WhatsAppPreviewContent Component
 *
 * Renders WhatsApp message preview on Android and iOS device mockups
 * Based on old TemplatePreview WhatsApp rendering (lines 1229-1328)
 * Uses same CSS classes and structure as TemplatePreview
 */

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 { ANDROID, IOS } from '../constants';
import messages from '../messages';
import { getWhatsappQuickReply, getWhatsappCarouselButtonView } from '../../../v2Containers/Whatsapp/utils';
import { QUICK_REPLY, PHONE_NUMBER, WHATSAPP_CATEGORIES, TEMPLATE_VARIABLE_REGEX } from '../../../v2Containers/Whatsapp/constants';
import videoPlay from '../../../assets/videoPlay.svg';
import whatsappImageEmptyPreview from '../../TemplatePreview/assets/images/empty_image_preview.svg';
import whatsappVideoEmptyPreview from '../../TemplatePreview/assets/images/empty_video_preview.svg';

// Import device mockup images
const whatsappMobileAndroid = require('../../../assets/whatsapp_android.png');
const whatsappMobileIos = require('../../../assets/whatsapp_ios.png');

const { CapLabelInline } = CapLabel;

const WhatsAppPreviewContent = ({
  content,
  device,
  isUpdating,
  error,
  formatMessage,
  accountName,
}) => {
  // Get device image based on device type
  const deviceImage = device === IOS ? whatsappMobileIos : whatsappMobileAndroid;

  // Render CTA buttons (matching TemplatePreview renderWhatsappCtaPreview)
  const renderCtaButtons = () => {
    const renderArray = [];
    const { ctaData = [] } = content || {};
    if (ctaData?.length) {
      renderArray.push(<CapDivider key="divider" className="whatsapp-divider" />);
      ctaData.forEach((i) => {
        const { ctaType, type, text } = i || {};
        if (text) {
          renderArray.push(
            <CapLabel key={`cta-${type}-${text}`} type="label21" className="whatsapp-cta-preview">
              {type !== WHATSAPP_CATEGORIES.authentication && (
                <CapIcon
                  type={(ctaType || type) === PHONE_NUMBER ? 'call' : 'launch'}
                  size="xs"
                />
              )}
              {text}
            </CapLabel>
          );
        }
      });
    }
    return renderArray;
  };

  // Render Quick Reply buttons
  const renderQuickReplyButtons = () => {
    const { quickReplyData = [] } = content || {};
    if (!quickReplyData.length) return null;

    return getWhatsappQuickReply(
      {
        buttons: quickReplyData,
        buttonType: QUICK_REPLY,
      },
      true
    );
  };

  // Render URL preview card
  const renderUrlPreview = (metaTags) => {
    if (!metaTags) return null;

    const {
      image = '', title = '', description = '', url = '',
    } = metaTags;
    return (
      <>
        {image && (
          <CapImage
            src={image}
            alt={formatMessage(messages.urlPreviewImage)}
            className="url-preview-image"
          />
        )}
        {title && (
          <CapLabel type="label8">
            {title}
          </CapLabel>
        )}
        {description && (
          <CapLabel className="url-preview-description">
            {description}
          </CapLabel>
        )}
        {url && (
          <CapLabel className="url-preview">
            {url}
          </CapLabel>
        )}
      </>
    );
  };

  // Render WhatsApp structure (common for all states) - Based on TemplatePreview lines 1229-1328
  const renderWhatsAppStructure = (contentSection) => (
    <CapRow className="whatsapp-preview-wrapper">
      <CapRow className="shell-v2-whatsapp align-center">
        <CapImage
          className="preview-image"
          src={deviceImage}
          alt={formatMessage(messages.previewGenerated)}
        />
        <CapLabel className={`whatsapp-brand-name whatsapp-brand-name-${device}`}>
          {accountName || ''}
        </CapLabel>
        <CapRow className={`msg-container whatsapp-message-container ${content?.carouselData && 'msg-container-carousel'}`}>
          <CapRow
            className={`message-pop align-left whatsapp-message-pop ${content?.carouselData && 'message-pop-carousel'}`}
          >
            <CapRow className="whatsapp-content">
              {contentSection}
            </CapRow>
          </CapRow>
          {content?.carouselData && (
            <CapRow className="scroll-container">
              {content.carouselData.map((data) => (
                <CapRow
                  key={`carousel-${data?.bodyText || data?.imageSrc || data?.videoPreviewImg || Math.random()}`}
                  className="message-pop align-left message-pop-carousel whatsapp-message-pop-carousel"
                >
                  <CapRow className="whatsapp-content">
                    {content?.carouselMediaType === 'image' && (
                      <CapImage
                        src={data?.imageSrc ? data.imageSrc : whatsappImageEmptyPreview}
                        className="whatsapp-image"
                        alt={formatMessage(messages.previewGenerated)}
                      />
                    )}
                    {content?.carouselMediaType === 'video' && (
                      <CapTooltip
                        title={formatMessage(messages.videoPreviewTooltip)}
                      >
                        <CapRow className="video-preview">
                          <CapImage
                            src={data?.videoPreviewImg ? data.videoPreviewImg : whatsappVideoEmptyPreview}
                            className="whatsapp-image"
                            alt={formatMessage(messages.previewGenerated)}
                          />
                          <CapRow className="icon-position">
                            <CapImage
                              className="video-icon"
                              src={videoPlay}
                              alt="Play"
                            />
                          </CapRow>
                        </CapRow>
                      </CapTooltip>
                    )}
                    <CapLabel type="label5">
                      {content?.isEditFlow ? data?.updatedBodyText?.join('') : data?.bodyText}
                    </CapLabel>
                    {getWhatsappCarouselButtonView(data?.buttons, true)}
                  </CapRow>
                </CapRow>
              ))}
            </CapRow>
          )}
        </CapRow>
      </CapRow>
    </CapRow>
  );

  // Determine content section based on state (following EmailPreviewContent pattern)
  let contentSection;
  if (isUpdating) {
    // Loading state
    contentSection = (
      <CapRow className="whatsapp-loading-container">
        <CapSpin size="large" />
        <CapRow className="whatsapp-loading-text">
          {formatMessage(messages.updatingPreview)}
        </CapRow>
      </CapRow>
    );
  } else if (error) {
    // Error state
    contentSection = (
      <CapRow className="whatsapp-error-container">
        <CapIcon type="exclamation-circle" className="exclamation-circle" />
        <CapRow className="whatsapp-error-text">
          {formatMessage(messages.previewError)}
        </CapRow>
        <CapRow className="whatsapp-error-message">{error}</CapRow>
      </CapRow>
    );
  } else if (content) {
    // Normal state with content - matching TemplatePreview structure exactly
    contentSection = (
      <>
        {/* URL Preview */}
        {content?.showUrlPreview && renderUrlPreview(content?.metaTagsDetails)}

        {/* Image Preview */}
        {content?.whatsappImageSrc && (
          TEMPLATE_VARIABLE_REGEX.test(content.whatsappImageSrc) ? (
            <CapRow className="whatsapp-image-url-placeholder">
              <CapIcon type="picture" size="s" className="whatsapp-image-url-placeholder-icon" />
              <CapLabelInline type="label2" className="whatsapp-image-url-placeholder-text">
                {content.whatsappImageSrc}
              </CapLabelInline>
            </CapRow>
          ) : (
            <CapImage
              src={content.whatsappImageSrc}
              className="whatsapp-image"
              alt={formatMessage(messages.previewGenerated)}
              onError={(e) => { e.target.src = whatsappImageEmptyPreview; }}
            />
          )
        )}

        {/* Video Preview */}
        {content?.whatsappVideoPreviewImg && (
          <CapTooltip
            title={formatMessage(messages.videoPreviewTooltip)}
          >
            <CapRow className="video-preview">
              <CapImage
                src={content.whatsappVideoPreviewImg}
                className="whatsapp-image"
                alt={formatMessage(messages.previewGenerated)}
              />
              <CapRow className="icon-position">
                <CapImage
                  className="video-icon"
                  src={videoPlay}
                  alt="Play"
                />
              </CapRow>
            </CapRow>
          </CapTooltip>
        )}

        {/* Document Preview */}
        {content?.docPreview && (
          <CapRow className="whatsapp-image">
            {content.docPreview}
          </CapRow>
        )}

        {/* Template Header */}
        {content?.templateHeader && (
          <CapLabel className="whatsapp-template-header-preview">
            {content.templateHeader}
          </CapLabel>
        )}

        {/* Message Text */}
        {content?.templateMsg && (
          <CapLabel type="label5">
            {content?.templateMsg?.split('\n').map((line, index, array) => {
              // Use line content as key, with fallback to index for empty lines
              const lineKey = line || `empty-line-${index}`;
              return (
                <React.Fragment key={lineKey}>
                  {line}
                  {index < array.length - 1 && <br />}
                </React.Fragment>
              );
            })}
          </CapLabel>
        )}

        {/* Template Footer */}
        {content?.templateFooter && (
          <CapLabel className="whatsapp-template-footer-preview">
            {content.templateFooter}
          </CapLabel>
        )}

        {/* CTA Buttons */}
        {renderCtaButtons()}

        {/* Quick Reply Buttons */}
        {renderQuickReplyButtons()}
      </>
    );
  } else {
    // No content state
    contentSection = (
      <CapRow className="whatsapp-no-content">
        {formatMessage(messages.noContent)}
      </CapRow>
    );
  }

  // Render WhatsApp structure with content section
  return renderWhatsAppStructure(contentSection);
};

WhatsAppPreviewContent.propTypes = {
  content: PropTypes.shape({
    templateMsg: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
    templateHeaderPreview: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
    templateFooterPreview: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
    whatsappImageSrc: PropTypes.string,
    whatsappVideoPreviewImg: PropTypes.string,
    docPreview: PropTypes.node,
    showUrlPreview: PropTypes.bool,
    metaTagsDetails: PropTypes.object,
    ctaData: PropTypes.array,
    quickReplyData: PropTypes.array,
  }),
  device: PropTypes.oneOf([ANDROID, IOS]),
  isUpdating: PropTypes.bool,
  error: PropTypes.string,
  formatMessage: PropTypes.func.isRequired,
  accountName: PropTypes.string,
};

WhatsAppPreviewContent.defaultProps = {
  content: {},
  device: ANDROID,
  isUpdating: false,
  error: null,
  accountName: 'Business Account',
};

export default WhatsAppPreviewContent;
