import apiFetch from '@wordpress/api-fetch';
import { serialize } from '@wordpress/blocks';

const getCategoryTermId = async ( categorySlug ) => {
	try {
		const terms = await apiFetch( {
			path: `/wp/v2/wp_pattern_category?slug=${ categorySlug }`,
			method: 'GET',
		} );
		if ( terms && terms.length > 0 ) {
			return terms[ 0 ].id;
		}
		return null;
	} catch ( error ) {
		console.error( 'Failed to get category term:', error );
		return null;
	}
};

export const getPatternsByCategory = async ( categorySlug ) => {
	try {
		const termId = await getCategoryTermId( categorySlug );
		if ( ! termId ) {
			return [];
		}

		const response = await apiFetch( {
			path: `/wp/v2/blocks?wp_pattern_category=${ termId }&per_page=100`,
			method: 'GET',
		} );
		return response || [];
	} catch ( error ) {
		console.error( 'Failed to get patterns:', error );
		return [];
	}
};

export const saveBlockAsPattern = async (
	block,
	patternName,
	categorySlug
) => {
	try {
		const serializedContent = serialize( block );

		const termId = await getCategoryTermId( categorySlug );

		const data = {
			title: patternName,
			content: serializedContent,
			status: 'publish',
		};

		if ( termId ) {
			data.wp_pattern_category = [ termId ];
		}

		const response = await apiFetch( {
			path: '/wp/v2/blocks',
			method: 'POST',
			data,
		} );

		return response;
	} catch ( error ) {
		console.error( 'Failed to save pattern:', error );
		throw error;
	}
};

export const deletePattern = async ( patternId ) => {
	try {
		const response = await apiFetch( {
			path: `/wp/v2/blocks/${ patternId }?force=true`,
			method: 'DELETE',
		} );
		return response;
	} catch ( error ) {
		console.error( 'Failed to delete pattern:', error );
		throw error;
	}
};

export const updatePattern = async ( patternId, updates ) => {
	try {
		const response = await apiFetch( {
			path: `/wp/v2/blocks/${ patternId }`,
			method: 'POST',
			data: updates,
		} );
		return response;
	} catch ( error ) {
		console.error( 'Failed to update pattern:', error );
		throw error;
	}
};

export const getPatternContent = async ( patternId ) => {
	try {
		const response = await apiFetch( {
			path: `/wp/v2/blocks/${ patternId }?context=edit`,
			method: 'GET',
		} );
		return response?.content?.raw || '';
	} catch ( error ) {
		console.error( 'Failed to get pattern content:', error );
		return '';
	}
};
