// MhubAdminContext.jsx
import React, { createContext, useContext, useState } from 'react';

// Create a context
const MhubAdminContext = createContext();

// Create a provider component
export const MhubAdminProvider = ({ children }) => {
  const [isModalOpen, setIsProModalOpen] = useState(false);
  const [connectionStatuses, setConnectionStatuses] = useState({
    jitsi: mhubMeetingsData.jitsi_active_status || '',
    zoom_oauth: mhubMeetingsData.oauthData || '',
    zoom_sdk: mhubMeetingsData.zoom_sdk_auth || '',
    webex: mhubMeetingsData.webex_auth || '',
    google_meet: mhubMeetingsData.google_account || '',
    msteams: mhubMeetingsData.msteams_auth || '',
  });

  const [prepStatuses, setPrepStatuses] = useState(mhubMeetingsData.prepStatus || {
    zoom_oauth: false,
    zoom_sdk: false,
    webex: false,
    msteams: false,
    google: false,
  });

  const [dismissedNotices, setDismissedNotices] = useState(mhubMeetingsData.dismissedNotices || {});

  const [zoomUsers, setZoomUsers] = useState(Array.isArray(mhubMeetingsData.zoom_users) ? mhubMeetingsData.zoom_users : []);
  const [zoomUsersLoading, setZoomUsersLoading] = useState(false);

  const fetchZoomUsers = async (force = false) => {
    if (!force && zoomUsers.length > 0) return;

    setZoomUsersLoading(true);
    try {
      const response = await wp.apiFetch({
        path: 'meetinghub/v2/zoom/users',
        method: 'GET',
      });

      if (response && response.users) {
        setZoomUsers(response.users);
        if (window.mhubMeetingsData) {
          window.mhubMeetingsData.zoom_users = response.users;
        }
      }
    } catch (error) {
      console.error('Failed to fetch Zoom users:', error);
    } finally {
      setZoomUsersLoading(false);
    }
  };

  const updateConnectionStatus = (platform, status) => {
    setConnectionStatuses(prev => ({
      ...prev,
      [platform]: status
    }));

    // If Zoom becomes connected, we might want to refresh users
    if ((platform === 'zoom_oauth' || platform === 'zoom_sdk') && status === 'connected') {
      fetchZoomUsers(true);
    }

    // Also sync with global object for legacy parts if needed
    if (window.mhubMeetingsData) {
      if (platform === 'jitsi') window.mhubMeetingsData.jitsi_active_status = status;
      if (platform === 'zoom_oauth') window.mhubMeetingsData.oauthData = status;
      if (platform === 'zoom_sdk') window.mhubMeetingsData.zoom_sdk_auth = status;
      if (platform === 'webex') window.mhubMeetingsData.webex_auth = status;
      if (platform === 'google_meet') window.mhubMeetingsData.google_account = status;
      if (platform === 'msteams') window.mhubMeetingsData.msteams_auth = status;
    }
  };

  const updatePrepStatus = (platform, status) => {
    setPrepStatuses(prev => ({
      ...prev,
      [platform]: status
    }));

    if (window.mhubMeetingsData && window.mhubMeetingsData.prepStatus) {
      window.mhubMeetingsData.prepStatus[platform] = status;
    }
  };

  const addDismissedNotice = (id, expiry) => {
    setDismissedNotices(prev => ({
      ...prev,
      [id]: expiry
    }));
  };

  // Updated to use SDK modal instead of React modal
  const openProModal = () => {
    console.log('openProModal called');
    console.log('window.PromoSDK:', window.PromoSDK);

    // Call SDK modal if available
    if (window.PromoSDK && window.PromoSDK.Modal) {
      console.log('SDK Modal found, calling show()');

      // Get the MeetingHub instance
      const instance = window.PromoSDK.Modal.instances['meetinghub'];

      if (instance) {
        console.log('MeetingHub instance found, showing modal');
        window.PromoSDK.Modal.show(instance);
      } else {
        console.error('MeetingHub modal instance not found!');
        console.log('Available instances:', Object.keys(window.PromoSDK.Modal.instances));
      }
    } else {
      console.log('SDK not loaded, using fallback modal');
      // Fallback to old modal if SDK not loaded
      setIsProModalOpen(true);
    }
  };

  const closeProModal = () => setIsProModalOpen(false);


  const contextValue = {
    isModalOpen,
    openProModal,
    closeProModal,
    connectionStatuses,
    updateConnectionStatus,
    prepStatuses,
    updatePrepStatus,
    dismissedNotices,
    addDismissedNotice,
    zoomUsers,
    zoomUsersLoading,
    fetchZoomUsers,
  };

  return (
    <MhubAdminContext.Provider value={contextValue}>
      {children}
    </MhubAdminContext.Provider>
  );
};

// Custom hook to use the context
export const useMhubAdmin = () => useContext(MhubAdminContext);
