/**
 * AI Generator component.
 *
 * @package Schema_AI
 */

import { useState } from '@wordpress/element';
import { Button, Card, CardBody, Notice, Spinner } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useAI } from '../../hooks/useAI';

function AIGenerator( { postId, onSchemaGenerated } ) {
	const [ loading, setLoading ] = useState( false );
	const [ analysis, setAnalysis ] = useState( null );
	const [ schema, setSchema ] = useState( null );
	const [ error, setError ] = useState( null );
	const [ limitReached, setLimitReached ] = useState( false );

	const { generate, canGenerate } = useAI();

	const handleGenerate = async ( schemaType = null ) => {
		if ( ! canGenerate() ) {
			setError( __( 'Monthly AI generation limit reached. Please upgrade to continue.', 'schema-ai' ) );
			return;
		}

		setLoading( true );
		setError( null );
		setLimitReached( false );

		try {
			const result = await generate.schema( postId, schemaType );
			setAnalysis( result.analysis );
			setSchema( result );

			if ( onSchemaGenerated ) {
				onSchemaGenerated( result );
			}
		} catch ( err ) {
			if ( err.code === 'schema_ai_limit_reached' ) {
				setLimitReached( true );
			} else {
				setError( err.message );
			}
		} finally {
			setLoading( false );
		}
	};

	return (
		<Card className="schema-ai-generator">
			<CardBody>
				{ limitReached && (
					<div className="saib-limit-notice">
						<p><strong>{ __( 'Monthly limit reached', 'schema-ai' ) }</strong></p>
						<p>{ __( 'You\'ve used all your free generations this month.', 'schema-ai' ) }</p>
						<a href={ window.schemaAiData?.upgradeUrl || '#' } className="button button-primary">
							{ __( 'Upgrade Plan', 'schema-ai' ) }
						</a>
					</div>
				) }

				{ error && <Notice status="error" isDismissible={ false }>{ error }</Notice> }

				{ ! analysis && ! loading && ! limitReached && (
					<div className="schema-ai-generator-start">
						<p>{ __( 'Let AI analyze your content and generate perfect schema markup automatically.', 'schema-ai' ) }</p>
						<Button variant="primary" onClick={ () => handleGenerate() } disabled={ ! canGenerate() } size="large">
							{ __( 'Generate Schema with AI', 'schema-ai' ) }
						</Button>
					</div>
				) }

				{ loading && (
					<div className="schema-ai-generator-loading">
						<Spinner />
						<p>{ __( 'AI is analyzing your content...', 'schema-ai' ) }</p>
					</div>
				) }

				{ analysis && (
					<div className="schema-ai-generator-result">
						<div className="schema-ai-analysis">
							<h3>{ __( 'Content Analysis', 'schema-ai' ) }</h3>
							<div className="schema-ai-detected-type">
								<strong>{ __( 'Detected Type:', 'schema-ai' ) }</strong>
								<span className="schema-ai-badge">{ analysis.primary_schema }</span>
								{ analysis.confidence && (
									<span className="schema-ai-confidence">{ `${ Math.round( analysis.confidence * 100 ) }%` }</span>
								) }
							</div>

							{ analysis.alternative_schemas?.length > 0 && (
								<div className="schema-ai-alternatives">
									<strong>{ __( 'Alternative Schemas:', 'schema-ai' ) }</strong>
									<div className="schema-ai-alternatives-list">
										{ analysis.alternative_schemas.map( ( alt ) => (
											<Button key={ alt.type } variant="secondary" onClick={ () => handleGenerate( alt.type ) } disabled={ loading } isSmall>
												{ `${ alt.type } (${ Math.round( alt.confidence * 100 ) }%)` }
											</Button>
										) ) }
									</div>
								</div>
							) }

							{ analysis.reasoning && (
								<div className="schema-ai-reasoning">
									<strong>{ __( 'Why this schema?', 'schema-ai' ) }</strong>
									<p>{ analysis.reasoning }</p>
								</div>
							) }
						</div>

						{ schema && (
							<div className="schema-ai-schema-preview">
								<h3>{ __( 'Generated Schema', 'schema-ai' ) }</h3>
								<pre>{ JSON.stringify( schema.schema, null, 2 ) }</pre>
							</div>
						) }
					</div>
				) }
			</CardBody>
		</Card>
	);
}

export default AIGenerator;
