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

/**
 * Google OAuth Refresh Token Tool
 * 
 * Handles the full flow:
 *  1. Opens Google OAuth consent in a new tab
 *  2. User copies the authorization code
 *  3. Exchanges code for refresh token (direct to Google, no backend needed)
 *  4. Shows the az CLI command to update the container
 * 
 * Also supports auto-capture: if the TestAPI URL is registered as a redirect URI,
 * the code will appear in the URL params and be auto-populated.
 */

// Default credentials (from your Google Cloud Console - Desktop app type)
const DEFAULTS = {
  clientId: '330518338348-a1qto1jug5tmpc6565059apsggsfg12i.apps.googleusercontent.com',
  clientSecret: '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',
  scope: 'https://www.googleapis.com/auth/adwords',
  containerApp: 'adp-googleapi',
  resourceGroup: 'RG-GraeJones'
};

export default function GoogleTokenTool() {
  const [clientId, setClientId] = useState(DEFAULTS.clientId);
  const [clientSecret, setClientSecret] = useState(DEFAULTS.clientSecret);
  const [authCode, setAuthCode] = useState('');
  const [result, setResult] = useState(null);
  const [error, setError] = useState(null);
  const [isBusy, setIsBusy] = useState(false);
  const [copied, setCopied] = useState(null);
  const [useRedirect, setUseRedirect] = useState(false);

  const redirectUri = useRedirect
    ? window.location.origin
    : 'urn:ietf:wg:oauth:2.0:oob';

  // Auto-capture: check URL for ?code= on mount (if redirect mode is used)
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const code = params.get('code');
    if (code) {
      setAuthCode(code);
      setUseRedirect(true);
      // Clean the URL
      window.history.replaceState({}, '', window.location.pathname);
    }
  }, []);

  const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?` +
    `client_id=${encodeURIComponent(clientId)}` +
    `&redirect_uri=${encodeURIComponent(redirectUri)}` +
    `&response_type=code` +
    `&scope=${encodeURIComponent(DEFAULTS.scope)}` +
    `&access_type=offline` +
    `&prompt=consent`;

  const openAuth = () => {
    window.open(authUrl, '_blank', 'width=600,height=700');
  };

  const exchangeCode = async () => {
    if (!authCode.trim()) return;

    setIsBusy(true);
    setError(null);
    setResult(null);

    try {
      const resp = await fetch('https://oauth2.googleapis.com/token', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
          code: authCode.trim(),
          client_id: clientId,
          client_secret: clientSecret,
          redirect_uri: redirectUri,
          grant_type: 'authorization_code'
        })
      });

      const data = await resp.json();

      if (data.error) {
        setError(`${data.error}: ${data.error_description || 'Unknown error'}`);
      } else {
        setResult({
          refreshToken: data.refresh_token,
          accessToken: data.access_token,
          expiresIn: data.expires_in,
          scope: data.scope,
          tokenType: data.token_type
        });
      }
    } catch (e) {
      setError(`Network error: ${e.message}`);
    } finally {
      setIsBusy(false);
    }
  };

  const azCommand = result?.refreshToken
    ? `az containerapp update --name ${DEFAULTS.containerApp} --resource-group ${DEFAULTS.resourceGroup} --set-env-vars GoogleAds__OAuth__RefreshToken=${result.refreshToken}`
    : '';

  const copyToClipboard = (text, label) => {
    navigator.clipboard.writeText(text).then(() => {
      setCopied(label);
      setTimeout(() => setCopied(null), 2000);
    });
  };

  return (
    <div className="token-tool">
      <div className="token-tool-header">
        <h3>Google OAuth Token Tool</h3>
        <span className="token-tool-badge">Utility</span>
      </div>

      {/* Step 1: Credentials (pre-filled, collapsible) */}
      <details className="token-step">
        <summary>OAuth Credentials (pre-filled)</summary>
        <div className="token-field">
          <label>Client ID</label>
          <input type="text" value={clientId} onChange={e => setClientId(e.target.value)} />
        </div>
        <div className="token-field">
          <label>Client Secret</label>
          <input type="text" value={clientSecret} onChange={e => setClientSecret(e.target.value)} />
        </div>
        <div className="token-field token-field-inline">
          <label>
            <input
              type="checkbox"
              checked={useRedirect}
              onChange={e => setUseRedirect(e.target.checked)}
            />
            {' '}Use redirect mode (requires {window.location.origin} in Google Cloud authorized redirect URIs)
          </label>
        </div>
      </details>

      {/* Step 2: Authorize */}
      <div className="token-step-open">
        <div className="step-label">Step 1 — Authorize with Google</div>
        <p className="step-hint">
          Opens Google sign-in. Sign in with <strong>addplatform.mcc@gmail.com</strong> and grant access.
          {!useRedirect && ' Copy the authorization code shown after approval.'}
        </p>
        <button className="token-btn token-btn-primary" onClick={openAuth}>
          Open Google Authorization
        </button>
      </div>

      {/* Step 3: Exchange code */}
      <div className="token-step-open">
        <div className="step-label">Step 2 — Exchange Code for Token</div>
        <div className="token-field">
          <label>Authorization Code</label>
          <input
            type="text"
            value={authCode}
            onChange={e => setAuthCode(e.target.value)}
            placeholder="Paste the authorization code here"
            className={authCode ? 'has-value' : ''}
          />
        </div>
        <button
          className="token-btn token-btn-primary"
          onClick={exchangeCode}
          disabled={!authCode.trim() || isBusy}
        >
          {isBusy ? 'Exchanging...' : 'Exchange for Refresh Token'}
        </button>
      </div>

      {/* Error */}
      {error && (
        <div className="token-error">
          <strong>Error:</strong> {error}
        </div>
      )}

      {/* Result */}
      {result && (
        <div className="token-result">
          <div className="step-label">Refresh Token</div>
          <div className="token-value-row">
            <code className="token-value">{result.refreshToken}</code>
            <button
              className="token-btn token-btn-small"
              onClick={() => copyToClipboard(result.refreshToken, 'token')}
            >
              {copied === 'token' ? '✓ Copied' : 'Copy'}
            </button>
          </div>

          <div className="step-label" style={{ marginTop: 16 }}>
            Step 3 — Update Container (run in PowerShell)
          </div>
          <div className="token-value-row">
            <code className="token-value token-cmd">{azCommand}</code>
            <button
              className="token-btn token-btn-small"
              onClick={() => copyToClipboard(azCommand, 'cmd')}
            >
              {copied === 'cmd' ? '✓ Copied' : 'Copy'}
            </button>
          </div>

          <details className="token-details" style={{ marginTop: 12 }}>
            <summary>Full token response</summary>
            <pre>{JSON.stringify(result, null, 2)}</pre>
          </details>
        </div>
      )}
    </div>
  );
}
