import { useState, useRef, useEffect } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { compact } from './format';

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

export const COLOR = '#686de0';
export const COLOR_SOFT = '#c9cbf5';
export const COLOR_PREV = '#a5a8c9';

/**
 * Width of an element in CSS pixels, kept up to date on resize. Charts draw at this width so
 * their text stays at its real font size instead of being scaled with the SVG.
 */
function useWidth( fallback ) {
	const ref = useRef( null );
	const [ width, setWidth ] = useState( fallback );
	useEffect( () => {
		const el = ref.current;
		if ( ! el ) {
			return undefined;
		}
		const measure = () => {
			const w = Math.round( el.getBoundingClientRect().width );
			if ( w > 0 ) {
				setWidth( w );
			}
		};
		measure();
		if ( typeof window.ResizeObserver === 'function' ) {
			const ro = new window.ResizeObserver( measure );
			ro.observe( el );
			return () => ro.disconnect();
		}
		window.addEventListener( 'resize', measure );
		return () => window.removeEventListener( 'resize', measure );
	}, [] );
	return [ ref, width ];
}

/**
 * Line / area chart in inline SVG. Hover or focus shows a tooltip; the SVG has a text label.
 *
 * series: [ { name, values: number[], color, dashed, area } ] sharing `labels`.
 */
export function LineChart( { labels, series, height = 240, format = ( v ) => String( v ), ariaLabel, maxXTicks = 7 } ) {
	const [ hover, setHover ] = useState( -1 );
	const ref = useRef( null );
	const [ boxRef, boxWidth ] = useWidth( 720 );
	const W = Math.max( 280, boxWidth );
	const H = height;
	const pad = { l: 46, r: 12, t: 12, b: 26 };
	const n = labels.length;
	const all = series.flatMap( ( s ) => s.values.filter( ( v ) => v !== null && v !== undefined ) );
	const max = Math.max( 1, ...all );
	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 / maxXTicks ) );

	const onMove = ( e ) => {
		const box = ref.current && ref.current.getBoundingClientRect();
		if ( ! box || ! n ) {
			return;
		}
		const ratio = ( ( e.clientX - box.left ) / box.width ) * W;
		const idx = Math.round( ( ( ratio - pad.l ) / iw ) * ( n - 1 ) );
		setHover( Math.max( 0, Math.min( n - 1, idx ) ) );
	};

	const pathFor = ( values ) => {
		let d = '';
		let pen = false;
		values.forEach( ( v, i ) => {
			if ( v === null || v === undefined ) {
				pen = false;
				return;
			}
			d += `${ pen ? 'L' : 'M' }${ x( i ).toFixed( 1 ) },${ y( v ).toFixed( 1 ) } `;
			pen = true;
		} );
		return d.trim();
	};

	const summary = sprintf(
		/* translators: 1: chart label, 2: number of points */
		__( '%1$s. %2$d data points.', TEXT_DOMAIN ),
		ariaLabel || __( 'Line chart', TEXT_DOMAIN ),
		n
	);

	return (
		<div className="ssgsw-chart" ref={ boxRef } onMouseLeave={ () => setHover( -1 ) }>
			<svg
				ref={ ref }
				className="ssgsw-chart__svg"
				viewBox={ `0 0 ${ W } ${ H }` }
				width={ W }
				height={ H }
				role="img"
				aria-label={ summary }
				tabIndex={ 0 }
				onMouseMove={ onMove }
				onFocus={ () => setHover( n - 1 ) }
				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>
				) ) }
				{ labels.map( ( l, i ) => ( i % step === 0 ? (
					<text key={ i } x={ x( i ) } y={ H - 6 } textAnchor="middle" className="ssgsw-chart__tick">{ l }</text>
				) : null ) ) }
				{ series.map( ( s, si ) => {
					const d = pathFor( s.values );
					return (
						<g key={ s.name || si }>
							{ s.area && d && (
								<path d={ `${ d } L${ x( n - 1 ).toFixed( 1 ) },${ y( 0 ) } L${ x( 0 ).toFixed( 1 ) },${ y( 0 ) } Z` } fill={ s.color || COLOR } opacity="0.12" />
							) }
							<path d={ d } fill="none" stroke={ s.color || COLOR } strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" strokeDasharray={ s.dashed ? '5 4' : undefined } />
							{ n <= 40 && s.values.map( ( v, i ) => ( v === null || v === undefined ? null : (
								<circle key={ i } cx={ x( i ) } cy={ y( v ) } r={ hover === i ? 4 : 2 } fill={ s.color || COLOR } />
							) ) ) }
						</g>
					);
				} ) }
				{ hover >= 0 && <line x1={ x( hover ) } x2={ x( hover ) } y1={ pad.t } y2={ pad.t + ih } className="ssgsw-chart__cursor" /> }
			</svg>
			{ hover >= 0 && labels[ hover ] !== undefined && (
				<div className="ssgsw-chart__tip" style={ { left: `${ ( x( hover ) / W ) * 100 }%` } } role="status">
					<strong>{ labels[ hover ] }</strong>
					{ series.map( ( s, si ) => (
						<span key={ s.name || si }>
							<i style={ { background: s.color || COLOR } } aria-hidden="true"></i>
							{ s.name ? `${ s.name }: ` : '' }
							{ s.values[ hover ] === null || s.values[ hover ] === undefined ? '–' : format( s.values[ hover ] ) }
						</span>
					) ) }
				</div>
			) }
			{ series.length > 1 && (
				<div className="ssgsw-chart__legend">
					{ series.map( ( s, si ) => (
						<span key={ s.name || si }><i style={ { background: s.color || COLOR } } aria-hidden="true"></i>{ s.name }</span>
					) ) }
				</div>
			) }
		</div>
	);
}

