import React from 'react';
import PropTypes from 'prop-types';
import chromeIcon from './assets/chrome-icon.png';
import AndroidMobileChromeHeader from './components/AndroidMobileChromeHeader';
import AndroidMobileExpanded from './components/AndroidMobileExpanded';
import NotificationExpandedContent from './components/NotificationExpandedContent';
import NotificationHeader from './components/NotificationHeader';
import WindowsChromeExpanded from './components/WindowsChromeExpanded';
import IOSHeader from './components/IOSHeader';
import {
  OS_MACOS,
  OS_IOS,
  OS_IPADOS,
  OS_WINDOWS,
  OS_ANDROID_MOBILE,
  OS_ANDROID_TABLET,
  BROWSER_CHROME,
  BROWSER_FIREFOX,
  BROWSER_EDGE,
  BROWSER_OPERA,
  BRAND_ICON_SUPPORTED_BROWSERS,
  BROWSER_DISPLAY_NAMES,
  NOTIFICATION_STATE_COLLAPSED,
  NOTIFICATION_STATE_EXPANDED,
} from './constants';
import {
  getNotificationContainerClassName,
  formatUrlForPreview,
  transformButtonsForPreview,
} from '../utils/previewUtils';

/**
 * NotificationContainer Component
 * 
 * Standalone notification container component that renders the actual notification UI.
 * This component is decoupled from any wrapper containers and can be used
 * in different contexts (main preview, device frame preview, etc.).
 * 
 * The component renders the notification-container div with all its content:
 * - Notification header (icon, title, URL, body)
 * - Expanded content (media image, CTA buttons) when state is 'Expanded'
 * 
 * @param {string} notificationTitle - Title of the notification
 * @param {string} notificationBody - Body text of the notification
 * @param {string} url - URL for the notification
 * @param {string} selectedOS - Operating system name
 * @param {string} selectedBrowser - Browser name
 * @param {string} notificationState - 'Collapsed' or 'Expanded' (default: 'Collapsed')
 * @param {string} className - Additional CSS classes to apply to the container
 * @param {string} icon - Icon asset for the browser (defaults to Chrome)
 * @param {boolean} supportsExpanded - Whether Expanded state is supported for this variant
 * @param {boolean} enableMedia - Whether to render media section when expanded
 * @param {boolean} enableCtas - Whether to render CTA buttons when expanded
 * @param {string} imageSrc - Media/banner image source URL
 * @param {string} brandIconSrc - Brand icon image source URL
 */
