/**
 * Dashboard component — redesigned.
 *
 * @package Schema_AI
 */

import { useState, useEffect } from '@wordpress/element';
import { Spinner } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { useSchema } from '../hooks/useSchema';
import { useUserContext } from '../context/UserContext';

const adminUrl = window.schemaAiData?.adminUrl || '';
const version = window.schemaAiData?.version || '';
const settings = window.schemaAiData?.settings || {};
const activationTime = window.schemaAiData?.activationTime || 0;
const planLabel = window.schemaAiData?.plan || 'free';

function ConnectionBanner() {
	const hasKey = !! settings.api_key;
	if ( hasKey ) {
		const planNames = { free: __( 'Free Plan', 'schema-ai' ), pro: __( 'Pro Plan', 'schema-ai' ), premium: __( 'Premium Plan', 'schema-ai' ) };
		const label = planNames[ planLabel ] || planNames.free;
		return (
			<div className="schema-ai-connection-banner schema-ai-connection-banner--connected">
				<span className="dashicons dashicons-yes-alt"></span>
				<span>{ __( 'Connected', 'schema-ai' ) } &middot; { label }</span>
			</div>
		);
	}
	return (
		<div className="schema-ai-connection-banner schema-ai-connection-banner--disconnected">
			<span className="dashicons dashicons-warning"></span>
			<span>{ __( 'Not connected', 'schema-ai' ) }</span>
			<a href={ adminUrl + 'admin.php?page=schema-ai-setup' } className="button button-small">
				{ __( 'Run Setup Wizard', 'schema-ai' ) }
			</a>
		</div>
	);
}

function StatsCard( { label, value, colorClass, icon } ) {
	return (
		<div className="schema-ai-stat-card">
			<div className={ `schema-ai-stat-icon ${ colorClass }` }>
				<span className={ `dashicons dashicons-${ icon }` }></span>
			</div>
			<div className="schema-ai-stat-number">{ value }</div>
			<div className="schema-ai-stat-label">{ label }</div>
		</div>
	);
}

function RecentSchemasTable( { recent, onRegenerate } ) {
	if ( ! recent || recent.length === 0 ) {
		return (
			<div className="schema-ai-empty-state">
				<span className="dashicons dashicons-editor-code"></span>
				<p>{ __( 'No schemas generated yet.', 'schema-ai' ) }</p>
				<a href={ adminUrl + 'post-new.php' } className="button button-primary">
					{ __( 'Create a Post', 'schema-ai' ) }
				</a>
			</div>
		);
	}
	return (
		<table className="widefat striped">
			<thead>
				<tr>
					<th>{ __( 'Post', 'schema-ai' ) }</th>
					<th>{ __( 'Type', 'schema-ai' ) }</th>
					<th>{ __( 'Status', 'schema-ai' ) }</th>
					<th>{ __( 'Date', 'schema-ai' ) }</th>
					<th>{ __( 'Actions', 'schema-ai' ) }</th>
				</tr>
			</thead>
			<tbody>
				{ recent.map( ( item, i ) => (
					<tr key={ i }>
						<td>
							{ item.post_url ? (
								<a href={ item.post_url }>{ item.post_title || `Post #${ item.post_id }` }</a>
							) : (
								item.post_title || `Post #${ item.post_id }`
							) }
						</td>
						<td><span className="schema-ai-badge schema-ai-badge--type">{ item.schema_type }</span></td>
						<td><span className={ `schema-ai-validation schema-ai-validation--${ item.validation_status }` }>{ item.validation_status }</span></td>
						<td>{ item.created_at }</td>
						<td className="schema-ai-actions-cell">
							<RegenerateButton postId={ item.post_id } onDone={ onRegenerate } />
							{ item.post_url && (
								<a
									href={ `https://search.google.com/test/rich-results?url=${ encodeURIComponent( item.post_url ) }` }
									target="_blank"
									rel="noopener noreferrer"
									className="schema-ai-test-google-link"
								>
									{ __( 'Test', 'schema-ai' ) } &#8599;
								</a>
							) }
						</td>
					</tr>
				) ) }
			</tbody>
		</table>
	);
}

