import { useCallback, useEffect, useState } from '@wordpress/element';

import { loadDashboardPayload, markReactAdminReady } from './api';

import { CompetitorWatch } from './components/CompetitorWatch';

import { KanbanBoard } from './components/KanbanBoard';

import { KpiSparkCard } from './components/KpiSparkCard';

import { LoadingState } from './components/LoadingState';

import { TaskTable } from './components/TaskTable';

import { TrendRadar } from './components/TrendRadar';
import { TaskForm } from './components/TaskForm';



export default function DashboardApp() {

	const [ payload, setPayload ] = useState( null );

	const [ loading, setLoading ] = useState( true );

	const [ filter, setFilter ] = useState( 'all' );

	const [ view, setView ] = useState( 'kanban' );

	const [ tasks, setTasks ] = useState( [] );

	const [ taskFormOpen, setTaskFormOpen ] = useState( false );

	const [ editingTask, setEditingTask ] = useState( null );

	const [ error, setError ] = useState( '' );



	const load = useCallback( async () => {

		setLoading( true );

		setError( '' );

		try {

			const data = await loadDashboardPayload();

			setPayload( data );

			setTasks( data.tasks || [] );

		} catch ( e ) {

			setError( e && e.message ? String( e.message ) : 'load_failed' );

		} finally {

			markReactAdminReady();

			setLoading( false );

		}

	}, [] );



	useEffect( () => {

		load();

	}, [ load ] );



	const onKanbanMoved = ( taskId, column ) => {

		setTasks( ( prev ) => prev.map( ( t ) => (

			t.id === taskId ? { ...t, kanbanColumn: column, statusKey: column } : t

		) ) );

	};



	const i18n = payload?.i18n || {};

	const kpis = payload?.kpis || {};

	const sparks = payload?.sparklines || {};

	const caps = payload?.capabilities || {};



	if ( loading ) {

		return <LoadingState label={ i18n.loading || 'Loading dashboard…' } />;

	}



	if ( ! payload ) {

		return (
			<div className="nros-page nros-page--dash">
				<div className="nros-page-error">
					<h2>{ i18n.error || 'Dashboard could not load.' }</h2>
					{ error && <p><code>{ error }</code></p> }
					<button type="button" className="button button-primary" onClick={ load }>Retry</button>
				</div>
			</div>
		);

	}



	const weekBadge = `${ kpis.weekTrendUp ? '+' : '-' }${ Math.abs( kpis.weekTrend ) }%`;



	return (

		<div className="nros-page nros-page--dash">

			<header className="nros-page__head nros-page__head--dash">

				<div>

					<h1 className="nros-page__title">Dashboard</h1>

					<p className="nros-page__sub">{ i18n.welcome }</p>

				</div>

				<button
					type="button"
					className="button button-primary nros-new-task-btn"
					onClick={ () => { setEditingTask( null ); setTaskFormOpen( true ); } }
				>

					{ i18n.new_task || i18n.add_task }

				</button>

			</header>



			<div className="nros-kpi-row nros-kpi-row--bento">

				<KpiSparkCard

					label={ i18n.active_tasks }

					value={ kpis.activeTasks }

					sub={ sprintf( i18n.overdue_today, kpis.overdue, kpis.dueToday ) }

					spark={ sparks.activeTasks }

					sparkColor="#6366f1"

					badge={ weekBadge }

					badgeTone={ kpis.weekTrendUp ? 'good' : 'bad' }

				/>

				<KpiSparkCard

					label={ i18n.articles_week }

					value={ kpis.postsThisWeek }

					sub={ sprintf( i18n.vs_last_week, kpis.weekTrendUp ? '↑' : '↓', Math.abs( kpis.weekTrend ) ) }

					spark={ sparks.articles }

					sparkColor="#22c55e"

					badge={ weekBadge }

					badgeTone={ kpis.weekTrendUp ? 'good' : 'bad' }

				/>

				<KpiSparkCard

					label={ i18n.seo_issues }

					value={ kpis.missingSeo }

					sub={ kpis.missingSeo > 0 ? i18n.needs_action : i18n.all_clear }

					href={ kpis.seoIssuesUrl }

					spark={ sparks.seoIssues }

					sparkColor="#f97316"

					badge={ kpis.missingSeo > 0 ? `-${ kpis.missingSeo }` : '0' }

					badgeTone={ kpis.missingSeo > 0 ? 'bad' : 'good' }

				/>

				<KpiSparkCard

					label={ i18n.desk_readiness || i18n.seo_health }

					value={ kpis.deskReadiness ?? kpis.seoHealth ?? 0 }

					unit={ ( kpis.deskReadiness ?? kpis.seoHealth ) > 0 ? '%' : '' }

					sub={ kpis.readinessSample > 0
						? ( i18n.readiness_sample || i18n.based_30d ).replace( '%d', String( kpis.readinessSample ) )
						: i18n.no_scores_yet || i18n.based_30d }

					spark={ sparks.readiness || sparks.seoHealth }

					sparkColor="#8b5cf6"

					badge={ kpis.readinessLow > 0 ? `${ kpis.readinessLow } low` : ( ( kpis.deskReadiness ?? kpis.seoHealth ) > 0 ? i18n.all_clear : '' ) }

					badgeTone={ kpis.readinessLow > 0 ? 'bad' : 'good' }

				/>

			</div>



			<div className="nros-bento nros-bento--dash">

				<section className="nros-bento-card nros-bento-card--workflow">

					<div className="nros-workflow__head">

						<div>

							<h3>{ i18n.workflow }</h3>

							<p>{ i18n.workflow_sub }</p>

						</div>

						<div className="nros-workflow__controls">

							{ [
								[ 'all', i18n.chip_all ],
								[ 'overdue', i18n.chip_overdue ],
								[ 'today', i18n.chip_today ],
							].map( ( [ id, label ] ) => (

								<button

									key={ id }

									type="button"

									className={ `nros-workflow__chip${ filter === id ? ' is-active' : '' }` }

									onClick={ () => setFilter( id ) }

								>

									{ label }

								</button>

							) ) }

							<div className="nros-view-toggle">

								<button type="button" className={ view === 'table' ? 'is-active' : '' } onClick={ () => setView( 'table' ) }>{ i18n.view_table }</button>

								<button type="button" className={ view === 'kanban' ? 'is-active' : '' } onClick={ () => setView( 'kanban' ) }>{ i18n.view_kanban }</button>

							</div>

						</div>

					</div>

					{ view === 'kanban' ? (

						<KanbanBoard tasks={ tasks } i18n={ i18n } onMoved={ onKanbanMoved } />

					) : (

						<TaskTable
							tasks={ tasks }
							filter={ filter }
							i18n={ i18n }
							caps={ caps }
							onEdit={ ( t ) => { setEditingTask( t ); setTaskFormOpen( true ); } }
						/>

					) }

				</section>



				<aside className="nros-bento-side">

					<TrendRadar geo={ payload.radar?.geo } choices={ payload.radar?.choices } i18n={ i18n } />

					<CompetitorWatch competitor={ payload.competitor } i18n={ i18n } />

				</aside>



				<section className="nros-bento-card nros-bento-card--posts">

					<div className="nros-bento-card__head">

						<h3>{ i18n.latest_posts }</h3>

						<a href={ payload.urls?.posts } className="button button-small">{ i18n.view_all }</a>

					</div>

					<ul className="nros-latest-posts">

						{ ( payload.latestPosts || [] ).map( ( p ) => (

							<li key={ p.id } className="nros-latest-posts__item">

								<div className="nros-latest-posts__thumb" aria-hidden="true" />

								<div className="nros-latest-posts__body">

									<a href={ p.editUrl } className="nros-latest-posts__title">{ p.title }</a>

									<div className="nros-latest-posts__meta">👤 { p.author } · 🕒 { p.ago }</div>

								</div>

								<span className="nros-latest-posts__badge">{ i18n.published_badge }</span>

							</li>

						) ) }

					</ul>

				</section>

			</div>

			<TaskForm
				open={ taskFormOpen }
				task={ editingTask }
				authors={ payload.authors }
				i18n={ i18n }
				taskNonce={ payload.taskNonce }
				onClose={ () => { setTaskFormOpen( false ); setEditingTask( null ); } }
				onSaved={ ( nextTasks ) => setTasks( nextTasks ) }
			/>

		</div>
	);
}



function sprintf( template, ...args ) {

	if ( ! template ) {

		return '';

	}

	let i = 0;

	return String( template ).replace( /%(\d+)\$[ds]/g, () => {

		const val = args[ i ];

		i += 1;

		return val != null ? String( val ) : '';

	} );

}


