/**
 * Schema Context - provides schema state across the app.
 *
 * @package Schema_AI
 */

import { createContext, useContext, useState, useCallback } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';

const SchemaContext = createContext();

export function SchemaProvider( { children } ) {
	const [ schemas, setSchemas ] = useState( [] );
	const [ currentSchema, setCurrentSchema ] = useState( null );
	const [ loading, setLoading ] = useState( false );
	const [ error, setError ] = useState( null );
	const [ stats, setStats ] = useState( null );

	const fetchSchemas = useCallback( async ( postId ) => {
		setLoading( true );
		setError( null );
		try {
			const data = await apiFetch( { path: `/schema-ai/v1/schema/${ postId }` } );
			setSchemas( Array.isArray( data ) ? data : [ data ] );
			return data;
		} catch ( err ) {
			setError( err.message );
			return [];
		} finally {
			setLoading( false );
		}
	}, [] );

	const saveSchema = useCallback( async ( postId, schemaData ) => {
		setLoading( true );
		try {
			const data = await apiFetch( {
				path: '/schema-ai/v1/schema',
				method: 'POST',
				data: schemaData,
			} );
			await fetchSchemas( postId );
			return data;
		} catch ( err ) {
			setError( err.message );
			throw err;
		} finally {
			setLoading( false );
		}
	}, [ fetchSchemas ] );

	const updateSchema = useCallback( async ( postId, schemaId, schemaData ) => {
		setLoading( true );
		try {
			const data = await apiFetch( {
				path: `/schema-ai/v1/schema/${ postId }`,
				method: 'PUT',
				data: { schema_id: schemaId, schema_data: schemaData },
			} );
			await fetchSchemas( postId );
			return data;
		} catch ( err ) {
			setError( err.message );
			throw err;
		} finally {
			setLoading( false );
		}
	}, [ fetchSchemas ] );

	const deleteSchema = useCallback( async ( postId, schemaId ) => {
		setLoading( true );
		try {
			await apiFetch( {
				path: `/schema-ai/v1/schema/${ postId }`,
				method: 'DELETE',
				data: { schema_id: schemaId },
			} );
			await fetchSchemas( postId );
		} catch ( err ) {
			setError( err.message );
			throw err;
		} finally {
			setLoading( false );
		}
	}, [ fetchSchemas ] );

	const fetchStats = useCallback( async () => {
		try {
			const data = await apiFetch( { path: '/schema-ai/v1/stats' } );
			setStats( data );
			return data;
		} catch ( err ) {
			setError( err.message );
			return null;
		}
	}, [] );

	const value = {
		schemas,
		currentSchema,
		setCurrentSchema,
		loading,
		error,
		stats,
		actions: { fetchSchemas, saveSchema, updateSchema, deleteSchema, fetchStats },
	};

	return (
		<SchemaContext.Provider value={ value }>
			{ children }
		</SchemaContext.Provider>
	);
}

export function useSchemaContext() {
	const context = useContext( SchemaContext );
	if ( ! context ) {
		throw new Error( 'useSchemaContext must be used within a SchemaProvider' );
	}
	return context;
}

export default SchemaContext;