function RegenerateButton( { postId, onDone } ) {
	const [ status, setStatus ] = useState( 'idle' );
	const [ errorMsg, setErrorMsg ] = useState( '' );

	const handleRegenerate = async () => {
		if ( status === 'loading' ) {
			return;
		}
		setStatus( 'loading' );
		setErrorMsg( '' );
		try {
			await apiFetch( {
				path: '/schema-ai/v1/generate',
				method: 'POST',
				data: { post_id: postId },
			} );
			setStatus( 'success' );
			if ( onDone ) {
				onDone();
			}
			setTimeout( () => setStatus( 'idle' ), 3000 );
		} catch ( err ) {
			const msg = err?.message || __( 'Generation failed. Please try again.', 'schema-ai' );
			if ( err?.code === 'schema_ai_rate_limited' ) {
				setErrorMsg( __( 'Monthly limit reached. Upgrade your plan for more.', 'schema-ai' ) );
			} else {
				setErrorMsg( msg );
			}
			setStatus( 'error' );
			setTimeout( () => { setStatus( 'idle' ); setErrorMsg( '' ); }, 5000 );
		}
	};

	let label = __( 'Regenerate', 'schema-ai' );
	let icon = 'update';
	if ( status === 'loading' ) {
		label = __( 'Generating...', 'schema-ai' );
		icon = 'update schema-ai-spin';
	} else if ( status === 'success' ) {
		label = __( 'Done!', 'schema-ai' );
		icon = 'yes';
	} else if ( status === 'error' ) {
		label = errorMsg;
		icon = 'warning';
	}

	return (
		<button
			type="button"
			className={ `schema-ai-regenerate-btn schema-ai-regenerate-btn--${ status }` }
			onClick={ handleRegenerate }
			disabled={ status === 'loading' }
			title={ status === 'error' ? errorMsg : '' }
		>
			<span className={ `dashicons dashicons-${ icon }` }></span>
			{ status === 'error' ? __( 'Failed', 'schema-ai' ) : label }
			{ status === 'error' && (
				<span className="schema-ai-error-tooltip">{ errorMsg }</span>
			) }
		</button>
	);
}

const MONTHLY_LIMITS = { free: 30, pro: 300, premium: 1000 };

function UsageCard( { plan, usage } ) {
	// Prefer the limit returned by the backend (respects customMonthlyLimit).
	// Fall back to hardcoded plan defaults only if the API hasn't responded yet.
	const limit = usage.limit ?? MONTHLY_LIMITS[ plan ] ?? 30;
	const remaining = usage.remaining ?? limit;
	const pct = Math.min( 100, ( remaining / limit ) * 100 );

	return (
		<div className="schema-ai-card">
			<h2>{ __( 'Usage', 'schema-ai' ) }</h2>
			<div className="schema-ai-usage-widget">
				<div className="schema-ai-usage-bar">
					<div
						className="schema-ai-usage-bar-fill"
						style={ { width: `${ pct }%` } }
					></div>
				</div>
				<p className="schema-ai-usage-text">
					{ `${ remaining } / ${ limit } ${ __( 'remaining this month', 'schema-ai' ) }` }
				</p>
				{ plan === 'free' && (
					<p className="schema-ai-usage-upgrade">
						<a href={ adminUrl + 'admin.php?page=schema-ai-upgrade' }>
							{ __( 'Upgrade for more', 'schema-ai' ) }
						</a>
					</p>
				) }
			</div>
		</div>
	);
}

function GettingStartedCard( { totalSchemas } ) {
	// Show only within first 7 days of activation.
	if ( ! activationTime ) {
		return null;
	}
	const daysSinceActivation = ( Date.now() / 1000 - activationTime ) / 86400;
	if ( daysSinceActivation > 7 ) {
		return null;
	}

	const hasKey = !! settings.api_key;
	const hasSchema = totalSchemas > 0;

	return (
		<div className="schema-ai-card">
			<h2>{ __( 'Getting Started', 'schema-ai' ) }</h2>
			<ul className="schema-ai-checklist">
				<li className="schema-ai-checklist-item schema-ai-checklist-item--done">
					<span className="dashicons dashicons-yes-alt"></span>
					{ __( 'Install plugin', 'schema-ai' ) }
				</li>
				<li className={ `schema-ai-checklist-item ${ hasKey ? 'schema-ai-checklist-item--done' : '' }` }>
					<span className={ `dashicons dashicons-${ hasKey ? 'yes-alt' : 'marker' }` }></span>
					{ hasKey ? (
						__( 'Connect API key', 'schema-ai' )
					) : (
						<a href={ adminUrl + 'admin.php?page=schema-ai-setup' }>{ __( 'Connect API key', 'schema-ai' ) }</a>
					) }
				</li>
				<li className={ `schema-ai-checklist-item ${ hasSchema ? 'schema-ai-checklist-item--done' : '' }` }>
					<span className={ `dashicons dashicons-${ hasSchema ? 'yes-alt' : 'marker' }` }></span>
					{ hasSchema ? (
						__( 'Generate first schema', 'schema-ai' )
					) : (
						<a href={ adminUrl + 'post-new.php' }>{ __( 'Generate first schema', 'schema-ai' ) }</a>
					) }
				</li>
				<li className="schema-ai-checklist-item">
					<span className="dashicons dashicons-marker"></span>
					<a href={ adminUrl + 'admin.php?page=schema-ai-tester' }>{ __( 'Test with Google', 'schema-ai' ) }</a>
				</li>
			</ul>
		</div>
	);
}

