
/**
 * UnifiedPreview Component
 *
 * Main preview component that provides consistent preview experience across all channels
 * Routes to channel-specific preview content components
 */

import React, { useState } from 'react';
import PropTypes from 'prop-types';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import CapSpin from '@capillarytech/cap-ui-library/CapSpin';
import CapIcon from '@capillarytech/cap-ui-library/CapIcon';
import PreviewHeader from './PreviewHeader';
import DeviceFrame from './DeviceFrame';
import EmailPreviewContent from './EmailPreviewContent';
import SmsPreviewContent from './SmsPreviewContent';
import WhatsAppPreviewContent from './WhatsAppPreviewContent';
import RcsPreviewContent from './RcsPreviewContent';
import InAppPreviewContent from './InAppPreviewContent';
import MobilePushPreviewContent from './MobilePushPreviewContent';
import ViberPreviewContent from './ViberPreviewContent';
import ZaloPreviewContent from './ZaloPreviewContent';
import WebPushPreviewContent from './WebPushPreviewContent';
import { CHANNELS, DESKTOP, TABLET, MOBILE, ANDROID, IOS } from '../constants';
import messages from '../messages';
import './_unifiedPreview.scss';

const UnifiedPreview = ({
  channel,
  content,
  device,
  showDeviceToggle,
  selectedCustomer,
  isUpdating,
  error,
  onDeviceChange,
  formatMessage,
  lastModified,
  updatedByName,
  showHeader, // Default to true for Test and Preview flow, false for channel component previews
}) => {
  /**
   * Render channel-specific preview content
   * For Phase 5, we'll render placeholders
   * Phase 6+ will implement actual content components
   */
  const [isFullscreenOpen, setIsFullscreenOpen] = useState(false);
  const renderChannelContent = () => {
    // Phase 5: Placeholder content for all channels
    // Phase 6+: Import and render actual channel-specific components

    switch (channel) {
      case CHANNELS.EMAIL:
        return (
          <EmailPreviewContent
            content={content?.resolvedBody || ''}
            subject={content?.resolvedTitle || ''}
            device={device}
            isUpdating={isUpdating}
            error={error}
            formatMessage={formatMessage}
          />
        );

      case CHANNELS.SMS: {
        // SMS content is a string, not an object
        let smsContent = typeof content === 'string' ? content : (content?.resolvedBody || content || '');

        // Check if content is a JSON stringified value (starts and ends with quotes)
        // This can happen if content was stringified somewhere in the flow
        if (typeof smsContent === 'string' && smsContent.length > 0) {
          // Check if it's a JSON string (starts with " and ends with ")
          // Handle both single and double stringification: "text" or "\"text\""
          if (smsContent.startsWith('"') && smsContent.endsWith('"')) {
            try {
              // Try to parse it as JSON to remove the quotes
              let parsed = JSON.parse(smsContent);
              // If parsing succeeds but result is still a string with quotes, parse again
              if (typeof parsed === 'string' && parsed.startsWith('"') && parsed.endsWith('"')) {
                parsed = JSON.parse(parsed);
              }
              smsContent = parsed;
            } catch (e) {
              // If parsing fails, it's not a JSON string, keep as is
              // But remove surrounding quotes if they exist
              if (smsContent.startsWith('"') && smsContent.endsWith('"') && smsContent.length >= 2) {
                smsContent = smsContent.slice(1, -1);
                // Check if there are still quotes after removing outer ones (double stringified)
                if (smsContent.startsWith('"') && smsContent.endsWith('"') && smsContent.length >= 2) {
                  smsContent = smsContent.slice(1, -1);
                }
              }
            }
          }
        }

        return (
          <SmsPreviewContent
            content={smsContent}
            device={device}
            isUpdating={isUpdating}
            error={error}
            formatMessage={formatMessage}
            senderId={content?.senderId}
            showHeader={showHeader}
          />
        );
      }

      case CHANNELS.WHATSAPP: {
        // WhatsApp content is an object with templateMsg, media, CTA, etc.
        const whatsappContent = typeof content === 'object' ? content : {};
        return (
          <WhatsAppPreviewContent
            content={whatsappContent}
            device={device}
            isUpdating={isUpdating}
            error={error}
            formatMessage={formatMessage}
            accountName={content?.accountName || whatsappContent?.accountName}
          />
        );
      }

      case CHANNELS.RCS: {
        // RCS content is an object with rcsTitle, rcsDesc, rcsImageSrc, suggestions, etc.
        const rcsContent = typeof content === 'object' ? content : {};
        return (
          <RcsPreviewContent
            content={rcsContent}
            device={device}
            isUpdating={isUpdating}
            error={error}
            formatMessage={formatMessage}
            senderId={content?.senderId}
            showHeader={showHeader}
          />
        );
      }

      case CHANNELS.INAPP: {
        // InApp content is an object with inAppPreviewContent containing mediaPreview, templateTitle, templateMsg, ctaData
        const inAppContent = typeof content === 'object' ? content : {};
        return (
          <InAppPreviewContent
            content={inAppContent}
            device={device}
            isUpdating={isUpdating}
            error={error}
            formatMessage={formatMessage}
            templateLayoutType={content?.templateLayoutType}
            showHeader={showHeader}
          />
        );
      }

      case CHANNELS.MOBILEPUSH: {
        // MobilePush content is an object with androidContent and iosContent
        const mobilePushContent = typeof content === 'object' ? content : {};
        return (
          <MobilePushPreviewContent
            content={mobilePushContent}
            device={device}
            isUpdating={isUpdating}
            error={error}
            formatMessage={formatMessage}
          />
        );
      }

      case CHANNELS.VIBER: {
        // Viber content is an object with viberPreviewContent
        const viberContent = typeof content === 'object' ? content : {};
        return (
          <ViberPreviewContent
            content={viberContent}
            device={device}
            isUpdating={isUpdating}
            error={error}
            formatMessage={formatMessage}
            accountName={content?.accountName || viberContent?.accountName}
            brandName={content?.brandName || viberContent?.brandName}
            showHeader={showHeader}
          />
        );
      }

      case CHANNELS.ZALO: {
        // Zalo preview - external preview link
        // Matches TemplatePreview structure (lines 1356-1385)
        const zaloContent = typeof content === 'object' ? content : {};
        return (
          <ZaloPreviewContent
            content={zaloContent}
            formatMessage={formatMessage}
            fullMode // Always use creative mode for Test and Preview
          />
        );
      }

      case CHANNELS.WEBPUSH: {
        // WebPush content arrives as a JSON string (from getCurrentContent or preview API response)
        let webPushOuter = {};
        try {
          webPushOuter = typeof content === 'string' ? JSON.parse(content) : (typeof content === 'object' && content !== null ? content : {});
        } catch (e) {
          webPushOuter = {};
        }
        const { content: webPushInner = {} } = webPushOuter;
        const {
          title,
          message,
          iconImageUrl,
          cta,
          expandableDetails = {},
        } = webPushInner;
        const { media: webPushMedia = [], ctas: webPushCtas = [] } = expandableDetails;
        const webPushButtons = webPushCtas.map(({ title: text = '', actionLink: url = '', type = '' }) => ({
          text,
          url,
          type,
        }));
        return (
          <WebPushPreviewContent
            notificationTitle={title || ''}
            notificationBody={message || ''}
            imageSrc={webPushMedia[0]?.url || ''}
            brandIconSrc={iconImageUrl || ''}
            buttons={webPushButtons}
            url={cta?.actionLink || ''}
            isUpdating={isUpdating}
            error={error}
            isFullscreenOpen={isFullscreenOpen}
            setIsFullscreenOpen={setIsFullscreenOpen}
            selectedCustomer={selectedCustomer}
          />
        );
      }

      default:
        return (
          <div className="channel-preview-placeholder">
            <CapIcon type="question-circle" className="question-circle" />
            <h3>Unknown Channel</h3>
            <p>
              Channel:
              {' '}
              {channel}
            </p>
          </div>
        );
    }
  };

  const showToggle = channel !== CHANNELS.WEBPUSH && showDeviceToggle;

  /**
   * Render loading state for all channels
   */
  if (isUpdating) {
    return (
      <CapRow className="unified-preview unified-preview-loading">
        {showHeader && (
          <PreviewHeader
            selectedCustomer={selectedCustomer}
            device={device}
            showDeviceToggle={showToggle}
            onDeviceChange={onDeviceChange}
            channel={channel}
            setIsFullscreenOpen={setIsFullscreenOpen}
          />
        )}
        <CapRow className="preview-loading-container">
          <CapSpin size="large" />
          <div className="loading-text">
            {formatMessage(messages.updatingPreviewForRoot)}
          </div>
        </CapRow>
      </CapRow>
    );
  }

  /**
   * Render error state for all channels
   */
  if (error) {
    return (
      <CapRow className="unified-preview unified-preview-error">
        {showHeader && (
          <PreviewHeader
            selectedCustomer={selectedCustomer}
            device={device}
            showDeviceToggle={showToggle}
            onDeviceChange={onDeviceChange}
            channel={channel}
            setIsFullscreenOpen={setIsFullscreenOpen}
          />
        )}
        <CapRow className="preview-error-container">
          <CapIcon type="exclamation-circle" className="exclamation-circle" />
          <div className="error-text">
            {formatMessage(messages.previewError)}
          </div>
          <div className="error-message">{error}</div>
        </CapRow>
      </CapRow>
    );
  }

  /**
   * Render preview content for all channels
   * PreviewHeader is shown only when showHeader is true (for Test and Preview flow)
   * Channel-specific content will be in separate files in future phases
   */
  return (
    <CapRow className="unified-preview">
      {/* PreviewHeader - shown only in Test and Preview flow, hidden in channel component previews */}
      {showHeader && (
        <PreviewHeader
          selectedCustomer={selectedCustomer}
          device={device}
          showDeviceToggle={showToggle}
          onDeviceChange={onDeviceChange}
          channel={channel}
          setIsFullscreenOpen={setIsFullscreenOpen}
        />
      )}

      {/* Channel-specific preview content */}
      <CapRow className={`preview-content-container ${!showHeader ? 'preview-content-container-no-header' : ''}`}>
        {[CHANNELS.EMAIL, CHANNELS.SMS, CHANNELS.WHATSAPP, CHANNELS.RCS, CHANNELS.INAPP, CHANNELS.MOBILEPUSH, CHANNELS.VIBER, CHANNELS.WEBPUSH].includes(channel) ? (
          renderChannelContent()
        ) : (
          <DeviceFrame device={device || DESKTOP}>
            {renderChannelContent()}
          </DeviceFrame>
        )}
      </CapRow>

      {/* Metadata (optional) */}
      {(lastModified || updatedByName) && (
        <CapRow className="preview-metadata">
          {lastModified && (
            <span className="metadata-item">
              {formatMessage(messages.lastModified)}
              :
              {' '}
              {lastModified}
            </span>
          )}
          {updatedByName && (
            <span className="metadata-item">
              {formatMessage(messages.by)}
              {' '}
              {updatedByName}
            </span>
          )}
        </CapRow>
      )}
    </CapRow>
  );
};

