import React, { useEffect, useRef, useState } from 'react';
import axios from 'axios';

const JitsiConference = ({ roomName, userName, onApiReady }) => {
  const jitsiContainer = useRef(null);
  const jitsiApi = useRef(null);
  const [jitsiScriptLoaded, setJitsiScriptLoaded] = useState(false); // New state to track script loading

  // Hardcoding for immediate testing; use env variable in production
  const JITSI_SERVER_DOMAIN = 'https://meet.jit.si'; // Replace with your Jitsi server domain if self-hosted
  const BACKEND_API_URL = process.env.REACT_APP_BACKEND_API_URL || 'http://localhost:5000';

  // Effect to load the Jitsi external_api.js script
  useEffect(() => {
    const scriptUrl = `${JITSI_SERVER_DOMAIN}/external_api.js`;

    const existingScript = document.querySelector(`script[src="${scriptUrl}"]`);

    if (!existingScript) {
      const script = document.createElement('script');
      script.src = scriptUrl;
      script.async = true;
      script.onload = () => {
        console.log("Jitsi external_api.js loaded successfully.");
        setJitsiScriptLoaded(true); // Update state to indicate script is ready
      };
      script.onerror = (e) => {
        console.error("Failed to load Jitsi external API script.", e);
        alert("Failed to load Jitsi meeting components. Please check your network or Jitsi domain configuration.");
      };
      document.body.appendChild(script);
    } else {
      // If script exists, check if JitsiMeetExternalAPI is already on window
      // This covers cases where the component remounts or StrictMode re-runs
      if (window.JitsiMeetExternalAPI) {
        setJitsiScriptLoaded(true);
      } else {
        // If script element exists but API isn't ready yet,
        // it means the script is still loading. Wait for its onload.
        existingScript.onload = () => { // Re-attach onload just in case
            setJitsiScriptLoaded(true);
        };
      }
    }
  }, [JITSI_SERVER_DOMAIN]); // Only re-run if Jitsi domain changes

  // Effect to initialize Jitsi once the script is loaded AND other dependencies are ready
  useEffect(() => {
    const initializeJitsiConference = async () => {
      if (!jitsiScriptLoaded || !window.JitsiMeetExternalAPI || !jitsiContainer.current) {
        // Not ready to initialize yet
        return;
      }

      console.log('Attempting to initialize JitsiMeetExternalAPI...');

      // **Important:** Clear the container before re-initializing
      while (jitsiContainer.current.firstChild) {
        jitsiContainer.current.removeChild(jitsiContainer.current.firstChild);
      }

      let token = null;
    //   if (JITSI_SERVER_DOMAIN !== 'https://meet.jit.si') {
    //       try {
    //           const response = await axios.post(`${BACKEND_API_URL}/api/auth/token`, {
    //               userName,
    //               roomName,
    //           });
    //           token = response.data.token;
    //       } catch (error) {
    //           console.error('Error fetching JWT:', error);
    //           alert('Failed to get meeting token. Please try again.');
    //           return;
    //       }
    //   }

      const options = {
        roomName: roomName || 'MultiPartyDemoRoom123',
        width: '100%',
        height: '100%',
        parentNode: jitsiContainer.current,
        userInfo: {
          displayName: userName || 'Guest User',
        },
        configOverwrite: {
          startWithAudioMuted: false,
          startWithVideoMuted: false,
          disableSelfView: false,
          enableWelcomePage: false,
          prejoinPageEnabled: false,
          disableInviteFunctions: true,
          ...(token && { jwt: token }),
        },
        interfaceConfigOverwrite: {
          HIDE_INVITE_MORE_HEADER: true,
          TOOLBAR_BUTTONS: [
            'microphone', 'camera', 'desktop', 'fullscreen',
            'fodeviceselection', 'hangup', 'profile', 'chat',
            'etherpad', 'sharedvideo', 'settings', 'raisehand',
            'videoquality', 'filmstrip', 'tileview', 'stats', 'shortcuts'
          ],
        },
      };

      try {
        const api = new window.JitsiMeetExternalAPI('meet.jit.si', options);
        jitsiApi.current = api;

        if (onApiReady && typeof onApiReady === 'function') {
          onApiReady(api);
        }

        api.addEventListener('videoConferenceJoined', () => {
          console.log('Conference Joined!');
          api.executeCommand('displayName', userName || 'Guest User');
        });
        api.addEventListener('participantJoined', (participant) => {
          console.log('Participant Joined:', participant);
        });
        api.addEventListener('participantLeft', (participant) => {
          console.log('Participant Left:', participant);
        });
        api.addEventListener('readyToClose', () => {
          console.log('Conference is ready to close');
          if (jitsiApi.current) {
            jitsiApi.current.dispose();
            jitsiApi.current = null;
          }
        });

      } catch (error) {
        console.error('Failed to initialize JitsiMeetExternalAPI:', error);
      }
    };

    initializeJitsiConference(); // Call initialization

    // Cleanup function for this effect
    return () => {
      if (jitsiApi.current) {
        console.log('Disposing Jitsi API instance...');
        jitsiApi.current.dispose();
        jitsiApi.current = null;
      }
    };
  }, [jitsiScriptLoaded, roomName, userName, onApiReady]); // Dependencies: only re-init if these change

  return (
    <div
      ref={jitsiContainer}
      style={{ width: '100%', height: '100%' }}
    />
  );
};

export default JitsiConference;