/** * WordPress Integration Form Component * Inline form for WordPress integration with API key generation and plugin download */ import React, { useState, useEffect } from 'react'; import { Card } from '../ui/card'; import Button from '../ui/button/Button'; import Label from '../form/Label'; import Input from '../form/input/InputField'; import Checkbox from '../form/input/Checkbox'; import { useToast } from '../ui/toast/ToastContainer'; import { integrationApi, SiteIntegration } from '../../services/integration.api'; import { fetchAPI } from '../../services/api'; import { CheckCircleIcon, AlertIcon, DownloadIcon, PlusIcon, CopyIcon, TrashBinIcon } from '../../icons'; import { Globe, Key, RefreshCw } from 'lucide-react'; interface WordPressIntegrationFormProps { siteId: number; integration: SiteIntegration | null; siteName?: string; siteUrl?: string; onIntegrationUpdate?: (integration: SiteIntegration) => void; } export default function WordPressIntegrationForm({ siteId, integration, siteName, siteUrl, onIntegrationUpdate, }: WordPressIntegrationFormProps) { const toast = useToast(); const [loading, setLoading] = useState(false); const [generatingKey, setGeneratingKey] = useState(false); const [apiKey, setApiKey] = useState(''); const [apiKeyVisible, setApiKeyVisible] = useState(false); // Load API key from site settings on mount useEffect(() => { loadApiKeyFromSite(); }, [siteId]); const loadApiKeyFromSite = async () => { try { const siteData = await fetchAPI(`/v1/auth/sites/${siteId}/`); if (siteData?.wp_api_key) { setApiKey(siteData.wp_api_key); } else { // Clear API key if it doesn't exist in the backend setApiKey(''); } } catch (error) { // API key might not exist yet, that's okay setApiKey(''); } }; const handleGenerateApiKey = async () => { try { setGeneratingKey(true); // Generate API key - format: igny8_site_{siteId}_{timestamp}_{random} const timestamp = Date.now(); const random = Math.random().toString(36).substring(2, 15); const token = `igny8_site_${siteId}_${timestamp}_${random}`; setApiKey(token); setApiKeyVisible(true); // Save API key to site settings immediately await saveApiKeyToSite(token); // Reload the API key from backend to ensure consistency await loadApiKeyFromSite(); toast.success('API key generated and saved successfully'); } catch (error: any) { toast.error(`Failed to generate API key: ${error.message}`); } finally { setGeneratingKey(false); } }; const handleRegenerateApiKey = async () => { if (!confirm('Are you sure you want to regenerate the API key? The old key will no longer work.')) { return; } try { setGeneratingKey(true); // Generate new API key const timestamp = Date.now(); const random = Math.random().toString(36).substring(2, 15); const token = `igny8_site_${siteId}_${timestamp}_${random}`; setApiKey(token); setApiKeyVisible(true); // Save new API key to site settings await saveApiKeyToSite(token); // Reload the API key from backend to ensure consistency await loadApiKeyFromSite(); toast.success('API key regenerated and saved successfully'); } catch (error: any) { toast.error(`Failed to regenerate API key: ${error.message}`); } finally { setGeneratingKey(false); } }; const handleRevokeApiKey = async () => { if (!confirm('Are you sure you want to revoke the API key? Your WordPress plugin will stop working until you generate a new key.')) { return; } try { setGeneratingKey(true); // Clear API key from site settings by setting it to empty string await fetchAPI(`/v1/auth/sites/${siteId}/`, { method: 'PATCH', body: JSON.stringify({ wp_api_key: '' }), }); setApiKey(''); setApiKeyVisible(false); // Trigger integration update to reload the integration state if (onIntegrationUpdate && integration) { await loadApiKeyFromSite(); // Reload integration to reflect changes const integrations = await integrationApi.getSiteIntegrations(siteId); const wp = integrations.find(i => i.platform === 'wordpress'); if (wp) { onIntegrationUpdate(wp); } } toast.success('API key revoked successfully'); } catch (error: any) { toast.error(`Failed to revoke API key: ${error.message}`); } finally { setGeneratingKey(false); } }; const saveApiKeyToSite = async (key: string) => { try { await fetchAPI(`/v1/auth/sites/${siteId}/`, { method: 'PATCH', body: JSON.stringify({ wp_api_key: key }), }); } catch (error: any) { console.error('Failed to save API key to site:', error); throw error; } }; const handleCopyApiKey = () => { if (apiKey) { navigator.clipboard.writeText(apiKey); toast.success('API key copied to clipboard'); } }; const handleDownloadPlugin = () => { const pluginUrl = `https://github.com/igny8/igny8-wp-bridge/releases/latest/download/igny8-wp-bridge.zip`; window.open(pluginUrl, '_blank'); toast.success('Plugin download started'); }; const maskApiKey = (key: string) => { if (!key) return ''; if (key.length <= 12) return key; return key.substring(0, 8) + '**********' + key.substring(key.length - 4); }; // Toggle integration enabled status const [integrationEnabled, setIntegrationEnabled] = useState(integration?.is_active ?? true); const handleToggleIntegration = async (enabled: boolean) => { try { setIntegrationEnabled(enabled); if (integration) { // Update existing integration await integrationApi.updateIntegration(integration.id, { is_active: enabled, } as any); toast.success(enabled ? 'Integration enabled' : 'Integration disabled'); // Reload integration const updated = await integrationApi.getWordPressIntegration(siteId); if (onIntegrationUpdate && updated) { onIntegrationUpdate(updated); } } else if (enabled && apiKey) { // Create integration when enabling for first time // Use API key-only authentication (no username/password required) await integrationApi.saveWordPressIntegration(siteId, { url: siteUrl || '', username: '', // Optional when using API key app_password: '', // Optional when using API key api_key: apiKey, is_active: enabled, sync_enabled: true, }); toast.success('Integration created and enabled'); // Reload integration const updated = await integrationApi.getWordPressIntegration(siteId); if (onIntegrationUpdate && updated) { onIntegrationUpdate(updated); } } else if (enabled && !apiKey) { // Toggle enabled but no API key - show error toast.error('API key is required to enable WordPress integration'); setIntegrationEnabled(false); } } catch (error: any) { toast.error(`Failed to update integration: ${error.message}`); // Revert on error setIntegrationEnabled(!enabled); } }; useEffect(() => { if (integration) { setIntegrationEnabled(integration.is_active ?? true); } }, [integration]); return (
{/* Header with Toggle */}

WordPress Integration

Connect your WordPress site using the IGNY8 WP Bridge plugin

{/* Toggle Switch */} {apiKey && (
{integrationEnabled ? 'Enabled' : 'Disabled'}
)}
{/* API Keys Table */}

API Keys

API keys are used to authenticate requests to the IGNY8 API

{!apiKey && (
)}
{apiKey ? (
Name Status Created Action
Regenerate
Active {new Date().toLocaleDateString('en-US', { day: 'numeric', month: 'short', year: 'numeric' })}
) : (

No API key generated yet. Click "Add API Key" to generate one.

)}
{/* Plugin Download Section */} {apiKey && (

IGNY8 WP Bridge Plugin

Download and install the plugin on your WordPress site

)}
); }