import { useCallback, useEffect, useState } from '@wordpress/element';
import { Area, AreaChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
import { loadInsightsPayload, markReactAdminReady, runChiefBrief } from './api';
import { ChannelBreakdown } from './components/ChannelBreakdown';
import { DeviceDonut } from './components/DeviceDonut';
import { KpiSparkCard } from './components/KpiSparkCard';
import { LoadingState } from './components/LoadingState';

function pctChange( current, prev ) {
	if ( ! prev ) {
		return current > 0 ? '+100%' : '0%';
	}
	const p = Math.round( ( ( current - prev ) / prev ) * 100 );
	return `${ p >= 0 ? '+' : '' }${ p }%`;
}

export default function InsightsApp() {
	const [ payload, setPayload ] = useState( null );
	const [ loading, setLoading ] = useState( true );
	const [ days, setDays ] = useState( 30 );
	const [ briefMode, setBriefMode ] = useState( 'morning' );
	const [ briefHtml, setBriefHtml ] = useState( '' );
	const [ briefBusy, setBriefBusy ] = useState( false );
	const [ error, setError ] = useState( '' );

	const load = useCallback( async ( d ) => {
		setLoading( true );
		setError( '' );
		try {
			const data = await loadInsightsPayload( 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 || {};
	if ( loading && ! payload ) {
		return <LoadingState label={ i18n.loading || 'Loading…' } />;
	}
	if ( ! payload ) {
		return (
			<div className="nros-page nros-page--insights">
				<div className="nros-page-error">
					<h2>{ i18n.error || 'Chief Insights could not load.' }</h2>
					{ error && <p><code>{ error }</code></p> }
					<button type="button" className="button button-primary" onClick={ () => load( days ) }>Retry</button>
				</div>
			</div>
		);
	}

	const kpis = payload.kpis || {};
	const chartData = buildChartData( payload.series );

	const onExport = () => window.print();
	const onBrief = async () => {
		setBriefBusy( true );
		try {
			const html = await runChiefBrief( days, briefMode );
			setBriefHtml( html );
		} catch ( e ) {
			setBriefHtml( `<p class="nros-form-error">${ e?.message || i18n.brief_error }</p>` );
		} finally {
			setBriefBusy( false );
		}
	};

	return (
		<div className="nros-page nros-page--insights nros-insights-print" id="nros-insights-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">
					<select className="nros-days-select" value={ days } onChange={ ( e ) => setDays( Number( e.target.value ) ) }>
						<option value={ 7 }>7d</option>
						<option value={ 30 }>30d</option>
						<option value={ 90 }>90d</option>
					</select>
					{ payload.canExport && (
						<button type="button" className="button" onClick={ onExport }>{ i18n.export_pdf }</button>
					) }
					{ payload.aiBriefReady && (
						<>
							<select value={ briefMode } onChange={ ( e ) => setBriefMode( e.target.value ) } className="nros-brief-mode">
								<option value="morning">{ i18n.morning }</option>
								<option value="evening">{ i18n.evening }</option>
							</select>
							<button type="button" className="button button-primary" disabled={ briefBusy } onClick={ onBrief }>
								{ briefBusy ? i18n.brief_loading : i18n.ai_brief }
							</button>
						</>
					) }
					{ payload.isDemo && <span className="nros-demo-pill">{ i18n.pro_demo }</span> }
				</div>
			</header>

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

			<div className="nros-kpi-row nros-kpi-row--bento">
				<KpiSparkCard
					label={ i18n.total_clicks }
					value={ formatK( kpis.totalClicks ) }
					badge={ typeof kpis.prevClicks === 'number' ? pctChange( kpis.totalClicks, kpis.prevClicks ) : null }
					badgeTone={ kpis.totalClicks >= ( kpis.prevClicks || 0 ) ? 'good' : 'warn' }
				/>
				<KpiSparkCard label={ i18n.published } value={ kpis.published ?? 0 } />
				<KpiSparkCard label={ i18n.avg_focus } value={ `${ kpis.avgFocus ?? 0 }%` } />
				<KpiSparkCard label={ i18n.avg_discover } value={ `${ kpis.avgDiscover ?? 0 }%` } />
			</div>

			<div className="nros-bento nros-bento--insights">
				<section className="nros-bento-card nros-bento-card--wide">
					<h3>{ i18n.search_perf }</h3>
					{ chartData.length === 0 ? (
						<div className="nros-chart-empty">{ i18n.no_gsc || 'No Google Search Console data for this period yet.' }</div>
					) : (
					<div className="nros-area-chart">
						<ResponsiveContainer width="100%" height={ 280 }>
							<AreaChart data={ chartData }>
								<defs>
									<linearGradient id="gWeb" x1="0" y1="0" x2="0" y2="1">
										<stop offset="0%" stopColor="#6366f1" stopOpacity={ 0.4 } />
										<stop offset="100%" stopColor="#6366f1" stopOpacity={ 0 } />
									</linearGradient>
									<linearGradient id="gDisc" x1="0" y1="0" x2="0" y2="1">
										<stop offset="0%" stopColor="#ec4899" stopOpacity={ 0.35 } />
										<stop offset="100%" stopColor="#ec4899" stopOpacity={ 0 } />
									</linearGradient>
								</defs>
								<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
								<XAxis dataKey="label" tick={ { fontSize: 11 } } />
								<YAxis tick={ { fontSize: 11 } } />
								<Tooltip contentStyle={ { borderRadius: 12, boxShadow: '0 8px 24px rgba(15,23,42,.12)' } } />
								<Area type="monotone" dataKey="web" stroke="#6366f1" fill="url(#gWeb)" name={ i18n.channel_web } />
								<Area type="monotone" dataKey="discover" stroke="#ec4899" fill="url(#gDisc)" name={ i18n.channel_discover } />
								<Area type="monotone" dataKey="news" stroke="#f97316" fill="transparent" name={ i18n.channel_news } />
							</AreaChart>
						</ResponsiveContainer>
					</div>
					) }
				</section>

				<section className="nros-bento-card">
					<h3>{ i18n.winning }</h3>
					<ul className="nros-movers">
						{ ( payload.winning || [] ).map( ( p, i ) => (
							<li key={ i }>
								<span>{ p.title }</span>
								<span className="nros-movers__stat is-good">+{ p.delta || 0 }</span>
							</li>
						) ) }
					</ul>
				</section>

				<section className="nros-bento-card">
					<h3>{ i18n.losing }</h3>
					<ul className="nros-movers">
						{ ( payload.losing || [] ).map( ( p, i ) => (
							<li key={ i }>
								<span>{ p.title }</span>
								<span className="nros-movers__stat is-bad">{ p.delta || 0 }</span>
							</li>
						) ) }
					</ul>
				</section>

				<DeviceDonut
					initial={ payload.deviceBreakdown }
					channels={ payload.deviceChannels }
					days={ days }
					i18n={ i18n }
				/>

				<ChannelBreakdown bars={ payload.channelBars } i18n={ i18n } />
			</div>
		</div>
	);
}

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

function buildChartData( series ) {
	const s = series || {};
	const labels = s.labels || [];
	if ( ! labels.length ) {
		return [];
	}
	return labels.map( ( label, i ) => ( {
		label: String( label ).slice( 5 ),
		web: Number( Array.isArray( s.web ) ? s.web[ i ] : 0 ),
		discover: Number( Array.isArray( s.discover ) ? s.discover[ i ] : 0 ),
		news: Number( Array.isArray( s.googleNews ) ? s.googleNews[ i ] : 0 ),
	} ) );
}