function QuickActionsCard() {
	return (
		<div className="schema-ai-card">
			<h2>{ __( 'Quick Actions', 'schema-ai' ) }</h2>
			<div className="schema-ai-quick-actions-list">
				<a href={ adminUrl + 'admin.php?page=schema-ai-tester' } className="schema-ai-quick-action">
					<span className="dashicons dashicons-search"></span>
					{ __( 'Test a Page', 'schema-ai' ) }
				</a>
				<a href={ adminUrl + 'admin.php?page=schema-ai-settings' } className="schema-ai-quick-action">
					<span className="dashicons dashicons-admin-generic"></span>
					{ __( 'Settings', 'schema-ai' ) }
				</a>
			</div>
		</div>
	);
}

function Dashboard() {
	const { stats, fetchStats, loading } = useSchema();
	const { plan, usage } = useUserContext();

	useEffect( () => {
		fetchStats();
	}, [ fetchStats ] );

	const totalSchemas = stats?.total_schemas || 0;
	const validSchemas = stats?.by_status?.valid || 0;
	const schemaTypes = stats?.by_type ? Object.keys( stats.by_type ).length : 0;
	const todayGenerations = stats?.today_generations || 0;

	return (
		<div className="schema-ai-dashboard">
			{ /* Header Bar */ }
			<div className="schema-ai-header">
				<div className="schema-ai-header-left">
					<h1 className="schema-ai-header-title">{ __( 'Schema AI', 'schema-ai' ) }</h1>
					{ version && <span className="schema-ai-header-version">v{ version }</span> }
				</div>
				<div className="schema-ai-header-right">
					<a href={ adminUrl + 'admin.php?page=schema-ai-settings' } className="schema-ai-header-settings-link" title={ __( 'Settings', 'schema-ai' ) }>
						<span className="dashicons dashicons-admin-generic"></span>
					</a>
				</div>
			</div>

			{ /* Connection Status Banner */ }
			<ConnectionBanner />

			{ loading ? (
				<div className="schema-ai-loading"><Spinner /></div>
			) : (
				<>
					{ /* Stats Grid */ }
					<div className="schema-ai-stats-grid">
						<StatsCard label={ __( 'Total Schemas', 'schema-ai' ) } value={ totalSchemas } colorClass="schema-ai-stat-icon--schemas" icon="editor-code" />
						<StatsCard label={ __( 'Valid', 'schema-ai' ) } value={ validSchemas } colorClass="schema-ai-stat-icon--valid" icon="yes-alt" />
						<StatsCard label={ __( 'Schema Types', 'schema-ai' ) } value={ schemaTypes } colorClass="schema-ai-stat-icon--types" icon="category" />
						<StatsCard label={ __( 'AI Generations Today', 'schema-ai' ) } value={ todayGenerations } colorClass="schema-ai-stat-icon--generations" icon="superhero" />
					</div>

					{ /* Two-column layout */ }
					<div className="schema-ai-content-grid">
						<div className="schema-ai-content-main">
							<div className="schema-ai-card">
								<h2>{ __( 'Recent Schemas', 'schema-ai' ) }</h2>
								<RecentSchemasTable recent={ stats?.recent } onRegenerate={ fetchStats } />
							</div>
						</div>

						<div className="schema-ai-content-sidebar">
							<UsageCard plan={ plan } usage={ usage } />
							<GettingStartedCard totalSchemas={ totalSchemas } />
							<QuickActionsCard />
						</div>
					</div>
				</>
			) }
		</div>
	);
}

export default Dashboard;
