import React from 'react';
import PropTypes from 'prop-types';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import CapSpin from '@capillarytech/cap-ui-library/CapSpin';
import messages from './messages';

const PreviewSection = ({
  previewDevice,
  setPreviewDevice,
  selectedCustomer,
  formData,
  isUpdatingPreview,
  previewDataHtml,
  content,
  formatMessage,
  PreviewChrome,
}) => (
  <CapRow useLegacy className="test-and-preview-section panel-section">
    <PreviewChrome
      device={previewDevice}
      onDeviceChange={setPreviewDevice}
      customer={selectedCustomer}
      subject={previewDataHtml?.resolvedTitle || formData['template-subject']}
    >
      {isUpdatingPreview && (
        <CapRow type="flex" vertical noWrap align="middle" justify="center" className="loading-container">
          <CapSpin />
          <CapRow useLegacy className="loading-text">{formatMessage(messages.updatingPreview)}</CapRow>
        </CapRow>
      )}
      {!isUpdatingPreview && previewDataHtml && (
        <iframe
          srcDoc={previewDataHtml?.resolvedBody}
          title="Email Preview"
          width="100%"
          height="100%"
          frameBorder="0"
        />
      )}
      {!isUpdatingPreview && !previewDataHtml && (
        <iframe
          srcDoc={content}
          title="Email Preview"
          width="100%"
          height="100%"
          frameBorder="0" />
      )}
    </PreviewChrome>
  </CapRow>
);

PreviewSection.propTypes = {
  previewDevice: PropTypes.string.isRequired,
  setPreviewDevice: PropTypes.func.isRequired,
  selectedCustomer: PropTypes.object,
  formData: PropTypes.object.isRequired,
  isUpdatingPreview: PropTypes.bool.isRequired,
  previewDataHtml: PropTypes.object,
  content: PropTypes.string.isRequired,
  formatMessage: PropTypes.func.isRequired,
  PreviewChrome: PropTypes.elementType.isRequired,
};

PreviewSection.defaultProps = {
  selectedCustomer: null,
  previewDataHtml: null,
};

export default PreviewSection;
