import { useEffect, useRef, useState } from 'react';
import ReactDOM from 'react-dom';
import { AuthProvider } from "react-auth-kit";
import { ThemeProvider } from '@material-tailwind/react';
import React from 'react';

function MonitorSelector({ componentType: Component, componentProps, authConfig }) {
  const popupRef = useRef(null);

  const openOnMonitor = (event) => {
    event.preventDefault();
    event.stopPropagation();

    const x = 0;
    const y = 0;

    let newWindow = window.open('', '_blank', `left=${x},top=${y},width=800,height=600`);

    if (!newWindow) {
      alert("Please allow pop-ups for this website.");
      return;
    }

    popupRef.current = newWindow;

    // Grab and apply styles to the new window
    const styles = Array.from(document.styleSheets)
        .reduce((acc, sheet) => {
            try {
                const rules = Array.from(sheet.cssRules)
                    .map(rule => rule.cssText)
                    .join('');
                return acc + rules;
            } catch (e) {
                return acc;
            }
        }, '');

    const styleElement = newWindow.document.createElement('style');
    styleElement.textContent = styles;
    newWindow.document.head.appendChild(styleElement);

    const linkElement = newWindow.document.createElement('link');
    linkElement.rel = 'stylesheet';
    linkElement.href = '../../../../index.css';  // Adjust with your Tailwind CSS path or CDN link
    newWindow.document.head.appendChild(linkElement);

    const popupRoot = newWindow.document.createElement('div');
    newWindow.document.body.appendChild(popupRoot);

    ReactDOM.render(
      <ThemeProvider>
            <AuthProvider {...authConfig}>
              <Component {...componentProps} />
            </AuthProvider>
      </ThemeProvider>,
      popupRoot
    );
  };

  useEffect(() => {
    return () => {
      if (popupRef.current) {
        popupRef.current.close();
      }
    };
  }, []);

  return (
    <button 
        className="bg-blue-500 hover:bg-black text-white font-semibold py-2 px-4 rounded shadow transition duration-200 ease-in-out text-black"
        onClick={openOnMonitor}>
        +
    </button>
  );
}

export default MonitorSelector;