const NotificationContainer = ({
  notificationTitle,
  notificationBody,
  url,
  selectedOS,
  selectedBrowser,
  notificationState = NOTIFICATION_STATE_COLLAPSED,
  className = '',
  icon = chromeIcon,
  supportsExpanded = true,
  enableMedia = true,
  enableCtas = true,
  brandIcon = '',
  enableBrandIconPreview = true,
  imageSrc = '',
  brandIconSrc = '',
  buttons = [],
  showSeparateIOSCTAs = false,
}) => {
  // Force expanded UI for Windows when Collapsed state is selected
  // Windows only supports expanded preview - when Windows + Collapsed is selected, render expanded UI
  // Note: If Windows needs separate Collapsed/Expanded states later, remove the second condition
  const isExpanded = (supportsExpanded && notificationState === NOTIFICATION_STATE_EXPANDED) || 
                     (selectedOS === OS_WINDOWS && notificationState === NOTIFICATION_STATE_COLLAPSED);
  const notificationContainerClass = getNotificationContainerClassName(selectedOS, selectedBrowser);
  const stateClass = isExpanded ? 'expanded' : 'collapsed';
  const selectedBrowserLower = (selectedBrowser || '').toLowerCase();

  // Platform detection object - provides clean access to all platform/browser checks
  const platform = {
    parts: notificationContainerClass.split('-'),
    get os() { return this.parts[0]; },
    get browser() { return this.parts.length === 3 ? this.parts[2] : this.parts[1]; },
    get isMacOs() { return selectedOS === OS_MACOS; },
    get isIOS() { return selectedOS === OS_IOS; },
    get isIPadOS() { return selectedOS === OS_IPADOS; },
    get isAndroidMobile() { return this.os === 'android' && this.parts[1] === 'mobile'; },
    get isAndroidTablet() { return this.os === 'android' && this.parts[1] === 'tablet'; },
    get isIOSBrowser() { return this.os === 'ios'; },
    get isIPadOSBrowser() { return this.os === 'ipados'; },
    get isWindows() { return this.os === 'windows'; },
    get supportsBrandIcon() { return BRAND_ICON_SUPPORTED_BROWSERS.includes(selectedBrowserLower); },
    get isMacOsBrandIconBrowser() { return this.isMacOs && this.supportsBrandIcon; },
    get isWindowsExpanded() { return this.isWindows && isExpanded; },
    get isMacOsExpandedBrand() { return this.isMacOs && isExpanded && this.supportsBrandIcon; },
  };

  const displayUrl = formatUrlForPreview(url) || url || '';
  // Use real media image from form/props
  const mediaImageUrl = imageSrc || '';
  // Use real brand icon from form/props, fallback to prop if provided for backward compatibility
  const actualBrandIcon = brandIconSrc || brandIcon || '';
  const shouldShowBrandIconAndroidExpanded =
    (platform.isAndroidMobile || platform.isAndroidTablet) && isExpanded && enableBrandIconPreview && Boolean(actualBrandIcon);
  const ctaButtons = transformButtonsForPreview(buttons);

  // Brand icon preview toggle (set enableBrandIconPreview to false to see no-brand state)
  const shouldShowBrandIcon = (() => {
    // iOS/iPadOS NEVER show brand icons - they use a simple notification style
    if (platform.isIOSBrowser || platform.isIPadOSBrowser) return false;
    
    if (!enableBrandIconPreview || !actualBrandIcon) return false;
    if (platform.isAndroidMobile && !isExpanded) return true;
    if (platform.isAndroidTablet && !isExpanded) return true;
    // macOS: show brand icon for all browsers in collapsed state
    if (platform.isMacOs && !isExpanded) return true;
    // Windows browsers: show brand icon in collapsed state (same as macOS Chrome)
    if (platform.isWindows && !isExpanded) return true;
    return false;
  })();

  const shouldShowBrandIconInExpandedMac = (() => {
    if (!platform.isMacOsExpandedBrand) return false;
    if (!enableBrandIconPreview || !actualBrandIcon) return false;
    return true;
  })();

  const shouldRenderExpandedMedia = (() => {
    if (!enableMedia) return false;
    if (platform.isMacOsExpandedBrand) {
      // For macOS brand browsers, only render if brand icon is available.
      return shouldShowBrandIconInExpandedMac;
    }
    return Boolean(mediaImageUrl);
  })();

  const containerClasses = [
    'notification-container',
    notificationContainerClass,
    stateClass,
    className,
    platform.isWindowsExpanded ? 'windows-chrome-expanded' : '',
  ]
    .filter(Boolean)
    .join(' ')
    .trim();

  // Get browser display name for Windows expanded notifications
  const getBrowserDisplayName = (browser) => {
    return BROWSER_DISPLAY_NAMES[browser] || browser;
  };

  // Check if we need to render separate CTA container for iOS + Collapsed
  const shouldRenderSeparateIOSCTAs = 
    showSeparateIOSCTAs &&
    platform.isIOSBrowser && 
    !isExpanded && 
    enableCtas && 
    ctaButtons && 
    ctaButtons.length > 0;

  const notificationContent = (
    <div className={containerClasses}>
      {platform.isWindowsExpanded ? (
        <WindowsChromeExpanded
          icon={icon}
          brandIcon={actualBrandIcon}
          enableBrandIconPreview={enableBrandIconPreview}
          notificationTitle={notificationTitle}
          notificationBody={notificationBody}
          displayUrl={displayUrl}
          browserName={getBrowserDisplayName(selectedBrowser)}
          mediaImageUrl={mediaImageUrl}
          enableCtas={enableCtas}
          ctaButtons={ctaButtons}
        />
      ) : (platform.isAndroidMobile || platform.isAndroidTablet) && isExpanded ? (
        <AndroidMobileExpanded
          icon={icon}
          selectedBrowser={selectedBrowser}
          notificationTitle={notificationTitle}
          notificationBody={notificationBody}
          displayUrl={displayUrl}
          brandIcon={actualBrandIcon}
          shouldShowBrandIcon={shouldShowBrandIcon}
          shouldShowBrandIconExpanded={shouldShowBrandIconAndroidExpanded}
          mediaImageUrl={mediaImageUrl}
          enableCtas={enableCtas}
          ctaButtons={ctaButtons}
        />
      ) : (
        <>
          {(platform.isAndroidMobile || platform.isAndroidTablet) && !isExpanded ? (
            <AndroidMobileChromeHeader
              icon={icon}
              selectedBrowser={selectedBrowser}
              notificationTitle={notificationTitle}
              notificationBody={notificationBody}
              brandIcon={actualBrandIcon}
              shouldShowBrandIcon={shouldShowBrandIcon}
            />
          ) : (platform.isIOSBrowser || platform.isIPadOSBrowser) ? (
            <IOSHeader
              icon={icon}
              selectedBrowser={selectedBrowser}
              notificationTitle={notificationTitle}
              notificationBody={notificationBody}
            />
          ) : (
            <NotificationHeader
              icon={icon}
              selectedBrowser={selectedBrowser}
              notificationTitle={notificationTitle}
              displayUrl={displayUrl}
              notificationBody={notificationBody}
              shouldShowBrandIcon={shouldShowBrandIcon}
              brandIcon={actualBrandIcon}
              isExpanded={isExpanded}
            />
          )}

          {isExpanded && (
            <NotificationExpandedContent
              shouldRenderExpandedMedia={shouldRenderExpandedMedia}
              shouldShowBrandIconInExpandedMac={shouldShowBrandIconInExpandedMac}
              brandIcon={actualBrandIcon}
              mediaImageUrl={mediaImageUrl}
              enableCtas={enableCtas}
              ctaButtons={ctaButtons}
            />
          )}
        </>
      )}
    </div>
  );

  // For iOS + Collapsed with CTAs, render notification and separate CTA container
  if (shouldRenderSeparateIOSCTAs) {
    return (
      <div className="ios-notification-wrapper">
        {notificationContent}
        <div className="ios-cta-container">
          {ctaButtons.map((button) => (
            <button
              key={button.id}
              type="button"
              className="ios-cta-button"
            >
              {button.label}
            </button>
          ))}
        </div>
      </div>
    );
  }

  // Default: return just the notification container
  return notificationContent;
};

NotificationContainer.propTypes = {
  notificationTitle: PropTypes.string,
  notificationBody: PropTypes.string,
  url: PropTypes.string,
  selectedOS: PropTypes.string.isRequired,
  selectedBrowser: PropTypes.string.isRequired,
  notificationState: PropTypes.oneOf([NOTIFICATION_STATE_COLLAPSED, NOTIFICATION_STATE_EXPANDED]),
  className: PropTypes.string,
  icon: PropTypes.string,
  supportsExpanded: PropTypes.bool,
  enableMedia: PropTypes.bool,
  enableCtas: PropTypes.bool,
  brandIcon: PropTypes.string,
  enableBrandIconPreview: PropTypes.bool,
  imageSrc: PropTypes.string,
  brandIconSrc: PropTypes.string,
  buttons: PropTypes.arrayOf(
    PropTypes.shape({
      text: PropTypes.string,
      url: PropTypes.string,
      type: PropTypes.string,
    })
  ),
  showSeparateIOSCTAs: PropTypes.bool,
};

export default NotificationContainer;

