import { useCallback, useEffect, useMemo, useState } from '@wordpress/element';
import { loadAuthorPerfPayload, markReactAdminReady, runAuthorDeskOverview } from './api';
import { AuthorExpandPanel } from './components/AuthorExpandPanel';
import { LoadingState } from './components/LoadingState';
import { ProgressBar } from './components/ProgressBar';

export default function AuthorPerfApp() {
	const [ payload, setPayload ] = useState( null );
	const [ loading, setLoading ] = useState( true );
	const [ query, setQuery ] = useState( '' );
	const [ openId, setOpenId ] = useState( null );
	const [ days, setDays ] = useState( 30 );
	const [ overviewHtml, setOverviewHtml ] = useState( '' );
	const [ overviewBusy, setOverviewBusy ] = useState( false );
	const [ error, setError ] = useState( '' );

	const load = useCallback( async ( d ) => {
		setLoading( true );
		setError( '' );
		try {
			const data = await loadAuthorPerfPayload( d );
			setPayload( data );
		} catch ( e ) {
			setError( e && e.message ? String( e.message ) : 'load_failed' );
		} finally {
			markReactAdminReady();
			setLoading( false );
		}
	}, [] );

	useEffect( () => { load( days ); }, [ days, load ] );

	const i18n = payload?.i18n || {};
	const filtered = useMemo( () => {
		const q = query.trim().toLowerCase();
		const list = payload?.authors || [];
		if ( ! q ) {
			return list;
		}
		return list.filter( ( a ) => {
			return ( a.name || '' ).toLowerCase().includes( q ) || ( a.role || '' ).toLowerCase().includes( q );
		} );
	}, [ payload, query ] );

	if ( loading && ! payload ) {
		return <LoadingState label={ i18n.loading || 'Loading…' } />;
	}
	if ( ! payload ) {
		return (
			<div className="nros-page nros-page--perf">
				<div className="nros-page-error">
					<h2>{ i18n.error || 'Author Performance could not load.' }</h2>
					{ error && <p><code>{ error }</code></p> }
					<button type="button" className="button button-primary" onClick={ () => load( days ) }>Retry</button>
				</div>
			</div>
		);
	}
	if ( ! payload.allowed ) {
		const boot = window.newsroomSettingsBoot || {};
		let detail = i18n.pro_only;
		if ( payload.denyReason === 'pro' ) {
			detail = i18n.pro_only_license || i18n.pro_only;
		} else if ( payload.denyReason === 'capability' ) {
			detail = i18n.pro_only_capability || i18n.pro_only;
		} else if ( payload.denyReason === 'error' && payload.error ) {
			detail = payload.error;
		}
		return (
			<div className="nros-page nros-page--perf">
				<div className="nros-page-error">
					<h2>{ detail }</h2>
					{ payload.denyReason === 'pro' && boot.proPageUrl && (
						<p><a className="button button-primary" href={ boot.proPageUrl }>{ i18n.activate_pro || 'Activate PRO' }</a></p>
					) }
					{ payload.urls?.classic && (
						<p><a className="button" href={ payload.urls.classic }>{ i18n.classicLink || 'Open classic view' }</a></p>
					) }
				</div>
			</div>
		);
	}
	const authors = payload.authors || [];

	const onDeskOverview = async () => {
		setOverviewBusy( true );
		try {
			const html = await runAuthorDeskOverview( days );
			setOverviewHtml( html );
		} finally {
			setOverviewBusy( false );
		}
	};

	const onExport = () => window.print();

	return (
		<div className="nros-page nros-page--perf nros-ap-print" id="nros-ap-print-area">
			<header className="nros-page__head">
				<div>
					<h1 className="nros-page__title">{ i18n.title }</h1>
					<p className="nros-page__sub">{ i18n.subtitle }</p>
				</div>
				<div className="nros-page__actions">
					<div className="nros-days-chips">
						{ [ [ 7, i18n.days_7 ], [ 30, i18n.days_30 ], [ 90, i18n.days_90 ] ].map( ( [ d, label ] ) => (
							<button
								key={ d }
								type="button"
								className={ `nros-workflow__chip${ days === d ? ' is-active' : '' }` }
								onClick={ () => setDays( d ) }
							>
								{ label }
							</button>
						) ) }
					</div>
					<button type="button" className="button" onClick={ onExport }>{ i18n.export_pdf }</button>
					{ payload.aiDeskReady && (
						<button type="button" className="button button-primary nros-ai-desk-btn" disabled={ overviewBusy } onClick={ onDeskOverview }>
							{ overviewBusy ? i18n.overview_loading : i18n.ai_desk }
						</button>
					) }
				</div>
			</header>

			{ overviewHtml && (
				<div className="nros-bento-card nros-ai-desk-result" dangerouslySetInnerHTML={ { __html: overviewHtml } } />
			) }

			<div className="nros-perf-toolbar">
				<input
					type="search"
					className="nros-perf-search"
					placeholder={ i18n.search }
					value={ query }
					onChange={ ( e ) => setQuery( e.target.value ) }
				/>
			</div>

			<div className="nros-perf-list">
				{ authors.length === 0 && (
					<div className="nros-empty-card nros-bento-card">
						<p>{ payload.gscReady ? i18n.no_coaching : ( i18n.pro_only || 'No author data yet.' ) }</p>
					</div>
				) }
				{ filtered.map( ( author ) => (
					<article
						key={ author.userId }
						className={ `nros-perf-card${ author.isSelf ? ' is-self' : '' }${ openId === author.userId ? ' is-open' : '' }` }
					>
						<div className="nros-perf-card__main">
							<div className="nros-perf-card__identity">
								{ author.avatar ? (
									<img src={ author.avatar } alt="" className="nros-perf-card__avatar" />
								) : (
									<span className="nros-perf-card__initials">{ author.initials }</span>
								) }
								<div>
									{ author.isSelf && <span className="nros-perf-card__badge">{ i18n.your_perf }</span> }
									<strong>{ author.name }</strong>
									{ author.role && <span className="nros-perf-card__role">{ author.role }</span> }
								</div>
							</div>
							<div className="nros-perf-card__metrics">
								<div className="nros-perf-metric">
									<span className="nros-perf-metric__label">{ i18n.posts }</span>
									<span className="nros-perf-metric__val">{ author.posts }</span>
								</div>
								<div className="nros-perf-metric">
									<span className="nros-perf-metric__label">{ i18n.focus }</span>
									<span className="nros-perf-metric__val">{ author.focus }%</span>
									<ProgressBar value={ author.focus } tone="green" />
								</div>
								<div className="nros-perf-metric">
									<span className="nros-perf-metric__label">{ i18n.discover }</span>
									<span className="nros-perf-metric__val">{ author.discover }%</span>
									<ProgressBar value={ author.discover } tone="purple" />
								</div>
								<div className="nros-perf-metric">
									<span className="nros-perf-metric__label">{ i18n.clicks }</span>
									<span className="nros-perf-metric__val">{ formatK( author.clicks ) }</span>
								</div>
							</div>
							<button
								type="button"
								className="nros-perf-card__toggle"
								onClick={ () => setOpenId( openId === author.userId ? null : author.userId ) }
								aria-expanded={ openId === author.userId }
							>
								{ i18n.details }
							</button>
						</div>
						{ openId === author.userId && (
							<AuthorExpandPanel
								userId={ author.userId }
								days={ days }
								perfNonce={ payload.perfNonce }
								i18n={ i18n }
							/>
						) }
					</article>
				) ) }
			</div>
		</div>
	);
}

function formatK( n ) {
	const v = Number( n ) || 0;
	if ( v >= 1000 ) {
		return `${ ( v / 1000 ).toFixed( 1 ) }k`;
	}
	return String( v );
}
