import React, { useEffect, useState } from "react";
import '../../../scss/settings/connect-tab.scss';
import Spinner from '../../common/Spinner';
import PassInputField from "../common-fields/PassInputField";
import { toast } from 'react-toastify';
import { langString } from "../../../Helpers";
import { useMhubAdmin } from "../../../App/MhubAdminContext";

const ConnectTab = ({
  formData,
  setFormData,
  savedCredentials = {},
  accessToken,
  setAccessToken,
  isAuthLoading,
  setIsAuthLoading
}) => {
  const { updateConnectionStatus } = useMhubAdmin();

  const handleInputChange = (field, value) => {
    setFormData(prevState => ({
      ...prevState,
      [field]: value
    }));
  };

  const fetchAuthUrl = () => {
    const clientId = savedCredentials.client_id;
    const redirectUri = mhubMeetingsData.msteams_redirect_url;
    const adminUrl = mhubMeetingsData.admin_url || '/wp-admin/admin.php';

    const params = new URLSearchParams({
      client_id: clientId,
      response_type: 'code',
      redirect_uri: redirectUri,
      scope: 'openid profile User.Read Calendars.ReadWrite offline_access',
      response_mode: 'query',
      state: adminUrl,
      prompt: 'consent'
    });

    const authUrl = `https://login.microsoftonline.com/common/oauth2/v2.0/authorize?${params.toString()}`;
    window.location.href = authUrl;
  };

  const disconnectMsTeams = async () => {
    setIsAuthLoading(true);
    try {
      await wp.apiFetch({
        path: 'meetinghub/v2/msteams/disconnect',
        method: 'POST',
      });

      setAccessToken('');
      updateConnectionStatus('msteams', '');
      toast.success(langString('disconnected_success') || 'Disconnected successfully.');
    } catch (error) {
      console.error(langString('api_error'), error);
      // Even if API fails, we should clear the local state to allow reconnecting
      setAccessToken('');
      toast.error(langString('failed_disconnect') || 'Failed to disconnect.');
    } finally {
      setIsAuthLoading(false);
    }
  };

  const { client_id, client_secret, tenant_id } = formData;

  return (
    <div className="meetinghub-connect-tab-content">
      <div className="accordion" id="meetinghub-msteams-credentials">
        <div className="msteams-credentials-info">
          <h3 className="title">
            Microsoft Teams OAuth Credentials
            {accessToken && accessToken.id && formData.client_id && formData.client_secret &&
              formData.client_id === savedCredentials.client_id &&
              formData.client_secret === savedCredentials.client_secret && (
                <span className="mhub-status-connected">{wp.i18n.__('Connected', 'meetinghub')}</span>
              )}
          </h3>
          <p className="description">
            For Microsoft Teams "OAuth Credentials" setup, visit the{' '}
            <a
              href="https://portal.azure.com/"
              target="_blank"
              rel="noreferrer noopener"
            >
              Azure Portal
            </a>
            . Read our{' '}
            <a
              href="https://sovlix.com/docs/microsoft-teams-integration-for-meetinghub/"
              target="_blank"
              rel="noreferrer noopener"
            >
              documentation
            </a>{' '}
            for guidance.
          </p>
        </div>

        {/* Redirect URL Section */}
        <div className="msteams-redirect-url-section">
          <h3 className="title">{langString('redirect_url_for_azure')}</h3>
          <p className="description">
            {langString('copy_redirect_url_instruction')}
          </p>
          <div className="url-copy">
            <input
              type="text"
              value={mhubMeetingsData.msteams_redirect_url || `${window.location.origin}/mhub-msteams-oauth/`}
              readOnly
              id="msteams-redirect-url"
            />
            <span
              className="copy-button"
              onClick={(event) => {
                const input = document.getElementById('msteams-redirect-url');
                input.select();
                document.execCommand('copy');
                // Show a temporary "Copied!" message
                const btn = event.target;
                const originalText = btn.textContent;
                btn.textContent = langString('copied');
                setTimeout(() => {
                  btn.textContent = originalText;
                }, 2000);
              }}
            >
              {langString('copy_url')}
            </span>
          </div>
        </div>

        {/* Connect Button: only show when credentials are saved in the database */}
        {savedCredentials.client_id && savedCredentials.client_secret ? (
          <div className="msteams-connect-button-wrapper">
            {isAuthLoading ? (
              <Spinner />
            ) : accessToken && accessToken.id ? (
              <a className="mhub-connect-msteams-btn disconnect" onClick={disconnectMsTeams}>
                Disconnect Microsoft Teams
              </a>
            ) : (
              <a className="mhub-connect-msteams-btn" onClick={fetchAuthUrl}>
                Connect Microsoft Teams
              </a>
            )}
          </div>
        ) : (formData.client_id && formData.client_secret) ? (
          <div className="msteams-save-notice">
            <p>⚠️ Please <strong>Save Changes</strong> before connecting.</p>
          </div>
        ) : null}

        <div className="mhub-section-pannel">
          {/* Client ID */}
          <PassInputField
            label={langString('client_id')}
            type="password"
            id="mhub_msteams_client_id"
            name="mhub_msteams_client_id"
            value={client_id}
            onChange={(value) =>
              handleInputChange('client_id', value)
            }
          />

          {/* Client Secret */}
          <PassInputField
            label={langString('client_secret')}
            type="password"
            id="mhub_msteams_client_secret"
            name="mhub_msteams_client_secret"
            value={client_secret}
            onChange={(value) =>
              handleInputChange('client_secret', value)
            }
          />

          {/* Tenant ID */}
          <PassInputField
            label="Tenant ID (Optional)"
            type="password"
            id="mhub_msteams_tenant_id"
            name="mhub_msteams_tenant_id"
            value={tenant_id}
            onChange={(value) =>
              handleInputChange('tenant_id', value)
            }
          />
        </div>

      </div>
    </div>
  );
};

export default ConnectTab;