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';
const { __ } = wp.i18n;
import { langString } from "../../../Helpers";
import { useMhubAdmin } from "../../../App/MhubAdminContext";

const ConnectTab = ({
  formData,
  setFormData,
  savedCredentials = {},
  accessToken,
  setAccessToken,
  isAuthLoading,
  setIsAuthLoading
}) => {
  const { updateConnectionStatus } = useMhubAdmin();
  const [authUrl, setAuthUrl] = useState('');

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

  const fetchAuthUrl = () => {
    const clientId = savedCredentials.client_id;
    const redirectUri = mhubMeetingsData.webex_redirect_url;

    const params = new URLSearchParams({
      response_type: 'code',
      client_id: clientId,
      redirect_uri: redirectUri,
      scope: 'meeting:schedules_read meeting:schedules_write',
      state: redirectUri // Match backend behavior
    });

    const authUrl = `https://webexapis.com/v1/authorize?${params.toString()}`;
    window.location.href = authUrl;
  };

  const disconnectWebex = async () => {
    setIsAuthLoading(true);
    try {
      await wp.apiFetch({
        path: 'meetinghub/v1/webex/revoke-access-token',
        method: 'GET',
      });

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


  // Helper to check if connected (handles both string and object)
  const isConnected = accessToken && (
    (typeof accessToken === 'string' && accessToken.trim() !== '') ||
    (typeof accessToken === 'object' && accessToken.access_token)
  );


  const { client_id, client_secret } = formData;

  return (
    <div className="meetinghub-connect-tab-content">
      <div className="accordion" id="meetinghub-webex-credentials">
        <div className="webex-credentials-info">
          <h3 className="title">
            {langString('webex_oauth_credentials')}
            {isConnected && client_id && client_secret &&
              client_id === savedCredentials.client_id &&
              client_secret === savedCredentials.client_secret && (
                <span className="mhub-status-connected">{__('Connected', 'meetinghub')}</span>
              )}
          </h3>
          <p className="description">
            {langString('webex_oauth_setup_hint')}{' '}
            <a
              href="https://developer.webex.com/"
              target="_blank"
              rel="noreferrer noopener"
            >
              {langString('webex_developer_portal')}
            </a>
            . {langString('watch_our')}{' '}
            <a
              href="https://youtu.be/vV3EwUNJusk"
              target="_blank"
              rel="noreferrer noopener"
            >
              {langString('tutorial_video')}
            </a>{' '}
            {langString('for_guidance')}
          </p>
        </div>

        <div className="msteams-redirect-url-section">
          <h3 className="title">Redirect URL for Webex App Registration</h3>
          <p className="description">
            Copy this URL and paste it as the Redirect URI when creating your Webex app in the Developer Portal.
          </p>
          <div className="url-copy">
            <input
              type="text"
              readOnly
              value={mhubMeetingsData.webex_redirect_url || window.location.origin}
              id="webex-redirect-url"
            />
            <span
              className="copy-button"
              onClick={(event) => {
                const input = document.getElementById('webex-redirect-url');
                input.select();
                document.execCommand('copy');
                // Show a temporary "Copied!" message
                const btn = event.target;
                const originalText = btn.textContent;
                btn.textContent = langString('copied') || 'Copied!';
                setTimeout(() => {
                  btn.textContent = originalText;
                }, 2000);
              }}
            >
              {langString('copy_url') || 'Copy URL'}
            </span>
          </div>
        </div>

        {/* Connect Button: only show when credentials are saved in the database */}
        {savedCredentials.client_id && savedCredentials.client_secret ? (
          <div className="webx-btn-wrapper">
            {isAuthLoading ? (
              <Spinner />
            ) : isConnected ? (
              <a className="mhub-connect-webex disconnect" onClick={disconnectWebex}>
                {langString('disconnect_webex')}
              </a>
            ) : (
              <a className="mhub-connect-webex" onClick={fetchAuthUrl}>
                {langString('connect_webex')}
              </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_webex_client_id"
            name="mhub_webex_client_id"
            value={client_id}
            onChange={(value) =>
              handleInputChange('client_id', value)
            }
          />

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

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

export default ConnectTab;
