import React, { useEffect, useRef, useState, useCallback } from 'react';
import ReactDOM from 'react-dom';

const WindowPortal = ({
  children,
  onClose,
  windowFeatures = 'width=400,height=300,left=200,top=200,menubar=no,toolbar=no,status=no,scrollbars=yes,resizable=yes,location=no, addressbar=no',
  title = 'Media Controls',
  onWindowReady,
  onWindowMessage,
  windowId
}) => {
  const [externalWindow, setExternalWindow] = useState(null);
  const [isReady, setIsReady] = useState(false);
  const containerRef = useRef(null);
  const messageHandlerRef = useRef(null);

  // Message handling
  const handleMessage = useCallback((event) => {
    // Only accept messages from our popup window
    if (event.source === externalWindow) {
      if (onWindowMessage) {
        onWindowMessage(event.data);
      }
    }
  }, [externalWindow, onWindowMessage]);

  // Send message to popup window
  const sendMessage = useCallback((message) => {
    if (externalWindow && !externalWindow.closed) {
      externalWindow.postMessage(message, window.location.origin);
    }
  }, [externalWindow]);

  // Auto-resize window based on content
  const resizeWindow = useCallback(() => {
    if (!externalWindow || externalWindow.closed) return;

    const container = containerRef.current;
    if (!container) return;

    const width = container.offsetWidth;
    const height = container.offsetHeight;

    // Add some padding for window chrome
    const chromePadding = 20;
    const newWidth = Math.max(width + chromePadding, 350);
    const newHeight = Math.max(height + chromePadding, 200);

    externalWindow.resizeTo(newWidth, newHeight);
  }, [externalWindow]);

  useEffect(() => {
    // Open new window
    const newWindow = window.open('', '_blank', windowFeatures);

    if (!newWindow) {
      console.error('WindowPortal: Failed to open popup window - popup blocker may be active');
      onClose();
      return;
    }

    // Set up the new window
    newWindow.document.title = title;
    newWindow.document.body.style.margin = '0';
    newWindow.document.body.style.padding = '0';
    newWindow.document.body.style.fontFamily = '-apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", sans-serif';
    newWindow.document.body.style.backgroundColor = '#f8f9fa';
    newWindow.document.body.style.overflow = 'hidden';

    // Copy all stylesheets from parent window to popup
    const stylesheets = Array.from(document.querySelectorAll('link[rel="stylesheet"], style'));
    stylesheets.forEach(sheet => {
      if (sheet.tagName === 'LINK') {
        const newLink = newWindow.document.createElement('link');
        newLink.rel = 'stylesheet';
        newLink.href = sheet.href;
        newWindow.document.head.appendChild(newLink);
      } else if (sheet.tagName === 'STYLE') {
        const newStyle = newWindow.document.createElement('style');
        newStyle.textContent = sheet.textContent;
        newWindow.document.head.appendChild(newStyle);
      }
    });

    // Add window ID for identification
    if (windowId) {
      newWindow.windowId = windowId;
    }

    // Create container div
    const container = newWindow.document.createElement('div');
    container.style.width = '100%';
    container.style.height = '100%';
    container.style.overflow = 'auto';
    container.style.boxSizing = 'border-box';
    newWindow.document.body.appendChild(container);
    containerRef.current = container;

    setExternalWindow(newWindow);
    setIsReady(true);

    // Set up message handling
    messageHandlerRef.current = handleMessage;
    window.addEventListener('message', messageHandlerRef.current);

    // Notify parent that window is ready
    if (onWindowReady) {
      onWindowReady(newWindow, sendMessage);
    }

    // Handle window close detection
    const checkClosed = setInterval(() => {
      if (newWindow.closed) {
        clearInterval(checkClosed);
        window.removeEventListener('message', messageHandlerRef.current);
        onClose();
      }
    }, 1000);

    // Handle page unload/close
    const handleBeforeUnload = () => {
      if (newWindow && !newWindow.closed) {
        newWindow.close();
      }
    };

    // Handle popup window unload
    const handlePopupUnload = () => {
      onClose();
    };

    window.addEventListener('beforeunload', handleBeforeUnload);
    newWindow.addEventListener('beforeunload', handlePopupUnload);

    // Skip initial resize - use windowFeatures dimensions
    // setTimeout(resizeWindow, 100);

    return () => {
      clearInterval(checkClosed);
      window.removeEventListener('beforeunload', handleBeforeUnload);
      window.removeEventListener('message', messageHandlerRef.current);
      if (newWindow && !newWindow.closed) {
        newWindow.removeEventListener('beforeunload', handlePopupUnload);
        newWindow.close();
      }
    };
  }, [windowFeatures, title, windowId, onClose, onWindowReady]);

  // Resize when children change - DISABLED for now to prevent expanding
  // useEffect(() => {
  //   if (isReady) {
  //     // Delay resize to allow DOM updates
  //     const timeoutId = setTimeout(resizeWindow, 50);
  //     return () => clearTimeout(timeoutId);
  //   }
  // }, [children, isReady, resizeWindow]);

  if (!isReady || !externalWindow || !containerRef.current) {
    return null;
  }

  // Render children into the new window
  return ReactDOM.createPortal(children, containerRef.current);
};

export default WindowPortal;
