/**
 * Template Library component.
 *
 * @package Schema_AI
 */

import { useState, useEffect } from '@wordpress/element';
import { TextControl, SelectControl, Spinner, TabPanel } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import TemplateCard from './TemplateCard';

function TemplateLibrary( { onApply } ) {
	const [ templates, setTemplates ] = useState( [] );
	const [ loading, setLoading ] = useState( true );
	const [ search, setSearch ] = useState( '' );
	const [ filterType, setFilterType ] = useState( '' );

	useEffect( () => {
		apiFetch( { path: '/schema-ai/v1/templates' } )
			.then( ( data ) => setTemplates( Array.isArray( data ) ? data : [] ) )
			.catch( () => setTemplates( [] ) )
			.finally( () => setLoading( false ) );
	}, [] );

	const filtered = templates.filter( ( t ) => {
		if ( search && ! t.name.toLowerCase().includes( search.toLowerCase() ) ) return false;
		if ( filterType && t.schema_type !== filterType ) return false;
		return true;
	} );

	const builtIn = filtered.filter( ( t ) => ! t.user_id );
	const userTemplates = filtered.filter( ( t ) => t.user_id );

	if ( loading ) return <Spinner />;

	return (
		<div className="schema-ai-template-library">
			<h2>{ __( 'Template Library', 'schema-ai' ) }</h2>
			<div className="schema-ai-template-filters">
				<TextControl placeholder={ __( 'Search templates...', 'schema-ai' ) } value={ search } onChange={ setSearch } />
				<SelectControl
					value={ filterType }
					options={ [
						{ label: __( 'All Types', 'schema-ai' ), value: '' },
						...[ 'Article', 'Product', 'LocalBusiness', 'FAQPage', 'Recipe', 'Event', 'HowTo', 'Review', 'Person', 'Organization', 'VideoObject', 'Course', 'Service' ].map( ( t ) => ( { label: t, value: t } ) ),
					] }
					onChange={ setFilterType }
				/>
			</div>
			<TabPanel tabs={ [
				{ name: 'builtin', title: __( 'Built-in', 'schema-ai' ) },
				{ name: 'my', title: __( 'My Templates', 'schema-ai' ) },
			] }>
				{ ( tab ) => (
					<div className="schema-ai-template-grid">
						{ ( tab.name === 'builtin' ? builtIn : userTemplates ).map( ( t, i ) => (
							<TemplateCard key={ i } template={ t } onApply={ onApply } />
						) ) }
						{ ( tab.name === 'builtin' ? builtIn : userTemplates ).length === 0 && (
							<p>{ __( 'No templates found.', 'schema-ai' ) }</p>
						) }
					</div>
				) }
			</TabPanel>
		</div>
	);
}

export default TemplateLibrary;