/** Horizontal bar list (label, bar, value) in inline SVG. rows: [ { label, value, sub } ]. */
export function BarList( { rows, format = ( v ) => String( v ), ariaLabel, color = COLOR } ) {
	const max = Math.max( 1, ...rows.map( ( r ) => Number( r.value ) || 0 ) );
	return (
		<ul className="ssgsw-bars" aria-label={ ariaLabel }>
			{ rows.map( ( r, i ) => (
				<li key={ `${ r.label }-${ i }` } className="ssgsw-bars__row">
					<span className="ssgsw-bars__label" title={ r.label }>
						{ r.onClick ? <button type="button" className="ssgsw-link" onClick={ r.onClick }>{ r.label }</button> : r.label }
						{ r.sub ? <small>{ r.sub }</small> : null }
					</span>
					<svg className="ssgsw-bars__bar" viewBox="0 0 100 8" preserveAspectRatio="none" role="img" aria-label={ `${ r.label }: ${ format( r.value ) }` }>
						<rect x="0" y="0" width="100" height="8" rx="2" fill={ COLOR_SOFT } opacity="0.35" />
						<rect x="0" y="0" width={ Math.max( 1, ( ( Number( r.value ) || 0 ) / max ) * 100 ) } height="8" rx="2" fill={ color } />
					</svg>
					<span className="ssgsw-bars__value">{ format( r.value ) }</span>
				</li>
			) ) }
		</ul>
	);
}

/** 7-point sparkline. */
export function Sparkline( { values, width = 84, height = 24, ariaLabel } ) {
	const v = Array.isArray( values ) && values.length ? values : [ 0 ];
	const max = Math.max( 1, ...v );
	const step = v.length > 1 ? ( width - 4 ) / ( v.length - 1 ) : 0;
	const pts = v.map( ( val, i ) => `${ ( 2 + i * step ).toFixed( 1 ) },${ ( height - 3 - ( val / max ) * ( height - 6 ) ).toFixed( 1 ) }` );
	const label = ariaLabel || sprintf( __( 'Units per day, last 7 days: %s', TEXT_DOMAIN ), v.join( ', ' ) );
	return (
		<svg className="ssgsw-spark" width={ width } height={ height } viewBox={ `0 0 ${ width } ${ height }` } role="img" aria-label={ label }>
			<polyline points={ pts.join( ' ' ) } fill="none" stroke={ COLOR } strokeWidth="1.6" strokeLinejoin="round" strokeLinecap="round" />
			{ pts.length > 0 && <circle cx={ pts[ pts.length - 1 ].split( ',' )[ 0 ] } cy={ pts[ pts.length - 1 ].split( ',' )[ 1 ] } r="2" fill={ COLOR } /> }
		</svg>
	);
}

/** Weekday x hour heatmap of order counts. */
export function Heatmap( { weekdays, hours, matrix, ariaLabel } ) {
	const [ boxRef, boxWidth ] = useWidth( 680 );
	const gap = 2;
	const left = 38;
	const top = 16;
	const cols = Math.max( 1, hours.length );
	// Cells fill the card width (min 18 px, max 30 px) while labels keep their real font size.
	const cellW = Math.max( 18, Math.min( 30, ( boxWidth - left ) / cols ) );
	const cell = Math.min( cellW, 26 );
	const W = left + cols * cellW;
	const H = top + weekdays.length * cell;
	const max = Math.max( 1, ...matrix.flat().map( ( v ) => Number( v ) || 0 ) );
	return (
		<div className="ssgsw-heatmap" ref={ boxRef }>
			<svg viewBox={ `0 0 ${ W } ${ H }` } width={ W } height={ H } role="img" aria-label={ ariaLabel || __( 'Orders by weekday and hour', TEXT_DOMAIN ) }>
				{ hours.map( ( h ) => ( h % 3 === 0 ? <text key={ h } x={ left + h * cellW + cellW / 2 } y={ 10 } textAnchor="middle" className="ssgsw-chart__tick">{ h }</text> : null ) ) }
				{ weekdays.map( ( d, r ) => (
					<g key={ d }>
						<text x={ left - 6 } y={ top + r * cell + cell / 2 + 4 } textAnchor="end" className="ssgsw-chart__tick">{ d }</text>
						{ hours.map( ( h, c ) => {
							const v = Number( matrix[ r ] && matrix[ r ][ c ] ) || 0;
							return (
								<rect key={ h } x={ left + c * cellW + gap / 2 } y={ top + r * cell + gap / 2 } width={ cellW - gap } height={ cell - gap } rx="3" fill={ v ? COLOR : '#eef0f6' } opacity={ v ? 0.18 + 0.82 * ( v / max ) : 1 }>
									<title>{ sprintf( __( '%1$s %2$s:00, %3$d orders', TEXT_DOMAIN ), d, String( h ).padStart( 2, '0' ), v ) }</title>
								</rect>
							);
						} ) }
					</g>
				) ) }
			</svg>
		</div>
	);
}
