import React, { useState, useEffect, Suspense } from 'react'; import { __ } from '@wordpress/i18n'; import { AlertCircle, Save, Undo2 } from 'lucide-react'; import { AdvancedSettings as AdvancedSettingsType } from '../types'; import { fetchSettings, sendSettingsToEndpoint } from '../utils/api'; import { MultiSelect } from './MultiSelect'; import { LoadingSpinner } from './LoadingSpinner'; import { ProAdvancedSections } from '../pro'; interface WordPressWindow extends Window { webhookButtonsSettings?: { meta_fields?: Record }; } export const AdvancedSettings: React.FC = () => { const [settings, setSettings] = useState({ general: { excludeMeta: [] } }); const [originalSettings, setOriginalSettings] = useState({ general: { excludeMeta: [] } }); // Product attribute taxonomies, from the localized variable const metaFields: Record = ((window as WordPressWindow).webhookButtonsSettings?.meta_fields || {}); const [hasChanges, setHasChanges] = useState(false); const [isSaving, setIsSaving] = useState(false); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const [notice, setNotice] = useState(null); // Fetch settings data on component mount useEffect(() => { const loadSettings = async () => { setIsLoading(true); setError(null); try { const response = await fetchSettings(); // If the response contains advanced settings, update the state if (response.success && response.settings && response.settings.advanced) { setSettings(response.settings.advanced); setOriginalSettings(JSON.parse(JSON.stringify(response.settings.advanced))); } } catch (err) { console.error('Failed to fetch advanced settings:', err); setError(__('Failed to load settings. Please refresh the page to try again.', 'webhook-buttons')); } finally { setIsLoading(false); } }; loadSettings(); }, []); // Check for changes whenever settings change useEffect(() => { const hasChanges = JSON.stringify(settings) !== JSON.stringify(originalSettings); setHasChanges(hasChanges); }, [settings, originalSettings]); const handleGeneralChange = (field: keyof typeof settings.general, value: string[]) => { setSettings(prev => ({ ...prev, general: { ...prev.general, [field]: value } })); }; const handleSave = async () => { setIsSaving(true); try { // Send advanced settings to the endpoint const result = await sendSettingsToEndpoint({ advanced: settings }); // Get the settings returned from the send Settings endpoint // Check if the response has the expected structure if (result.success && result.settings && result.settings.advanced) { // Update the current data with the returned settings setSettings(result.settings.advanced); // Update original settings to match current settings setOriginalSettings(JSON.parse(JSON.stringify(result.settings.advanced))); setNotice(__('Settings saved.', 'webhook-buttons')); setError(null); } else { console.error('Unexpected API response structure:', result); setError(__('The server sent unexpected data. Please refresh and try again.', 'webhook-buttons')); } } catch (error) { console.error('Failed to save advanced settings:', error); setError(__('Could not save settings. Please try again.', 'webhook-buttons')); } finally { setIsSaving(false); } }; const handleUndo = () => { setSettings(JSON.parse(JSON.stringify(originalSettings))); }; return (
{notice && !error && (
{notice}
)} {error && (

{__('Error', 'webhook-buttons')}

{error}

)} {isLoading ? ( ) : (

{__('Advanced settings', 'webhook-buttons')}

{__('Extra options for the data each button sends', 'webhook-buttons')}

{/* Always visible save buttons */}
{/* General Section */}

{__('General', 'webhook-buttons')}

({ value: `pa_${value}`, label }))} value={settings.general.excludeMeta} onChange={(value: string[]) => handleGeneralChange('excludeMeta', value)} placeholder={__('Select attributes to leave out…', 'webhook-buttons')} className="w-full" />

{__('These product attributes are not sent.', 'webhook-buttons')}

{ProAdvancedSections && ( setSettings(prev => ({ ...prev, ...patch }))} /> )} {/* Save Status */} {!hasChanges && (
{__('All settings saved', 'webhook-buttons')}
)}
)}
); };