import { useEffect, useState } from '@wordpress/element';
import { runLegacyAjax } from '../api';

export function TrendRadar( { geo, choices, i18n } ) {
	const [ tab, setTab ] = useState( 'trends' );
	const [ currentGeo, setCurrentGeo ] = useState( geo || 'US' );
	const [ items, setItems ] = useState( [] );
	const [ loading, setLoading ] = useState( true );
	const [ error, setError ] = useState( '' );

	useEffect( () => {
		let cancelled = false;
		const load = async () => {
			setLoading( true );
			setError( '' );
			try {
				const action = tab === 'news' ? 'newsai_dashboard_radar_news' : 'newsai_dashboard_radar_trends';
				const res = await runLegacyAjax( action, { geo: currentGeo } );
				if ( ! cancelled ) {
					setItems( res?.items || [] );
				}
			} catch ( e ) {
				if ( ! cancelled ) {
					setError( e?.message || '' );
					setItems( [] );
				}
			} finally {
				if ( ! cancelled ) {
					setLoading( false );
				}
			}
		};
		load();
		return () => { cancelled = true; };
	}, [ tab, currentGeo ] );

	const geoKeys = Object.keys( choices || {} ).filter( ( k ) => k !== '_default' );

	return (
		<div className="nros-radar nros-bento-card">
			<div className="nros-radar__head">
				<h3>{ i18n.trend_radar || 'Trend radar' }</h3>
				{ geoKeys.length > 0 && (
					<select
						className="nros-radar__geo"
						value={ currentGeo }
						onChange={ ( e ) => setCurrentGeo( e.target.value ) }
					>
						{ geoKeys.map( ( code ) => (
							<option key={ code } value={ code }>{ code }</option>
						) ) }
					</select>
				) }
			</div>
			<div className="nros-radar__tabs">
				<button type="button" className={ tab === 'trends' ? 'is-active' : '' } onClick={ () => setTab( 'trends' ) }>
					{ i18n.trends_tab || 'Trends' }
				</button>
				<button type="button" className={ tab === 'news' ? 'is-active' : '' } onClick={ () => setTab( 'news' ) }>
					{ i18n.news_tab || 'News' }
				</button>
			</div>
			<ul className="nros-radar__list">
				{ loading && <li className="nros-radar__idle">{ i18n.loading || 'Loading…' }</li> }
				{ ! loading && error && <li className="nros-radar__error">{ error }</li> }
				{ ! loading && ! error && items.length === 0 && (
					<li className="nros-radar__idle">{ i18n.no_articles || 'No items' }</li>
				) }
				{ ! loading && items.map( ( item, i ) => (
					<li key={ i } className="nros-radar__item">
						<a href={ item.url } target="_blank" rel="noreferrer">{ item.title }</a>
						{ item.pct > 0 && <span className="nros-radar__pct">+{ item.pct }%</span> }
						{ item.traffic && <span className="nros-radar__traffic">{ item.traffic }</span> }
					</li>
				) ) }
			</ul>
		</div>
	);
}
