/**
 * MetaBox component for the post editor.
 *
 * @package Schema_AI
 */

import { useState, useEffect } from '@wordpress/element';
import { Spinner, Notice } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useSchema } from '../hooks/useSchema';
import { useUserContext } from '../context/UserContext';
import AIGenerator from './SchemaBuilder/AIGenerator';
import VisualEditor from './SchemaBuilder/VisualEditor';
import CodeEditor from './SchemaBuilder/CodeEditor';

function MetaBox( { postId } ) {
	const { schemas, loading, error, fetchSchemas, deleteSchema } = useSchema( postId );
	const { plan, usage } = useUserContext();
	const [ activeTab, setActiveTab ]     = useState( 'generate' );
	const [ currentSchema, setCurrentSchema ] = useState( null );
	const [ panelOpen, setPanelOpen ]     = useState( false );

	useEffect( () => {
		if ( schemas.length > 0 ) {
			setCurrentSchema( schemas[ 0 ] );
			setActiveTab( 'visual' );
		}
	}, [ schemas ] );

	const handleTabChange = ( id ) => {
		setActiveTab( id );
	};

	const handleSchemaGenerated = () => {
		fetchSchemas( postId );
	};

	const handleDelete = async () => {
		if ( currentSchema && window.confirm( __( 'Delete this schema?', 'schema-ai' ) ) ) {
			await deleteSchema( currentSchema.id );
			setCurrentSchema( null );
			setActiveTab( 'generate' );
		}
	};

	if ( loading ) {
		return (
			<div className="saib-loading">
				<Spinner />
			</div>
		);
	}

	return (
		<div className="saib-react-area">
			{ error && (
				<Notice status="error" isDismissible={ false }>
					{ error }
				</Notice>
			) }

			{ currentSchema ? (
				<>
					{ /* Tab nav + collapse toggle on the right */ }
					<div className="saib-tab-bar">
						<nav className="saib-tab-nav">
							{ [
								{ id: 'visual',   label: __( 'Visual', 'schema-ai' ) },
								{ id: 'code',     label: __( 'Code', 'schema-ai' ) },
								{ id: 'generate', label: __( 'Regenerate', 'schema-ai' ) },
							].map( ( tab ) => (
								<button
									key={ tab.id }
									type="button"
									className={ `saib-tab-btn${ activeTab === tab.id ? ' saib-tab-btn--active' : '' }` }
									onClick={ () => handleTabChange( tab.id ) }
								>
									{ tab.label }
								</button>
							) ) }
						</nav>

						{ /* Only show collapse toggle for Visual and Code tabs */ }
						{ ( activeTab === 'visual' || activeTab === 'code' ) && (
							<button
								type="button"
								className="saib-collapse-btn"
								onClick={ () => setPanelOpen( ( v ) => ! v ) }
								title={ panelOpen ? __( 'Collapse', 'schema-ai' ) : __( 'Expand', 'schema-ai' ) }
							>
								{ panelOpen ? '▲' : '▼' }
							</button>
						) }
					</div>

					{ /* Tab content — hidden when collapsed */ }
					{ panelOpen && (
						<div className="saib-tab-panel">
							{ activeTab === 'visual' && (
								<VisualEditor
									schema={ currentSchema.schema_data }
									onChange={ ( s ) => setCurrentSchema( { ...currentSchema, schema_data: s } ) }
									schemaType={ currentSchema.schema_type }
								/>
							) }
							{ activeTab === 'code' && (
								<CodeEditor
									schema={ currentSchema.schema_data }
									onChange={ ( s ) => setCurrentSchema( { ...currentSchema, schema_data: s } ) }
								/>
							) }
							{ activeTab === 'generate' && (
								<AIGenerator postId={ postId } onSchemaGenerated={ handleSchemaGenerated } />
							) }
						</div>
					) }

					{ /* Action row */ }
					<div className="saib-actions">
						<button type="button" className="button button-primary">
							{ __( 'Save Schema', 'schema-ai' ) }
						</button>
						<a
							href={ `https://search.google.com/test/rich-results?url=${ encodeURIComponent( currentSchema.post_url || '' ) }` }
							target="_blank"
							rel="noopener noreferrer"
							className="button"
						>
							{ __( 'Test with Google', 'schema-ai' ) }
						</a>
						<button
							type="button"
							className="saib-btn-delete"
							onClick={ handleDelete }
						>
							{ __( 'Delete', 'schema-ai' ) }
						</button>
					</div>
				</>
			) : (
				<AIGenerator postId={ postId } onSchemaGenerated={ handleSchemaGenerated } />
			) }
		</div>
	);
}

export default MetaBox;
