import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import "../../scss/settings/tab.scss";
import Spinner from "../common/Spinner";
import SettingIcons from "./SettingIcons";
import ConnectTab from "./msteams/ConnectTab";
import ConfigTab from "./msteams/ConfigTab";
import { toast } from 'react-toastify';
import ShortcodesTab from "./msteams/ShortcodesTab";
import { langString, isProActive } from "../../Helpers";
import { useMhubAdmin } from "../../App/MhubAdminContext";

function MsTeamsSettings() {
  const { updateConnectionStatus } = useMhubAdmin();
  const storedTab = localStorage.getItem("mhub_msteams_settings_active_tab");
  const [activeTab, setActiveTab] = useState(
    storedTab ? storedTab : "ConnectTab"
  );

  const [formData, setFormData] = useState({
    client_id: "",
    client_secret: "",
    tenant_id: "",
    meeting_timezone: mhubMeetingsData.mhub_timezone,
    hide_sidebar: false,
    hide_header_footer: false,
    auto_record: false,
    allow_attendee_camera: isProActive(),
    allow_attendee_mic: isProActive(),
    enable_lobby: true,
    enable_should_register: false,
    enable_recurring_meeting: false,
    join_before_host: false,
  });

  const [isLoading, setIsLoading] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [saveButtonText, setSaveButtonText] = useState(langString('save_changes'));
  const [saveButtonClass, setSaveButtonClass] = useState("");
  // Tracks credentials that are actually saved in the database (not just typed in the form).
  const [savedCredentials, setSavedCredentials] = useState({ client_id: '', client_secret: '' });
  const [accessToken, setAccessToken] = useState('');
  const [isAuthLoading, setIsAuthLoading] = useState(false);

  useEffect(() => {
    // Retrieve active tab from localStorage on component mount
    if (storedTab) {
      setActiveTab(storedTab);
    }
  }, []);

  // UseEffect to fetch Microsoft Teams settings and user status when the component mounts
  useEffect(() => {
    const fetchInitialData = async () => {
      setIsLoading(true);
      setIsAuthLoading(true);
      try {
        // Fetch both in parallel
        const [settingsResponse, userResponse] = await Promise.all([
          wp.apiFetch({
            path: 'meetinghub/v2/settings/msteams',
            method: 'GET',
          }),
          wp.apiFetch({
            path: 'meetinghub/v2/msteams/user',
            method: 'GET',
          }).catch(error => {
            // Silently handle expected auth errors
            if (error.code !== 'rest_forbidden' &&
              error.code !== 'rest_no_route' &&
              error.code !== 'msteams_user_error' &&
              error.code !== 'msteams_not_connected') {
              console.error(langString('api_error'), error);
            }
            return null;
          })
        ]);

        if (settingsResponse) {
          setFormData({
            client_id: settingsResponse.client_id || formData.client_id,
            client_secret: settingsResponse.client_secret || formData.client_secret,
            tenant_id: settingsResponse.tenant_id || formData.tenant_id,
            meeting_timezone: settingsResponse.meeting_timezone || formData.meeting_timezone,
            hide_sidebar: settingsResponse.hide_sidebar || formData.hide_sidebar,
            hide_header_footer: settingsResponse.hide_header_footer || formData.hide_header_footer,
            auto_record: isProActive() ? (settingsResponse.auto_record || formData.auto_record) : false,
            allow_attendee_camera: isProActive() ? (settingsResponse.allow_attendee_camera !== undefined ? settingsResponse.allow_attendee_camera : formData.allow_attendee_camera) : false,
            allow_attendee_mic: isProActive() ? (settingsResponse.allow_attendee_mic !== undefined ? settingsResponse.allow_attendee_mic : formData.allow_attendee_mic) : false,
            enable_lobby: settingsResponse.enable_lobby !== undefined ? settingsResponse.enable_lobby : formData.enable_lobby,
            enable_should_register: settingsResponse.enable_should_register || formData.enable_should_register,
            enable_recurring_meeting: settingsResponse.enable_recurring_meeting || formData.enable_recurring_meeting,
            join_before_host: settingsResponse.join_before_host || formData.join_before_host,
          });

          setSavedCredentials({
            client_id: settingsResponse.client_id || '',
            client_secret: settingsResponse.client_secret || '',
          });
        }

        if (userResponse) {
          setAccessToken(userResponse);
        } else {
          setAccessToken('');
        }

      } catch (error) {
        if (error.code !== 'rest_no_route' && error.code !== 'rest_forbidden') {
          console.error(langString('api_error'), error);
        }
      } finally {
        setIsLoading(false);
        setIsAuthLoading(false);
      }
    };

    fetchInitialData();
  }, []);


  const handleTabClick = (tabName) => {
    setActiveTab(tabName);
    // Store active tab in localStorage
    localStorage.setItem("mhub_msteams_settings_active_tab", tabName);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    setIsSaving(true);
    try {
      const response = await wp.apiFetch({
        path: "meetinghub/v2/settings/msteams",
        method: "POST",
        data: {
          client_id: formData.client_id,
          client_secret: formData.client_secret,
          tenant_id: formData.tenant_id,
          meeting_timezone: formData.meeting_timezone,
          hide_sidebar: formData.hide_sidebar,
          hide_header_footer: formData.hide_header_footer,
          auto_record: formData.auto_record,
          allow_attendee_camera: formData.allow_attendee_camera,
          allow_attendee_mic: formData.allow_attendee_mic,
          enable_lobby: formData.enable_lobby,
          enable_should_register: formData.enable_should_register,
          enable_recurring_meeting: formData.enable_recurring_meeting,
          join_before_host: formData.join_before_host,
        },
      });

      if (response && response.msteams_settings_saved) {
        toast.success(langString('settings_saved'));
        setSaveButtonText(langString('saved'));
        setSaveButtonClass("saved");
        // Update savedCredentials so Connect button becomes visible immediately after saving.
        setSavedCredentials({
          client_id: formData.client_id || '',
          client_secret: formData.client_secret || '',
        });

        // If credentials are empty, also clear access token state to update UI immediately
        if (!formData.client_id || !formData.client_secret) {
          setAccessToken('');
        }

        // Update global data for the main settings page
        const isTeamsConnected = (accessToken && accessToken.id) && formData.client_id && formData.client_secret;
        updateConnectionStatus('msteams', isTeamsConnected ? 'connected' : '');

        setTimeout(() => {
          setSaveButtonText(langString('save_changes'));
          setSaveButtonClass("");
        }, 2000);
      } else {
        toast.error(langString('failed_update_settings'));
      }
    } catch (error) {
      console.error(langString('api_error'), error);
    } finally {
      setIsSaving(false);
    }
  };

  const renderTabContent = () => {
    // Map tab names to corresponding components
    const tabComponents = {
      ConnectTab: (
        <ConnectTab
          formData={formData}
          setFormData={setFormData}
          savedCredentials={savedCredentials}
          accessToken={accessToken}
          setAccessToken={setAccessToken}
          isAuthLoading={isAuthLoading}
          setIsAuthLoading={setIsAuthLoading}
        />
      ),
      Configurations: (
        <ConfigTab formData={formData} setFormData={setFormData} />
      ),
    };

    // Render the component for the active tab
    return tabComponents[activeTab] || null;
  };

  return (
    <div className="msteams-settings-container">
      <Link to="/" className="back-button">
        &lt; {langString('back_to_settings')}
      </Link>

      <div className="main-wrapper">
        <div className="header">
          {SettingIcons.msteams}
          <div className="title">Microsoft Teams</div>
        </div>

        <div className="tab-wrapper">
          <div className="tab">
            <div
              className={`tab-item ${activeTab === "ConnectTab" ? "active" : ""
                }`}
              onClick={() => handleTabClick("ConnectTab")}
            >
              {langString('connect')}

            </div>
            <div
              className={`tab-item ${activeTab === "Configurations" ? "active" : ""
                }`}
              onClick={() => handleTabClick("Configurations")}
            >
              {langString('configurations')}
            </div>
            <div
              className={`tab-item ${activeTab === "Shortcodes" ? "active" : ""
                }`}
              onClick={() => handleTabClick("Shortcodes")}
            >
              {langString('shortcodes')}
            </div>

          </div>
          <a
            className="create-meeting-btn"
            href={mhubMeetingsData.createMeetingUrl}
          >
            <span className="dashicons dashicons-plus-alt2"></span>
            {langString('create_meeting')}
          </a>
        </div>

        {isLoading ? (
          <Spinner />
        ) : (
          <div className="msteams-meeting-form ">
            <div className="form-wrapper">
              {activeTab !== "Shortcodes" && (
                <form onSubmit={handleSubmit}>
                  {renderTabContent()}
                  <div className="mhub-save-actions">
                    <button
                      type="submit"
                      className={`setting-save-button ${saveButtonClass}`}
                      disabled={isSaving}
                    >
                      {isSaving ? langString('saving') : saveButtonText}
                    </button>
                  </div>
                </form>
              )}

              {activeTab === "Shortcodes" && (
                <ShortcodesTab />
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

export default MsTeamsSettings;