/**
 * @file OAuthSettingsStep.jsx
 * @description OAuth settings step of the onboarding wizard.
 * Scopes are automatically configured based on partner category type.
 */

window.OAuthSettingsStep = function OAuthSettingsStep({ data, onChange, onNext, onPrev }) {
  const [loading, setLoading] = React.useState(true);
  const [newUri, setNewUri] = React.useState('');
  const [uriError, setUriError] = React.useState('');
  const [allScopes, setAllScopes] = React.useState([]);

  /**
   * Map partner category type to the appropriate prefs scope.
   * @param {string} categoryType - The partner category type
   * @returns {string|null} The prefs scope for this category, or null for general
   */
  const getCategoryPrefsScope = (categoryType) => {
    const categoryToPrefs = {
      'adult_content': 'prefs_adult',
      'alcohol': 'prefs_alcohol',
      'gambling': 'prefs_gambling',
      'cannabis': 'prefs_cannabis'
    };
    return categoryToPrefs[categoryType] || null;
  };

  React.useEffect(() => {
    API.getScopes().then(res => {
      const scopes = res.data.scopes || [];
      setAllScopes(scopes);

      // Auto-include all scopes - required scopes plus all optional scopes
      const allScopeNames = scopes.map(s => s.name);

      // Filter out prefs_* scopes that don't match the partner's category
      // Only include the prefs scope matching the partner's category type
      const categoryPrefsScope = getCategoryPrefsScope(data.partnerCategoryType);
      const prefsScopes = ['prefs_adult', 'prefs_alcohol', 'prefs_gambling', 'prefs_cannabis'];

      const autoScopes = allScopeNames.filter(scope => {
        // Keep all non-prefs scopes
        if (!prefsScopes.includes(scope)) {
          return true;
        }
        // Only keep the prefs scope that matches the category
        return scope === categoryPrefsScope;
      });

      onChange({ ...data, allowedScopes: autoScopes });
      setLoading(false);
    }).catch(() => setLoading(false));
  }, [data.partnerCategoryType]);

  // Generate the auto-callback URL from company website
  const getAutoCallbackUrl = () => {
    if (!data.companyWebsite) return null;
    let baseUrl = data.companyWebsite;
    if (!baseUrl.startsWith('http')) {
      baseUrl = `https://${baseUrl}`;
    }
    baseUrl = baseUrl.replace(/\/$/, '');
    return `${baseUrl}/auth/v0uchme/callback`;
  };

  const autoCallbackUrl = getAutoCallbackUrl();

  const validateAndProceed = () => {
    onNext();
  };

  /**
   * Get human-readable category label for display.
   */
  const getCategoryLabel = () => {
    const labels = {
      'adult_content': 'Adult Content',
      'alcohol': 'Alcohol',
      'gambling': 'Gambling',
      'cannabis': 'Cannabis',
      'general': 'General'
    };
    return labels[data.partnerCategoryType] || 'Unknown';
  };

  const addRedirectUri = () => {
    setUriError('');
    if (!newUri) return;

    try {
      const url = new URL(newUri);
      if (url.protocol !== 'https:' && !['localhost', '127.0.0.1'].includes(url.hostname)) {
        setUriError('Redirect URI must use HTTPS (except for localhost)');
        return;
      }

      const current = data.redirectUris || [];
      if (current.includes(newUri)) {
        setUriError('This URI is already added');
        return;
      }

      onChange({ ...data, redirectUris: [...current, newUri] });
      setNewUri('');
    } catch {
      setUriError('Please enter a valid URL');
    }
  };

  const removeRedirectUri = (uri) => {
    const current = data.redirectUris || [];
    onChange({ ...data, redirectUris: current.filter(u => u !== uri) });
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center py-12">
        <div className="w-8 h-8 border-4 border-gray-200 border-t-blue-600 rounded-full loading-spinner" />
      </div>
    );
  }

  return (
    <div className="fade-in">
      <h2 className="text-2xl font-bold text-gray-900 mb-6">OAuth Settings</h2>
      <p className="text-gray-600 mb-8">Configure your OAuth 2.0 integration.</p>

      <div className="space-y-8">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-3">
            Redirect URIs
          </label>
          <p className="text-gray-500 text-sm mb-3">
            The callback URL is automatically generated from your company website.
            Add additional URIs below if needed (e.g., for development/staging environments).
          </p>

          {autoCallbackUrl && (
            <div className="mb-4 p-4 bg-green-50 border border-green-200 rounded-lg">
              <div className="flex items-center gap-2 mb-1">
                <svg className="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                </svg>
                <span className="text-sm font-medium text-green-800">Auto-generated Callback URL</span>
              </div>
              <code className="text-sm text-green-700 break-all">{autoCallbackUrl}</code>
            </div>
          )}

          <div className="flex gap-2 mb-3">
            <input
              type="url"
              value={newUri}
              onChange={(e) => { setNewUri(e.target.value); setUriError(''); }}
              onKeyDown={(e) => e.key === 'Enter' && addRedirectUri()}
              className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              placeholder="https://localhost:3000/callback (optional)"
            />
            <button
              onClick={addRedirectUri}
              className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200"
            >
              Add
            </button>
          </div>
          {uriError && <p className="text-red-500 text-sm mb-3">{uriError}</p>}

          {(data.redirectUris && data.redirectUris.length > 0) && (
            <div className="space-y-2">
              <p className="text-sm font-medium text-gray-600">Additional Redirect URIs:</p>
              {data.redirectUris.map((uri, i) => (
                <div key={i} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                  <code className="text-sm text-gray-700">{uri}</code>
                  <button
                    onClick={() => removeRedirectUri(uri)}
                    className="text-red-500 hover:text-red-700"
                  >
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                    </svg>
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-3">
            Data Access Permissions
          </label>
          <p className="text-gray-500 text-sm mb-4">
            Your application will automatically receive all available user data when users sign in with v0uchme.
            Users can always authenticate - these settings control what information is shared with your application.
          </p>

          {/* Auto-configured scopes info */}
          <div className="p-4 bg-green-50 border border-green-200 rounded-lg mb-4">
            <div className="flex items-start gap-3">
              <svg className="w-5 h-5 text-green-600 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
              <div>
                <p className="text-sm font-medium text-green-800">Data access automatically configured</p>
                <p className="text-sm text-green-700 mt-1">
                  Your application will receive all available user data including age verification, verification metadata,
                  demographics, and contact information.
                </p>
              </div>
            </div>
          </div>

          {/* Category-specific prefs scope info */}
          {data.partnerCategoryType && data.partnerCategoryType !== 'general' && (
            <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg mb-4">
              <div className="flex items-start gap-3">
                <svg className="w-5 h-5 text-blue-600 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <div>
                  <p className="text-sm font-medium text-blue-800">Category-specific preferences enabled</p>
                  <p className="text-sm text-blue-700 mt-1">
                    As a <strong>{getCategoryLabel()}</strong> partner, you will receive user preferences
                    specific to your category (<code className="bg-blue-100 px-1 rounded">{getCategoryPrefsScope(data.partnerCategoryType)}</code>).
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* Included scopes summary */}
          <div className="border border-gray-200 rounded-lg overflow-hidden">
            <div className="bg-gray-50 px-4 py-3 border-b border-gray-200">
              <h3 className="text-sm font-semibold text-gray-900">Included Data Scopes</h3>
            </div>
            <div className="p-4 max-h-64 overflow-y-auto">
              <div className="grid grid-cols-2 gap-2">
                {(data.allowedScopes || []).map(scopeName => {
                  const scopeInfo = allScopes.find(s => s.name === scopeName);
                  return (
                    <div key={scopeName} className="flex items-center gap-2 text-sm">
                      <svg className="w-4 h-4 text-green-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                      </svg>
                      <span className="font-mono text-gray-700" title={scopeInfo?.description || scopeName}>{scopeName}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="flex justify-between mt-8">
        <button
          onClick={onPrev}
          className="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
        >
          Back
        </button>
        <button
          onClick={validateAndProceed}
          className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
        >
          Continue
        </button>
      </div>
    </div>
  );
};
