import { useEffect, useState, useCallback, useRef } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { rangePhrase, niceDate } from './format';
import DateRangeButton from './ui/DateRangeButton';
import { SkeletonRegion, SkeletonCard, SkeletonKpis } from './ui/Skeleton';
import { MAX_RANGE_DAYS, backToToday, rangeDates, rangeKey, rangeParams, shiftToLatest, todayStr } from './ui/rangeUtils';

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

export const DAY_OPTIONS = [ 7, 14, 28, 90 ];

/** In-app routes used by next-step buttons (one place to change if the router changes). */
export const settingsPath = ( page = '' ) => ( page ? `/analytics/settings/${ page }` : '/analytics/settings' );
export const reportPath = ( id ) => `/analytics/${ id }`;

// The range helpers live in ui/rangeUtils.js; re-exported so pages keep importing them from here.
export { MAX_RANGE_DAYS, rangeDates, rangeKey, rangeParams, todayStr };

/** Load a report; re-runs when deps change; ignores stale responses. */
export function useReport( fetcher, deps ) {
	const [ state, setState ] = useState( { data: null, loading: true, error: '' } );
	const [ tick, setTick ] = useState( 0 );
	const seq = useRef( 0 );
	useEffect( () => {
		const id = ++seq.current;
		setState( ( s ) => ( { data: s.data, loading: true, error: '' } ) );
		fetcher()
			.then( ( data ) => id === seq.current && setState( { data, loading: false, error: '' } ) )
			.catch( ( e ) => id === seq.current && setState( { data: null, loading: false, error: e.message || __( 'Something went wrong.', TEXT_DOMAIN ) } ) );
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [ ...deps, tick ] );
	const reload = useCallback( () => setTick( ( t ) => t + 1 ), [] );
	return { ...state, reload };
}

/** Skeleton placeholder (shaped like a KPI row and a card) with a screen-reader "Loading" message. */
export const Loading = ( { label } ) => (
	<SkeletonRegion label={ label }>
		<SkeletonKpis count={ 4 } />
		<SkeletonCard chart height={ 180 } />
	</SkeletonRegion>
);

export const ErrorBox = ( { message, onRetry } ) => (
	<div className="ssgsw-an-state ssgsw-an-state--error" role="alert">
		<strong>{ __( 'We could not load this report.', TEXT_DOMAIN ) }</strong>
		<span>{ message }</span>
		{ onRetry && <button type="button" className="ssgsw-analytics-btn ssgsw-analytics-btn--secondary" onClick={ onRetry }>{ __( 'Try again', TEXT_DOMAIN ) }</button> }
	</div>
);

export const EmptyState = ( { title, children, action } ) => (
	<div className="ssgsw-an-state ssgsw-an-state--empty">
		<span className="dashicons dashicons-chart-area" aria-hidden="true"></span>
		<strong>{ title }</strong>
		{ children && <span>{ children }</span> }
		{ action }
	</div>
);

/**
 * Friendly "no data in this range" state that names the dates and offers the next step:
 * show the period ending on the latest sale, or go back to today.
 */
export const NoSalesState = ( { from, to, range, setRange, latest } ) => {
	const last = latest || ( range && range.latest );
	const canShift = !! ( last && setRange && range && last < to );
	return (
		<EmptyState
			title={ __( 'No sales in this period', TEXT_DOMAIN ) }
			action={ canShift || ( range && range.auto && setRange ) ? (
				<span className="ssgsw-an-state__actions">
					{ canShift && (
						<button type="button" className="ssgsw-analytics-btn ssgsw-analytics-btn--primary" onClick={ () => setRange( shiftToLatest( { ...range, latest: last } ) ) }>
							{ __( 'Show my latest sales', TEXT_DOMAIN ) }
						</button>
					) }
					{ range.auto && (
						<button type="button" className="ssgsw-analytics-btn ssgsw-analytics-btn--secondary" onClick={ () => setRange( backToToday( range ) ) }>
							{ __( 'Back to today', TEXT_DOMAIN ) }
						</button>
					) }
				</span>
			) : null }
		>
			{ sprintf(
				/* translators: 1: date range */
				__( 'There are no counted orders %1$s.', TEXT_DOMAIN ),
				rangePhrase( from, to )
			) }
			{ last ? ` ${ sprintf( __( 'The latest sale was on %s.', TEXT_DOMAIN ), niceDate( last ) ) }` : '' }
		</EmptyState>
	);
};

/**
 * Compatibility wrapper: pages now render their own PageHeader, but anything still using RangeBar gets the
 * same date and compare dropdowns (plus any children) in a toolbar.
 */
export function RangeBar( { range, onChange, timezone, children } ) {
	return (
		<div className="ssgsw-an-toolbar">
			<DateRangeButton range={ range } onChange={ onChange } timezone={ timezone } />
			{ children }
		</div>
	);
}

/** "vs previous period" / "vs same period last year" text for KPI tiles; '' when comparison is off. */
export const compareText = ( range ) => {
	const c = ( range && range.compare ) || 'previous';
	return c === 'none' ? '' : c === 'last_year' ? __( 'vs same period last year', TEXT_DOMAIN ) : __( 'vs previous period', TEXT_DOMAIN );
};

/** ▲ / ▼ percent change. `invert` when an increase is bad (refunds). */
export function Delta( { value, invert = false } ) {
	if ( value === null || value === undefined ) {
		return <span className="ssgsw-delta is-flat" aria-label={ __( 'No previous data to compare', TEXT_DOMAIN ) }>–</span>;
	}
	const up = value > 0;
	const flat = value === 0;
	const good = flat ? null : up !== invert;
	const text = `${ Math.abs( value ).toLocaleString( undefined, { maximumFractionDigits: 1 } ) }%`;
	return (
		<span className={ `ssgsw-delta ${ flat ? 'is-flat' : good ? 'is-good' : 'is-bad' }` } aria-label={ `${ up ? __( 'up', TEXT_DOMAIN ) : flat ? __( 'unchanged', TEXT_DOMAIN ) : __( 'down', TEXT_DOMAIN ) } ${ text }` }>
			{ flat ? '' : up ? '▲' : '▼' } { text }
		</span>
	);
}

export const Card = ( { title, subtitle, actions, children, className = '' } ) => (
	<section className={ `ssgsw-an-card ${ className }` }>
		{ ( title || actions ) && (
			<header className="ssgsw-an-card__head">
				{ title && (
					<div className="ssgsw-an-card__headtext">
						<h3 className="ssgsw-an-card__title">{ title }</h3>
						{ subtitle && <p className="ssgsw-an-card__sub">{ subtitle }</p> }
					</div>
				) }
				{ actions }
			</header>
		) }
		{ children }
	</section>
);

const SEVERITY = {
	critical: __( 'Critical', TEXT_DOMAIN ),
	warning: __( 'Warning', TEXT_DOMAIN ),
	info: __( 'Info', TEXT_DOMAIN ),
};
export const SeverityChip = ( { severity } ) => (
	<span className={ `ssgsw-sev ssgsw-sev--${ SEVERITY[ severity ] ? severity : 'info' }` }>{ SEVERITY[ severity ] || SEVERITY.info }</span>
);

const STATUS = {
	instock: [ __( 'In stock', TEXT_DOMAIN ), 'ok' ],
	lowstock: [ __( 'Low stock', TEXT_DOMAIN ), 'warn' ],
	outofstock: [ __( 'Out of stock', TEXT_DOMAIN ), 'bad' ],
	onbackorder: [ __( 'Backorder', TEXT_DOMAIN ), 'warn' ],
	unmanaged: [ __( 'Not tracked', TEXT_DOMAIN ), 'muted' ],
	out_of_stock: [ __( 'Out of stock', TEXT_DOMAIN ), 'bad' ],
	low_stock: [ __( 'Low stock', TEXT_DOMAIN ), 'warn' ],
	at_risk: [ __( 'At risk', TEXT_DOMAIN ), 'warn' ],
	overstock: [ __( 'Overstock', TEXT_DOMAIN ), 'info' ],
	dead_stock: [ __( 'Dead stock', TEXT_DOMAIN ), 'muted' ],
	healthy: [ __( 'Healthy', TEXT_DOMAIN ), 'ok' ],
};
export const StatusBadge = ( { status } ) => {
	const s = STATUS[ status ] || [ status || '–', 'muted' ];
	return <span className={ `ssgsw-badge ssgsw-badge--${ s[ 1 ] }` }>{ s[ 0 ] }</span>;
};

/** Pager for a total/limit/page set. */
export function Pager( { total, limit, page, onPage } ) {
	const pages = Math.max( 1, Math.ceil( total / limit ) );
	if ( pages <= 1 ) {
		return null;
	}
	return (
		<nav className="ssgsw-pager" aria-label={ __( 'Pagination', TEXT_DOMAIN ) }>
			<button type="button" className="ssgsw-analytics-btn ssgsw-analytics-btn--secondary" disabled={ page <= 1 } onClick={ () => onPage( page - 1 ) }>{ __( 'Previous', TEXT_DOMAIN ) }</button>
			<span>{ sprintf( __( 'Page %1$d of %2$d', TEXT_DOMAIN ), page, pages ) }</span>
			<button type="button" className="ssgsw-analytics-btn ssgsw-analytics-btn--secondary" disabled={ page >= pages } onClick={ () => onPage( page + 1 ) }>{ __( 'Next', TEXT_DOMAIN ) }</button>
		</nav>
	);
}

/** Slide-in drawer (Esc closes, focus moves in). */
export function Drawer( { title, onClose, children } ) {
	const ref = useRef( null );
	useEffect( () => {
		const prev = document.activeElement;
		if ( ref.current ) {
			ref.current.focus();
		}
		const key = ( e ) => e.key === 'Escape' && onClose();
		document.addEventListener( 'keydown', key );
		return () => {
			document.removeEventListener( 'keydown', key );
			if ( prev && prev.focus ) {
				prev.focus();
			}
		};
	}, [ onClose ] );
	return (
		<div className="ssgsw-drawer-wrap">
			<div className="ssgsw-drawer-backdrop" onClick={ onClose } aria-hidden="true"></div>
			<aside className="ssgsw-drawer" role="dialog" aria-modal="true" aria-label={ title } tabIndex={ -1 } ref={ ref }>
				<header className="ssgsw-drawer__head">
					<h3>{ title }</h3>
					<button type="button" className="ssgsw-drawer__close" onClick={ onClose } aria-label={ __( 'Close', TEXT_DOMAIN ) }>×</button>
				</header>
				<div className="ssgsw-drawer__body">{ children }</div>
			</aside>
		</div>
	);
}
