import { useEffect, useRef, useState } from 'react'; import { toast } from 'sonner'; import { KeyRound } from 'lucide-react'; import { __ } from '@wordpress/i18n'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { useConfirm } from '@/components/ConfirmDialog'; import { ajax, errorMessage } from '@/lib/api'; import { onAnchor } from '@/lib/anchors'; import { useSettingsStore } from '@/store/settings-store'; import { useApiKeyDraft } from './api-key-draft'; import type { ModelsData } from './types'; /** * Custom OpenAI key. A saved key shows masked with Change / Remove; a new * key is checked against OpenAI by "Validate & Save API Key" and saved on * its own, without the page's Save button. */ export default function ApiKeyField( { data }: { data: ModelsData } ) { const { hasKey, masked } = data.apiKey; const { draft, editing, error, success } = useApiKeyDraft(); const refresh = useSettingsStore( ( state ) => state.refresh ); const confirm = useConfirm(); const input = useRef( null ); const focusOnShow = useRef( false ); const [ validating, setValidating ] = useState( false ); const [ removing, setRemoving ] = useState( false ); const showInput = ! hasKey || editing; // Focus the key input once it replaces the masked key after Change / Remove. useEffect( () => { if ( showInput && focusOnShow.current ) { focusOnShow.current = false; input.current?.focus(); } }, [ showInput ] ); const startEditing = () => { focusOnShow.current = true; useApiKeyDraft.setState( { editing: true, draft: '', error: '', success: '' } ); }; // Fix links to #wtofe-api-key-row ("Replace the key") open the field for editing. useEffect( () => onAnchor( 'wtofe-api-key-row', () => { if ( hasKey && ! editing ) { startEditing(); } } ), [ hasKey, editing ] ); const validateAndSave = async () => { const verifyFailed = __( 'Could not verify the API key. Please try again.', 'ai-content-generator-for-woocommerce' ); const apiKey = draft.trim(); if ( '' === apiKey ) { useApiKeyDraft.setState( { error: __( 'Please enter an API key first.', 'ai-content-generator-for-woocommerce' ), success: '' } ); return; } setValidating( true ); useApiKeyDraft.setState( { error: '', success: '' } ); try { const response = await ajax<{ message?: string }>( 'wtofe_save_api_key', { nonce: data.nonces.saveKey, api_key: apiKey } ); if ( response?.success ) { useApiKeyDraft.setState( { draft: '', editing: false, success: response.data?.message || __( 'API key validated and saved successfully.', 'ai-content-generator-for-woocommerce' ), } ); await refresh(); } else { useApiKeyDraft.setState( { error: errorMessage( response, verifyFailed ) } ); } } catch { useApiKeyDraft.setState( { error: verifyFailed } ); } finally { setValidating( false ); } }; const remove = async () => { const removeFailed = __( 'Could not remove the API key. Please try again.', 'ai-content-generator-for-woocommerce' ); const confirmed = await confirm( { message: __( 'Remove the saved API key? This cannot be undone.', 'ai-content-generator-for-woocommerce' ), confirmLabel: __( 'Remove', 'ai-content-generator-for-woocommerce' ), } ); if ( ! confirmed ) { return; } setRemoving( true ); try { const response = await ajax( 'wtofe_remove_api_key', { nonce: data.nonces.removeKey } ); if ( ! response?.success ) { toast.error( errorMessage( response, removeFailed ) ); return; } focusOnShow.current = true; useApiKeyDraft.setState( { draft: '', editing: false, error: '', success: '' } ); await refresh(); } catch { toast.error( removeFailed ); } finally { setRemoving( false ); } }; return (
{ showInput ? (
useApiKeyDraft.setState( { draft, error: '', success: '' } ) } onKeyDown={ ( event ) => { if ( 'Enter' === event.key ) { event.preventDefault(); validateAndSave(); } } } />
) : (
undefined } />
) } { error && (

{ error }

) } { success &&

{ success }

}

{ __( 'Enter your OpenAI API key. This will be used instead of any configured AI Connector.', 'ai-content-generator-for-woocommerce' ) }

); }