import { useRef, useState } from '@wordpress/element';
import { __, _n, sprintf } from '@wordpress/i18n';
import { useNavigate } from 'react-router-dom';
import { Card, EmptyState, ErrorBox, Loading, settingsPath, useReport } from './common';
import PageHeader from './ui/PageHeader';
import { SkeletonKpis, SkeletonRegion, SkeletonTable } from './ui/Skeleton';
import { COLOR, COLOR_PREV, Sparkline } from './charts';
import { fetchForecastBacktest, fetchForecastSku, fetchForecastTop } from './api_expansion';
import { compact, downloadCsv, forecastStyleName, niceDate, num, pct } from './format';

const TEXT_DOMAIN = 'stock-sync-with-google-sheet-for-woocommerce';

export const HORIZONS = [ 7, 14, 30, 60, 90 ];

/** Forecast accuracy from MAPE (mean absolute % error): 100 − MAPE, never below 0. */
export const accuracyOf = ( mape ) => ( mape === null || mape === undefined ? null : Math.max( 0, 100 - Number( mape ) ) );

/** Stock-out cell: date + days, or why there is none. */
export function StockoutCell( { row, horizon } ) {
	if ( row.stock === null || row.stock === undefined ) {
		return <span className="ssgsw-badge ssgsw-badge--muted">{ __( 'Stock not tracked', TEXT_DOMAIN ) }</span>;
	}
	if ( row.days_to_stockout === 0 ) {
		return <span className="ssgsw-badge ssgsw-badge--bad">{ __( 'Out of stock now', TEXT_DOMAIN ) }</span>;
	}
	if ( row.days_to_stockout === null || row.days_to_stockout === undefined ) {
		/* translators: %d: forecast horizon in days */
		return <span className="ssgsw-badge ssgsw-badge--ok">{ sprintf( __( 'Not within %d days', TEXT_DOMAIN ), horizon ) }</span>;
	}
	const tone = row.days_to_stockout <= 7 ? 'bad' : row.days_to_stockout <= 14 ? 'warn' : 'info';
	return (
		<span className="ssgsw-fc-out">
			<span className={ `ssgsw-badge ssgsw-badge--${ tone }` }>{ niceDate( row.stockout_date ) }</span>
			{ /* translators: %d: days until the SKU runs out */ }
			<small>{ sprintf( _n( 'in %d day', 'in %d days', Number( row.days_to_stockout ) || 0, TEXT_DOMAIN ), row.days_to_stockout ) }</small>
		</span>
	);
}

/**
 * History + forecast + 80% band in inline SVG (same look as LineChart). Hover / arrow keys show a tooltip.
 * history: [ { date, units } ], points: [ { date, units, low, high } ].
 */
