/**
 * Errors List - validation errors across schemas.
 *
 * @package Schema_AI
 */

import { useState, useEffect } from '@wordpress/element';
import { Button, Spinner } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';

function ErrorsList() {
	const [ schemas, setSchemas ] = useState( [] );
	const [ loading, setLoading ] = useState( true );

	useEffect( () => {
		apiFetch( { path: '/schema-ai/v1/schema/list?validation_status=invalid&per_page=20' } )
			.then( ( data ) => setSchemas( data.items || data || [] ) )
			.catch( () => setSchemas( [] ) )
			.finally( () => setLoading( false ) );
	}, [] );

	const handleRevalidate = async ( postId ) => {
		try {
			await apiFetch( { path: `/schema-ai/v1/validate/${ postId }`, method: 'POST' } );
			// Refresh the list.
			const data = await apiFetch( { path: '/schema-ai/v1/schema/list?validation_status=invalid&per_page=20' } );
			setSchemas( data.items || data || [] );
		} catch ( err ) {
			alert( err.message );
		}
	};

	if ( loading ) return <Spinner />;

	return (
		<div className="schema-ai-errors-list">
			<h3>{ __( 'Schemas with Errors', 'schema-ai' ) }</h3>
			{ schemas.length === 0 ? (
				<p>{ __( 'No schemas with errors.', 'schema-ai' ) }</p>
			) : (
				<table className="widefat">
					<thead>
						<tr>
							<th>{ __( 'Post', 'schema-ai' ) }</th>
							<th>{ __( 'Type', 'schema-ai' ) }</th>
							<th>{ __( 'Errors', 'schema-ai' ) }</th>
							<th>{ __( 'Actions', 'schema-ai' ) }</th>
						</tr>
					</thead>
					<tbody>
						{ 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>{ s.schema_type }</td>
								<td>{ s.validation_errors?.length || 0 }</td>
								<td><Button isSmall onClick={ () => handleRevalidate( s.post_id ) }>{ __( 'Revalidate', 'schema-ai' ) }</Button></td>
							</tr>
						) ) }
					</tbody>
				</table>
			) }
		</div>
	);
}

export default ErrorsList;
