/**
*
* PreviewSideBar
*
*/

import PropTypes from 'prop-types';

import React from 'react';
import { CapTab, CapIcon } from '@capillarytech/cap-ui-library';
import { get, isEmpty} from 'lodash';
import TemplatePreview from '../TemplatePreview';
import '../PreviewSideBar/_previewsidebar.scss';
import { MOBILE_PUSH } from '../../v2Containers/CreativesContainer/constants';
import { INAPP } from '../../v2Containers/App/constants';
import { ANDROID, IOS } from '../../v2Containers/InApp/constants';
import { getCtaObject } from '../../v2Containers/InApp/utils';
import { CAROUSEL, VIDEO } from '../../v2Containers/MobilePushNew/constants';
import { DEVICE_TYPES, IPHONE } from './constants';

class MobilePushPreviewV2 extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.goToEdit = this.goToEdit.bind(this);
    this.goToDuplicate = this.goToDuplicate.bind(this);
    this.changeDevice = this.changeDevice.bind(this);
    this.getPreview = this.getPreview.bind(this);
    this.setContent = this.setContent.bind(this);
    this.goToDuplicate = this.goToDuplicate.bind(this);
    // Check for INAPP channel structure (versions.base.content.ANDROID/IOS) or MOBILE_PUSH structure (versions.base.ANDROID/IOS)
    const { channel, templateData } = props;
    let hasAndroid;
    let hasIos;
    if (channel === INAPP.toUpperCase()) {
      hasAndroid = get(templateData, 'versions.base.content.ANDROID') || get(templateData, 'androidContent');
      hasIos = get(templateData, 'versions.base.content.IOS') || get(templateData, 'iosContent');
    } else {
      hasAndroid = get(templateData, 'versions.base.ANDROID') || get(templateData, 'androidContent.title');
      hasIos = get(templateData, 'versions.base.IOS') || get(templateData, 'iosContent.title');
    }
    let device = "android";
    if (hasAndroid) {
      device = 'android';
    } else if (hasIos) {
      device = 'ios';
    }
    this.state = {
      device,
      content: this.setContent(props.templateData, device, this.props.channel),
    };
  }

  setContent(templateData, device, channel) {
    let content;
    if (channel === INAPP.toUpperCase()) {
      const androidContent = get(templateData, 'versions.base.content.ANDROID') || get(templateData, 'androidContent');
      const iosContent = get(templateData, 'versions.base.content.IOS') || get(templateData, 'iosContent');
      const isBeeFreeTemplate = get(androidContent, 'isBEEeditor') || get(iosContent, 'isBEEeditor');
      if (isBeeFreeTemplate) {
        // Normalize device to 'android' or 'ios' for comparison
        const normalizedDevice = device === IPHONE ? DEVICE_TYPES.IOS : device?.toLowerCase();
        const isAndroid = normalizedDevice === ANDROID.toLowerCase();
        content = {
          inAppPreviewContent: isAndroid ? androidContent?.beeHtml : iosContent?.beeHtml,
          isBeeFreeTemplate: true,
        };
        return content;
      }
      const androidPreviewContent = {
        templateTitle: androidContent?.title,
        templateMsg: androidContent?.message,
        mediaPreview: { inAppImageSrcAndroid: androidContent?.expandableDetails?.image },
        ctaData: getCtaObject(androidContent?.expandableDetails?.ctas),
      };
      const iosPreviewContent = {
        templateTitle: iosContent?.title,
        templateMsg: iosContent?.message,
        mediaPreview: { inAppImageSrcIos: iosContent?.expandableDetails?.image },
        ctaData: getCtaObject(iosContent?.expandableDetails?.ctas),
      };
      // Normalize device to 'android' or 'ios' for comparison
      const normalizedDevice = device === IPHONE ? DEVICE_TYPES.IOS : device?.toLowerCase();
      const isAndroid = normalizedDevice === ANDROID.toLowerCase();
      content = {
        inAppPreviewContent: isAndroid ? androidPreviewContent : iosPreviewContent,
        templateLayoutType: isAndroid ? androidContent?.bodyType : iosContent?.bodyType,
      };
    } else if (channel === MOBILE_PUSH) {
      const androidContent = get(templateData, 'versions.base.ANDROID') || get(templateData, 'androidContent');
      const iosContent = get(templateData, 'versions.base.IOS') || get(templateData, 'iosContent');

      const data = device?.toLowerCase() === "android" ? androidContent : iosContent;
      const {
        title = '', message = '', type = '', expandableDetails: {
          ctas = [], image = '', media = [], carouselData = [],
        } = {},
      } = data || {};

      // Handle video/GIF content from expandableDetails.media array (new format)
      let bodyVideo = {};
      let bodyGif = '';
      let bodyImage = image;

      if (media?.length > 0) {
        const mediaItem = media[0];
        const { type: mediaType, url } = mediaItem;
        if (mediaType === VIDEO) {
          // Distinguish between actual video and GIF based on URL extension
          if (url && url?.toLowerCase()?.includes('.gif')) {
            bodyGif = url;
          } else {
            bodyVideo = {
              videoSrc: url,
              videoPreview: url,
            };
          }
          // Clear bodyImage when we have video/GIF content
          bodyImage = '';
        }
      }

      content = {
        header: title,
        bodyText: message,
        bodyImage,
        bodyVideo,
        bodyGif,
        actions: [],
        appName: templateData?.appName,
        carouselData,
      };

      // Map CTAs consistently for both Android and iOS
      if (ctas?.length > 0 && type !== CAROUSEL) {
        content.actions = ctas.map((cta) => {
          const {
            actionText, type: Type, actionLink, deepLinkKeys,
          } = cta || {};
          return {
            label: actionText || '',
            type: Type || '',
            url: actionLink || '',
            deepLinkKeys: deepLinkKeys || [],
          };
        });
      }
    }
    return content;
  }

  getPreview(device) {
    // Normalize device to 'android' or 'ios' for comparison
    const normalizedDevice = device === IPHONE ? DEVICE_TYPES.IOS : device?.toLowerCase();
    const deviceParam = normalizedDevice === ANDROID.toLowerCase() ? ANDROID : IOS;
    return (
      <TemplatePreview
        device={this.props.channel === INAPP.toUpperCase() ? deviceParam : device}
        channel={this.props.channel}
        content={this.state.content || ''}
        templateData={this.props.templateData}
        templateLayoutType={this.state.content.templateLayoutType || ''}
      />
    );
  }

  goToDuplicate() {
    this.props.onDuplicateClick(this.props.templateData);
    this.props.handleClose();
  }

  changeDevice(device) {
    const content = this.setContent(this.props.templateData, device, this.props.channel);
    this.setState({device, content });
  }

  goToEdit(e, path) {
    this.props.onEditClick(e, this.props.templateData._id, this.props.templateData.modeType, path);
  }

  render() {
    const {templateData} = this.props;
    let hasAndroid;
    let hasIos;
    if (this.props.channel === MOBILE_PUSH) {
      hasAndroid = get(templateData, 'versions.base.ANDROID') || get(templateData, 'androidContent.title');
      hasIos = get(templateData, 'versions.base.IOS') || get(templateData, 'iosContent.title');
    } else if (this.props.channel === INAPP.toUpperCase()) {
      hasAndroid = get(templateData, 'versions.base.content.ANDROID') || get(templateData, 'androidContent');
      hasIos = get(templateData, 'versions.base.content.IOS') || get(templateData, 'iosContent');
    }
    const hasBothAndroidAndIos = hasAndroid && hasIos;
    return (
      <div>
        <div className="devices">
          {!isEmpty(templateData)
            && ( hasBothAndroidAndIos ? (
              <CapTab
                panes={[
                  {
                    content: this.getPreview('android'),
                    tab: <CapIcon type="android" size="m" />,
                    key: 'android',
                  },
                  {
                    content: this.getPreview('iphone'),
                    tab: <CapIcon type="ios" size="m" />,
                    key: 'iphone',
                  },
                ]}
                onChange={(activeKey) => this.changeDevice(activeKey)}
                tabBarStyle={{margin: 'auto', width: '38%', justifyContent: 'center'}}
              />
            ) : (
              (hasAndroid || hasIos) && this.getPreview(hasAndroid ? 'android' : 'ios')
            ))
          }
        </div>
      </div>
    );
  }
}

MobilePushPreviewV2.propTypes = {
  templateData: PropTypes.object.isRequired,
  channel: PropTypes.string.isRequired,
  handleClose: PropTypes.func,
  onEditClick: PropTypes.func,
  onDuplicateClick: PropTypes.func,
};

export default MobilePushPreviewV2;