UnifiedPreview.propTypes = {
  // Core
  channel: PropTypes.oneOf(Object.values(CHANNELS)).isRequired,
  content: PropTypes.oneOfType([PropTypes.object, PropTypes.string]).isRequired,

  // Display options
  device: PropTypes.oneOf([DESKTOP, TABLET, MOBILE, ANDROID, IOS]),
  showDeviceToggle: PropTypes.bool,

  // Header info
  selectedCustomer: PropTypes.shape({
    name: PropTypes.string,
    email: PropTypes.string,
    mobile: PropTypes.string,
  }),

  // State
  isUpdating: PropTypes.bool,
  error: PropTypes.string,

  // Callbacks
  onDeviceChange: PropTypes.func,

  // Metadata (optional)
  lastModified: PropTypes.string,
  updatedByName: PropTypes.string,

  // Intl
  formatMessage: PropTypes.func.isRequired,

  // Header display
  showHeader: PropTypes.bool, // Show PreviewHeader (true for Test and Preview flow, false for channel component previews)
};

UnifiedPreview.defaultProps = {
  device: DESKTOP,
  showDeviceToggle: false,
  selectedCustomer: null,
  isUpdating: false,
  error: null,
  onDeviceChange: () => {},
  lastModified: null,
  updatedByName: null,
  showHeader: true, // Default to true for Test and Preview flow
};

export default UnifiedPreview;