export function ForecastChart( { history, points, stockoutDate, height = 260 } ) {
	const [ hover, setHover ] = useState( -1 );
	const ref = useRef( null );
	const W = 720;
	const H = height;
	const pad = { l: 46, r: 12, t: 14, b: 26 };
	const rows = [
		...history.map( ( h ) => ( { date: h.date, actual: Number( h.units ) || 0 } ) ),
		...points.map( ( p ) => ( { date: p.date, forecast: Number( p.units ) || 0, low: Number( p.low ) || 0, high: Number( p.high ) || 0 } ) ),
	];
	const n = rows.length;
	const split = history.length; // first forecast index
	const max = Math.max( 1, ...rows.map( ( r ) => Math.max( r.actual || 0, r.high || 0, r.forecast || 0 ) ) );
	const niceMax = ( () => {
		const p = Math.pow( 10, Math.floor( Math.log10( max ) ) );
		const f = max / p;
		return ( f <= 1 ? 1 : f <= 2 ? 2 : f <= 5 ? 5 : 10 ) * p;
	} )();
	const iw = W - pad.l - pad.r;
	const ih = H - pad.t - pad.b;
	const x = ( i ) => pad.l + ( n <= 1 ? iw / 2 : ( i * iw ) / ( n - 1 ) );
	const y = ( v ) => pad.t + ih - ( v / niceMax ) * ih;
	const ticks = [ 0, 0.25, 0.5, 0.75, 1 ].map( ( f ) => f * niceMax );
	const step = Math.max( 1, Math.ceil( n / 7 ) );

	const line = ( from, to, key ) => rows.slice( from, to ).map( ( r, k ) => `${ k ? 'L' : 'M' }${ x( from + k ).toFixed( 1 ) },${ y( r[ key ] ).toFixed( 1 ) }` ).join( ' ' );
	const actualPath = split ? line( 0, split, 'actual' ) : '';
	// The forecast line starts at the last actual day so the two lines join.
	const fcRows = rows.slice( split );
	const joinAt = split > 0 ? `M${ x( split - 1 ).toFixed( 1 ) },${ y( rows[ split - 1 ].actual ).toFixed( 1 ) } ` : '';
	const fcPath = fcRows.length ? joinAt + fcRows.map( ( r, k ) => `${ joinAt || k ? 'L' : 'M' }${ x( split + k ).toFixed( 1 ) },${ y( r.forecast ).toFixed( 1 ) }` ).join( ' ' ) : '';
	const band = fcRows.length
		? `${ fcRows.map( ( r, k ) => `${ k ? 'L' : 'M' }${ x( split + k ).toFixed( 1 ) },${ y( r.high ).toFixed( 1 ) }` ).join( ' ' ) } ${ fcRows.slice().reverse().map( ( r, k ) => `L${ x( split + fcRows.length - 1 - k ).toFixed( 1 ) },${ y( r.low ).toFixed( 1 ) }` ).join( ' ' ) } Z`
		: '';
	const outIdx = stockoutDate ? rows.findIndex( ( r ) => r.date === stockoutDate ) : -1;

	const onMove = ( e ) => {
		const box = ref.current && ref.current.getBoundingClientRect();
		if ( ! box || ! n ) {
			return;
		}
		const ratio = ( ( e.clientX - box.left ) / box.width ) * W;
		setHover( Math.max( 0, Math.min( n - 1, Math.round( ( ( ratio - pad.l ) / iw ) * ( n - 1 ) ) ) ) );
	};
	const tip = hover >= 0 ? rows[ hover ] : null;
	const summary = sprintf(
		/* translators: 1: days of history, 2: forecast days */
		__( 'Units per day: %1$d days of actual sales, then a %2$d-day forecast with an 80%% likely range.', TEXT_DOMAIN ),
		split,
		fcRows.length
	);

	return (
		<div className="ssgsw-chart" onMouseLeave={ () => setHover( -1 ) }>
			<svg
				ref={ ref }
				className="ssgsw-chart__svg"
				viewBox={ `0 0 ${ W } ${ H }` }
				role="img"
				aria-label={ summary }
				tabIndex={ 0 }
				onMouseMove={ onMove }
				onFocus={ () => setHover( split ) }
				onBlur={ () => setHover( -1 ) }
				onKeyDown={ ( e ) => {
					if ( e.key === 'ArrowRight' ) {
						setHover( ( h ) => Math.min( n - 1, h + 1 ) );
					} else if ( e.key === 'ArrowLeft' ) {
						setHover( ( h ) => Math.max( 0, h - 1 ) );
					}
				} }
			>
				{ ticks.map( ( t ) => (
					<g key={ t }>
						<line x1={ pad.l } x2={ W - pad.r } y1={ y( t ) } y2={ y( t ) } className="ssgsw-chart__grid" />
						<text x={ pad.l - 6 } y={ y( t ) + 4 } textAnchor="end" className="ssgsw-chart__tick">{ compact( t ) }</text>
					</g>
				) ) }
				{ rows.map( ( r, i ) => ( i % step === 0 ? (
					<text key={ r.date } x={ x( i ) } y={ H - 6 } textAnchor="middle" className="ssgsw-chart__tick">{ niceDate( r.date, false ) }</text>
				) : null ) ) }
				{ band && <path d={ band } fill={ COLOR } opacity="0.12" /> }
				{ split > 0 && fcRows.length > 0 && (
					<g>
						<line x1={ x( split - 1 ) } x2={ x( split - 1 ) } y1={ pad.t } y2={ pad.t + ih } className="ssgsw-chart__cursor" strokeDasharray="2 3" />
						<text x={ x( split - 1 ) + 4 } y={ pad.t + 10 } className="ssgsw-chart__tick">{ __( 'Forecast →', TEXT_DOMAIN ) }</text>
					</g>
				) }
				{ actualPath && <path d={ actualPath } fill="none" stroke={ COLOR_PREV } strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" /> }
				{ fcPath && <path d={ fcPath } fill="none" stroke={ COLOR } strokeWidth="2" strokeDasharray="5 4" strokeLinejoin="round" strokeLinecap="round" /> }
				{ outIdx >= 0 && (
					<g>
						<line x1={ x( outIdx ) } x2={ x( outIdx ) } y1={ pad.t } y2={ pad.t + ih } stroke="#d63638" strokeWidth="1.5" />
						<text x={ x( outIdx ) - 4 } y={ pad.t + 24 } textAnchor="end" className="ssgsw-chart__tick ssgsw-fc-outlabel">{ __( 'Runs out', TEXT_DOMAIN ) }</text>
					</g>
				) }
				{ hover >= 0 && <line x1={ x( hover ) } x2={ x( hover ) } y1={ pad.t } y2={ pad.t + ih } className="ssgsw-chart__cursor" /> }
			</svg>
			{ tip && (
				<div className="ssgsw-chart__tip" style={ { left: `${ ( x( hover ) / W ) * 100 }%` } } role="status">
					<strong>{ niceDate( tip.date ) }</strong>
					{ tip.actual !== undefined ? (
						<span><i style={ { background: COLOR_PREV } } aria-hidden="true"></i>{ sprintf( __( 'Sold: %s', TEXT_DOMAIN ), num( tip.actual, 1 ) ) }</span>
					) : (
						<>
							<span><i style={ { background: COLOR } } aria-hidden="true"></i>{ sprintf( __( 'Forecast: %s', TEXT_DOMAIN ), num( tip.forecast, 1 ) ) }</span>
							<span>{ sprintf( __( 'Likely %1$s – %2$s', TEXT_DOMAIN ), num( tip.low, 1 ), num( tip.high, 1 ) ) }</span>
						</>
					) }
				</div>
			) }
			<div className="ssgsw-chart__legend">
				<span><i style={ { background: COLOR_PREV } } aria-hidden="true"></i>{ __( 'Actual units', TEXT_DOMAIN ) }</span>
				<span><i style={ { background: COLOR } } aria-hidden="true"></i>{ __( 'Forecast', TEXT_DOMAIN ) }</span>
				<span><i style={ { background: COLOR, opacity: 0.25 } } aria-hidden="true"></i>{ __( 'Likely range (80%)', TEXT_DOMAIN ) }</span>
			</div>
		</div>
	);
}

/** Horizon picker (7 / 14 / 30 / 60 / 90 days). */
export function HorizonBar( { value, onChange, children } ) {
	return (
		<div className="ssgsw-an-toolbar">
			<div className="ssgsw-an-seg" role="group" aria-label={ __( 'Forecast horizon', TEXT_DOMAIN ) }>
				{ HORIZONS.map( ( d ) => (
					<button key={ d } type="button" aria-pressed={ value === d } className={ value === d ? 'is-active' : '' } onClick={ () => onChange( d ) }>
						{ sprintf( __( '%d days', TEXT_DOMAIN ), d ) }
					</button>
				) ) }
			</div>
			{ children }
		</div>
	);
}

/** Forecast table (also used by the locked preview with sample rows). */
export function ForecastTable( { items, horizon, selected, onSelect } ) {
	return (
		<div className="ssgsw-table-wrap">
			<table className="ssgsw-table">
				<thead>
					<tr>
						<th>{ __( 'SKU', TEXT_DOMAIN ) }</th>
						<th>{ __( 'Product', TEXT_DOMAIN ) }</th>
						<th className="is-num">{ __( 'Stock', TEXT_DOMAIN ) }</th>
						<th className="is-num">{ __( 'Sold / day (28 d)', TEXT_DOMAIN ) }</th>
						<th className="is-num">{ __( 'Next 7 days', TEXT_DOMAIN ) }</th>
						<th className="is-num">{ sprintf( __( 'Next %d days', TEXT_DOMAIN ), horizon ) }</th>
						<th>{ __( 'Trend', TEXT_DOMAIN ) }</th>
						<th>{ __( 'Stock-out date', TEXT_DOMAIN ) }</th>
					</tr>
				</thead>
				<tbody>
					{ items.map( ( r ) => (
						<tr
							key={ r.sku }
							className={ selected === r.sku ? 'is-selected' : '' }
							onClick={ () => onSelect && onSelect( r.sku ) }
						>
							<td>
								<button type="button" className="ssgsw-link" onClick={ ( e ) => { e.stopPropagation(); if ( onSelect ) { onSelect( r.sku ); } } } aria-expanded={ selected === r.sku }>
									{ r.sku }
								</button>
							</td>
							<td className="ssgsw-table__product"><span title={ r.product }>{ r.product }</span></td>
							<td className="is-num">{ r.stock === null || r.stock === undefined ? '–' : num( r.stock ) }</td>
							<td className="is-num">{ num( r.avg_daily_28, 2 ) }</td>
							<td className="is-num">{ num( r.forecast_7, 1 ) }</td>
							<td className="is-num"><strong>{ num( r.forecast_total, 1 ) }</strong></td>
							<td>{ Array.isArray( r.daily ) && r.daily.length ? <Sparkline values={ r.daily.slice( 0, 30 ) } ariaLabel={ sprintf( __( 'Forecast units per day for %s', TEXT_DOMAIN ), r.sku ) } /> : '–' }</td>
							<td><StockoutCell row={ r } horizon={ horizon } /></td>
						</tr>
					) ) }
				</tbody>
			</table>
		</div>
	);
}

/** One SKU's forecast card: chart + facts. */
function SkuForecast( { sku, horizon, onClose } ) {
	const { data, loading, error, reload } = useReport( () => fetchForecastSku( sku, horizon ), [ sku, horizon ] );
	const f = data && data.forecast;
	const acc = f && f.backtest ? accuracyOf( f.backtest.mape ) : null;
	return (
		<Card
			title={ sprintf( __( 'Forecast for %s', TEXT_DOMAIN ), sku ) }
			actions={ <button type="button" className="ssgsw-link" onClick={ onClose }>{ __( 'Close', TEXT_DOMAIN ) }</button> }
		>
			{ loading && ! f && <Loading /> }
			{ error && <ErrorBox message={ error } onRetry={ reload } /> }
			{ f && (
				<div className={ loading ? 'is-refreshing' : '' }>
					{ f.product && <p className="ssgsw-analytics-muted ssgsw-fc-product">{ f.product }</p> }
					<ForecastChart history={ f.history || [] } points={ f.points || [] } stockoutDate={ f.stockout_date } />
					<ul className="ssgsw-facts ssgsw-fc-facts">
						<li><span>{ __( 'In stock', TEXT_DOMAIN ) }</span><strong>{ f.stock === null || f.stock === undefined ? __( 'Not tracked', TEXT_DOMAIN ) : num( f.stock ) }</strong></li>
						<li><span>{ sprintf( __( 'Forecast, next %d days', TEXT_DOMAIN ), f.horizon ) }</span><strong>{ num( f.forecast_total, 1 ) }</strong></li>
						<li><span>{ __( 'Stock-out date', TEXT_DOMAIN ) }</span><strong><StockoutCell row={ f } horizon={ f.horizon } /></strong></li>
						<li>
							<span>{ __( 'Forecast accuracy', TEXT_DOMAIN ) }</span>
							<strong>{ acc === null ? __( 'Not enough history', TEXT_DOMAIN ) : pct( acc, 0 ) }</strong>
						</li>
					</ul>
					<p className="ssgsw-an-foot">
						{ sprintf(
							/* translators: 1: method name, 2: days of history */
							__( 'Forecast style: %1$s, from %2$d days of sales%3$s. Accuracy is how close the forecast came to the real sales of the last 14 days.', TEXT_DOMAIN ),
							forecastStyleName( f.method ),
							f.history_days,
							f.seasonal ? __( ', adjusted for weekday patterns', TEXT_DOMAIN ) : ''
						) }
					</p>
				</div>
			) }
		</Card>
	);
}

/**
 * Forecast tab: best sellers' demand forecast for the chosen horizon, stock-out dates and accuracy.
 */
export default function Forecast() {
	const navigate = useNavigate();
	const [ horizon, setHorizon ] = useState( null ); // null = the default from Settings
	const [ selected, setSelected ] = useState( '' );
	const [ lookup, setLookup ] = useState( '' );
	const { data, loading, error, reload } = useReport( () => fetchForecastTop( { horizon, limit: 25 } ), [ horizon ] );
	const backtest = useReport( () => fetchForecastBacktest( 20 ), [] );
	const h = horizon || ( data && data.horizon ) || 30;
	const items = ( data && data.items ) || [];

	if ( error && /forecast_disabled|turned off/i.test( `${ error }` ) ) {
		return (
			<div className="ssgsw-an-screen">
				<PageHeader title={ __( 'Forecast', TEXT_DOMAIN ) } description={ __( 'How many units you will sell and when each product runs out.', TEXT_DOMAIN ) } />
				<EmptyState
					title={ __( 'Forecasting is turned off', TEXT_DOMAIN ) }
					action={ <button type="button" className="ssgsw-analytics-btn ssgsw-analytics-btn--primary" onClick={ () => navigate( settingsPath() ) }>{ __( 'Turn it on in settings', TEXT_DOMAIN ) }</button> }
				>
					{ __( 'Turn on Forecasting to see how many units each product will sell and when it will run out.', TEXT_DOMAIN ) }
				</EmptyState>
			</div>
		);
	}

	const bt = backtest.data;
	const acc = bt ? accuracyOf( bt.mape ) : null;
	const outSoon = items.filter( ( r ) => r.days_to_stockout !== null && r.days_to_stockout !== undefined && r.days_to_stockout <= h ).length;
	const totalUnits = items.reduce( ( s, r ) => s + ( Number( r.forecast_total ) || 0 ), 0 );

	const exportCsv = () => downloadCsv(
		`flexstock-forecast-${ h }-days.csv`,
		[ 'SKU', 'Product', 'Stock', 'Sold per day (28 days)', 'Forecast next 7 days', `Forecast next ${ h } days`, 'Stock-out date', 'Days to stock-out' ],
		items.map( ( r ) => [ r.sku, r.product, r.stock ?? '', r.avg_daily_28, r.forecast_7, r.forecast_total, r.stockout_date || '', r.days_to_stockout ?? '' ] )
	);

	return (
		<div className="ssgsw-an-screen">
			<PageHeader
				title={ __( 'Forecast', TEXT_DOMAIN ) }
				description={ data ? sprintf( __( 'How many units you will sell in the next %d days, and when each product runs out.', TEXT_DOMAIN ), h ) : __( 'How many units you will sell and when each product runs out.', TEXT_DOMAIN ) }
				onRefresh={ reload }
				refreshing={ loading && !! data }
				actions={ (
					<div className="ssgsw-an-seg" role="group" aria-label={ __( 'Forecast how far ahead', TEXT_DOMAIN ) }>
						{ HORIZONS.map( ( d ) => (
							<button key={ d } type="button" aria-pressed={ h === d } className={ h === d ? 'is-active' : '' } onClick={ () => setHorizon( d ) }>
								{ sprintf( __( '%d days', TEXT_DOMAIN ), d ) }
							</button>
						) ) }
					</div>
				) }
			/>

			<div className="ssgsw-toolbar">
				<form
					className="ssgsw-fc-lookup"
					onSubmit={ ( e ) => {
						e.preventDefault();
						if ( lookup.trim() ) {
							setSelected( lookup.trim() );
						}
					} }
				>
					<label htmlFor="ssgsw-fc-lookup" className="screen-reader-text">{ __( 'Forecast one SKU', TEXT_DOMAIN ) }</label>
					<input id="ssgsw-fc-lookup" type="search" className="ssgsw-analytics-input" placeholder={ __( 'Any SKU…', TEXT_DOMAIN ) } value={ lookup } onChange={ ( e ) => setLookup( e.target.value ) } />
					<button type="submit" className="ssgsw-analytics-btn ssgsw-analytics-btn--secondary" disabled={ ! lookup.trim() }>{ __( 'Forecast', TEXT_DOMAIN ) }</button>
				</form>
			</div>

			{ selected && ! items.some( ( r ) => r.sku === selected ) && <SkuForecast sku={ selected } horizon={ h } onClose={ () => setSelected( '' ) } /> }

			{ loading && ! data && <SkeletonRegion label={ __( 'Calculating forecasts…', TEXT_DOMAIN ) }><SkeletonKpis count={ 4 } /><SkeletonTable rows={ 8 } cols={ 7 } /></SkeletonRegion> }
			{ error && <ErrorBox message={ error } onRetry={ reload } /> }

			{ data && ! items.length && (
				<EmptyState
					title={ __( 'Nothing to forecast yet', TEXT_DOMAIN ) }
					action={ <button type="button" className="ssgsw-analytics-btn ssgsw-analytics-btn--secondary" onClick={ () => navigate( settingsPath() ) }>{ __( 'Add past sales in settings', TEXT_DOMAIN ) }</button> }
				>
					{ __( 'Forecasts need sales in the 28 days up to yesterday. Orders placed today count from tomorrow.', TEXT_DOMAIN ) }
				</EmptyState>
			) }

			{ data && items.length > 0 && (
				<div className={ loading ? 'is-refreshing' : '' }>
					<div className="ssgsw-kpis">
						<div className="ssgsw-kpi">
							<span className="ssgsw-kpi__label">{ sprintf( __( 'Units expected, next %d days', TEXT_DOMAIN ), h ) }</span>
							<strong className="ssgsw-kpi__value">{ num( totalUnits ) }</strong>
							<span className="ssgsw-kpi__meta"><small>{ items.length === 1 ? __( 'Top product', TEXT_DOMAIN ) : sprintf( _n( 'Top %d product', 'Top %d products', items.length, TEXT_DOMAIN ), items.length ) }</small></span>
						</div>
						<div className={ `ssgsw-kpi${ outSoon ? ' ssgsw-kpi--tone-bad' : ' ssgsw-kpi--tone-ok' }` }>
							<span className="ssgsw-kpi__label">{ sprintf( __( 'Run out within %d days', TEXT_DOMAIN ), h ) }</span>
							<strong className="ssgsw-kpi__value">{ num( outSoon ) }</strong>
							<span className="ssgsw-kpi__meta"><small>{ __( 'SKUs at current stock', TEXT_DOMAIN ) }</small></span>
						</div>
						<div className="ssgsw-kpi">
							<span className="ssgsw-kpi__label">{ __( 'Forecast accuracy', TEXT_DOMAIN ) }</span>
							<strong className="ssgsw-kpi__value">{ backtest.loading && ! bt ? '…' : acc === null ? '–' : pct( acc, 0 ) }</strong>
							<span className="ssgsw-kpi__meta">
								<small>
									{ bt && bt.mape !== null && bt.mape !== undefined
										? sprintf( __( 'Average error %1$s on the last %2$d days', TEXT_DOMAIN ), pct( bt.mape, 0 ), bt.holdout )
										: __( 'Needs about 4 weeks of sales history', TEXT_DOMAIN ) }
								</small>
							</span>
						</div>
						<div className="ssgsw-kpi">
							<span className="ssgsw-kpi__label">{ __( 'Forecast style', TEXT_DOMAIN ) }</span>
							<strong className="ssgsw-kpi__value ssgsw-fc-method">{ forecastStyleName( data.method ) }</strong>
							<span className="ssgsw-kpi__meta"><small>{ sprintf( __( 'Reacts to change at %s · set in Settings', TEXT_DOMAIN ), data.alpha ) }</small></span>
						</div>
					</div>

					{ selected && items.some( ( r ) => r.sku === selected ) && <SkuForecast sku={ selected } horizon={ h } onClose={ () => setSelected( '' ) } /> }

					<Card
						title={ __( 'Best sellers, soonest stock-out first', TEXT_DOMAIN ) }
						className="ssgsw-an-card--flush"
						actions={ <button type="button" className="ssgsw-analytics-btn ssgsw-analytics-btn--secondary" onClick={ exportCsv }>{ __( 'Download CSV', TEXT_DOMAIN ) }</button> }
					>
						<ForecastTable items={ items } horizon={ h } selected={ selected } onSelect={ ( sku ) => setSelected( sku === selected ? '' : sku ) } />
						<p className="ssgsw-table-foot">{ __( 'Select a SKU to see its chart with the likely range. Forecasts use counted orders up to yesterday (store time).', TEXT_DOMAIN ) }</p>
					</Card>
				</div>
			) }
		</div>
	);
}
