/**
 * Schema Manager - lists all schemas across posts.
 *
 * @package Schema_AI
 */

import { useState, useEffect, useCallback } from '@wordpress/element';
import { Button, SelectControl, Spinner } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';

function SchemaManager() {
	const [ schemas, setSchemas ] = useState( [] );
	const [ loading, setLoading ] = useState( true );
	const [ page, setPage ] = useState( 1 );
	const [ totalPages, setTotalPages ] = useState( 1 );
	const [ filterType, setFilterType ] = useState( '' );
	const [ filterStatus, setFilterStatus ] = useState( '' );

	const fetchSchemas = useCallback( async () => {
		setLoading( true );
		try {
			const params = new URLSearchParams( { page, per_page: 20 } );
			if ( filterType ) params.append( 'schema_type', filterType );
			if ( filterStatus ) params.append( 'validation_status', filterStatus );

			const data = await apiFetch( { path: `/schema-ai/v1/schema/list?${ params }` } );
			setSchemas( data.items || data || [] );
			setTotalPages( data.total_pages || 1 );
		} catch ( err ) {
			setSchemas( [] );
		} finally {
			setLoading( false );
		}
	}, [ page, filterType, filterStatus ] );

	useEffect( () => { fetchSchemas(); }, [ fetchSchemas ] );

	const handleDelete = async ( schemaId, postId ) => {
		if ( ! window.confirm( __( 'Delete this schema?', 'schema-ai' ) ) ) return;
		try {
			await apiFetch( { path: `/schema-ai/v1/schema/${ postId }`, method: 'DELETE', data: { schema_id: schemaId } } );
			fetchSchemas();
		} catch ( err ) {
			alert( err.message );
		}
	};

	return (
		<div className="schema-ai-schemas-page">
			<h1>{ __( 'All Schemas', 'schema-ai' ) }</h1>

			<div className="schema-ai-filters">
				<SelectControl
					label={ __( 'Schema Type', 'schema-ai' ) }
					value={ filterType }
					options={ [
						{ label: __( 'All Types', 'schema-ai' ), value: '' },
						{ label: 'Article', value: 'Article' },
						{ label: 'Product', value: 'Product' },
						{ label: 'LocalBusiness', value: 'LocalBusiness' },
						{ label: 'FAQPage', value: 'FAQPage' },
						{ label: 'HowTo', value: 'HowTo' },
						{ label: 'Event', value: 'Event' },
						{ label: 'Recipe', value: 'Recipe' },
						{ label: 'Review', value: 'Review' },
						{ label: 'Person', value: 'Person' },
						{ label: 'Organization', value: 'Organization' },
						{ label: 'VideoObject', value: 'VideoObject' },
						{ label: 'Course', value: 'Course' },
						{ label: 'Service', value: 'Service' },
					] }
					onChange={ ( v ) => { setFilterType( v ); setPage( 1 ); } }
				/>
				<SelectControl
					label={ __( 'Status', 'schema-ai' ) }
					value={ filterStatus }
					options={ [
						{ label: __( 'All Statuses', 'schema-ai' ), value: '' },
						{ label: __( 'Valid', 'schema-ai' ), value: 'valid' },
						{ label: __( 'Pending', 'schema-ai' ), value: 'pending' },
						{ label: __( 'Invalid', 'schema-ai' ), value: 'invalid' },
					] }
					onChange={ ( v ) => { setFilterStatus( v ); setPage( 1 ); } }
				/>
			</div>

			{ loading ? <Spinner /> : (
				<>
					<table className="widefat schema-ai-table">
						<thead>
							<tr>
								<th>{ __( 'Post', 'schema-ai' ) }</th>
								<th>{ __( 'Schema Type', 'schema-ai' ) }</th>
								<th>{ __( 'Status', 'schema-ai' ) }</th>
								<th>{ __( 'Confidence', 'schema-ai' ) }</th>
								<th>{ __( 'Date', 'schema-ai' ) }</th>
								<th>{ __( 'Actions', 'schema-ai' ) }</th>
							</tr>
						</thead>
						<tbody>
							{ schemas.length === 0 ? (
								<tr><td colSpan="6">{ __( 'No schemas found.', 'schema-ai' ) }</td></tr>
							) : schemas.map( ( s ) => (
								<tr key={ s.id }>
									<td><a href={ `${ window.schemaAiData?.adminUrl }post.php?post=${ s.post_id }&action=edit` }>{ s.post_title || `#${ s.post_id }` }</a></td>
									<td><span className="schema-ai-badge">{ s.schema_type }</span></td>
									<td><span className={ `schema-ai-status schema-ai-status--${ s.validation_status }` }>{ s.validation_status }</span></td>
									<td>{ s.confidence_score ? `${ Math.round( s.confidence_score * 100 ) }%` : '—' }</td>
									<td>{ s.created_at }</td>
									<td>
									{ s.post_url && (
										<a
											href={ `https://search.google.com/test/rich-results?url=${ encodeURIComponent( s.post_url ) }` }
											target="_blank"
											rel="noopener noreferrer"
											className="button button-small"
											style={ { marginRight: '4px' } }
										>
											{ __( 'Test', 'schema-ai' ) }
										</a>
									) }
									<Button isDestructive isSmall onClick={ () => handleDelete( s.id, s.post_id ) }>{ __( 'Delete', 'schema-ai' ) }</Button>
								</td>
								</tr>
							) ) }
						</tbody>
					</table>
					{ totalPages > 1 && (
						<div className="schema-ai-pagination">
							<Button disabled={ page <= 1 } onClick={ () => setPage( page - 1 ) }>{ __( 'Previous', 'schema-ai' ) }</Button>
							<span>{ `${ page } / ${ totalPages }` }</span>
							<Button disabled={ page >= totalPages } onClick={ () => setPage( page + 1 ) }>{ __( 'Next', 'schema-ai' ) }</Button>
						</div>
					) }
				</>
			) }
		</div>
	);
}

export default SchemaManager;
