/**
 * Code Editor - raw JSON editing.
 *
 * @package Schema_AI
 */

import { useState, useEffect } from '@wordpress/element';
import { Button, Notice } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { copyToClipboard } from '../../utils/helpers';

function CodeEditor( { schema, onChange } ) {
	const [ jsonText, setJsonText ] = useState( '' );
	const [ parseError, setParseError ] = useState( null );
	const [ copied, setCopied ] = useState( false );

	useEffect( () => {
		setJsonText( JSON.stringify( schema, null, 2 ) );
	}, [ schema ] );

	const handleChange = ( text ) => {
		setJsonText( text );
		setParseError( null );
	};

	const handleBlur = () => {
		try {
			const parsed = JSON.parse( jsonText );
			onChange( parsed );
			setParseError( null );
		} catch ( e ) {
			setParseError( e.message );
		}
	};

	const handleFormat = () => {
		try {
			const parsed = JSON.parse( jsonText );
			setJsonText( JSON.stringify( parsed, null, 2 ) );
			setParseError( null );
		} catch ( e ) {
			setParseError( e.message );
		}
	};

	const handleCopy = () => {
		copyToClipboard( jsonText );
		setCopied( true );
		setTimeout( () => setCopied( false ), 2000 );
	};

	return (
		<div className="schema-ai-code-editor">
			<div className="schema-ai-code-editor-actions">
				<Button variant="secondary" onClick={ handleFormat } isSmall>{ __( 'Format JSON', 'schema-ai' ) }</Button>
				<Button variant="secondary" onClick={ handleCopy } isSmall>{ copied ? __( 'Copied!', 'schema-ai' ) : __( 'Copy', 'schema-ai' ) }</Button>
			</div>
			{ parseError && <Notice status="error" isDismissible={ false }>{ parseError }</Notice> }
			<textarea
				className="schema-ai-code-textarea"
				value={ jsonText }
				onChange={ ( e ) => handleChange( e.target.value ) }
				onBlur={ handleBlur }
				rows={ 20 }
				spellCheck={ false }
			/>
		</div>
	);
}

export default CodeEditor;
