import { useEffect, useId, useRef, useState } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import Portal from '../../components/Portal';

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

/*
 * "See it in Google Sheets" demo for the locked Analytics preview (FlexStock Free).
 * A pure HTML/CSS/SVG imitation of a Google Sheet with the FlexStock Analytics sidebar open.
 * Everything here is invented sample data: no requests, no images, no iframes, no external fonts.
 */

// Invented products: [ID, type, name, stock, regular price, sale price, SKU].
const PRODUCTS = [
	[ 101, 'Simple', 'Eco friendly Tool Lite', 24, '29.00', '24.00', 'TEST-TOO-0001' ],
	[ 102, 'Variable', 'Modern Gadget Pro', 'in', '89.00', '', 'TEST-GAD-0002' ],
	[ 103, 'Simple', 'Classic Desk Lamp', 8, '45.00', '39.00', 'TEST-LAM-0003' ],
	[ 104, 'Grouped', 'Kitchen Starter Set', 'in', '120.00', '', 'TEST-SET-0004' ],
	[ 105, 'External', 'Smart Garden Kit', 0, '64.00', '', 'TEST-KIT-0005' ],
	[ 106, 'Simple', 'Travel Mug Steel', 57, '18.00', '15.00', 'TEST-MUG-0006' ],
	[ 107, 'Variable', 'Cotton Hoodie Basic', 'in', '42.00', '36.00', 'TEST-HOO-0007' ],
	[ 108, 'Simple', 'Wireless Mouse Slim', 13, '25.00', '', 'TEST-MOU-0008' ],
	[ 109, 'Simple', 'Yoga Mat Plus', 31, '38.00', '32.00', 'TEST-YOG-0009' ],
	[ 110, 'Grouped', 'Bathroom Bundle', 'in', '75.00', '', 'TEST-BUN-0010' ],
	[ 111, 'External', 'Solar Lantern Mini', 4, '22.00', '19.00', 'TEST-SOL-0011' ],
	[ 112, 'Simple', 'Ceramic Plant Pot', 66, '14.00', '', 'TEST-POT-0012' ],
];
const LETTERS = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M' ];
const EMPTY_ROWS = 6;

const usd = ( n, digits = 0 ) => `$${ n.toLocaleString( 'en-US', { minimumFractionDigits: digits, maximumFractionDigits: digits } ) }`;

// [label, value, format, change %, previous value, lower is better]
const KPIS = [
	[ __( 'Revenue', TEXT_DOMAIN ), 12480, ( v ) => usd( v ), 8.2, 11534, false ],
	[ __( 'Orders', TEXT_DOMAIN ), 312, ( v ) => Math.round( v ).toLocaleString( 'en-US' ), 5.1, 297, false ],
	[ __( 'Units sold', TEXT_DOMAIN ), 688, ( v ) => Math.round( v ).toLocaleString( 'en-US' ), 6.4, 647, false ],
	[ __( 'Average order value', TEXT_DOMAIN ), 40, ( v ) => usd( v, 2 ), 2.9, 38.87, false ],
	[ __( 'Refunds', TEXT_DOMAIN ), 310, ( v ) => usd( v ), -12, 352, true ],
	[ __( 'Refund rate', TEXT_DOMAIN ), 2.5, ( v ) => `${ v.toFixed( 1 ) }%`, -13.8, 2.9, true ],
];

const REVENUE = [ 320, 410, 380, 460, 430, 520, 610, 390, 420, 470, 450, 540, 580, 640, 410, 450, 500, 470, 560, 620, 690, 440, 480, 530, 510, 600, 650, 720 ];

const reducedMotion = () => typeof window !== 'undefined' && window.matchMedia && window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches;

/** Counts from 0 to `target` once (skipped when `run` is false or motion is reduced). */
function useCountUp( target, run ) {
	const [ value, setValue ] = useState( run && ! reducedMotion() ? 0 : target );
	useEffect( () => {
		if ( ! run || reducedMotion() ) {
			setValue( target );
			return undefined;
		}
		let frame;
		const start = performance.now();
		const tick = ( now ) => {
			const t = Math.min( 1, ( now - start ) / 900 );
			setValue( target * ( 1 - Math.pow( 1 - t, 3 ) ) );
			if ( t < 1 ) {
				frame = requestAnimationFrame( tick );
			}
		};
		// Start after the sidebar has slid in.
		const timer = setTimeout( () => {
			frame = requestAnimationFrame( tick );
		}, 250 );
		return () => {
			clearTimeout( timer );
			cancelAnimationFrame( frame );
		};
	}, [ target, run ] );
	return value;
}

/* ---- Inline SVG icons (decorative) ---------------------------------------------------------- */

const SheetIcon = () => (
	<svg className="ssgsw-sheet-demo__logo" viewBox="0 0 24 32" aria-hidden="true" focusable="false">
		<path d="M3 0h12l9 9v20a3 3 0 0 1-3 3H3a3 3 0 0 1-3-3V3a3 3 0 0 1 3-3z" fill="#188038" />
		<path d="M15 0l9 9h-6a3 3 0 0 1-3-3z" fill="#0f5c27" />
		<path d="M5 14h14v11H5z M7 16v2h4v-2z M13 16v2h4v-2z M7 20v3h4v-3z M13 20v3h4v-3z" fill="#fff" fillRule="evenodd" />
	</svg>
);

const PATHS = {
	overview: 'M2 2h5v5H2zM9 2h5v5H9zM2 9h5v5H2zM9 9h5v5H9z',
	skus: 'M2 3h1.5v10H2zM5 3h1v10H5zM7.5 3h2v10h-2zM11 3h1v10h-1zM13 3h1.5v10H13z',
	stock: 'M8 1.5l6 3v7l-6 3-6-3v-7zm0 1.7L3.8 5.3 8 7.4l4.2-2.1zM3.5 6.6v4l3.8 1.9v-4zm9 0l-3.8 1.9v4l3.8-1.9z',
	forecast: 'M1.5 12.5l4-4 3 2.5 5.5-6.5 1 .9-6.4 7.6-3-2.5-3.1 3.1z',
	trends: 'M1 13h14v1.5H1zM2 11l3-5 3 3 3-6 3 4-1.2.9L11 5.6 8.3 11 5.2 7.9 3.3 11.8z',
	ai: 'M8 1l1.6 4.4L14 7l-4.4 1.6L8 13l-1.6-4.4L2 7l4.4-1.6zM13 11l.7 1.3L15 13l-1.3.7L13 15l-.7-1.3L11 13l1.3-.7z',
	reports: 'M3 1h7l3 3v11H3zm1.5 1.5v11h7v-8H9V2.5zM5.5 8h5v1.2h-5zm0 2.5h5v1.2h-5z',
	settings: 'M2 4h7v1.4H2zM11.5 4H14v1.4h-2.5zM9 2.6h2.5v4.2H9zM2 10.6h2.5V12H2zM7 10.6h7V12H7zM4.5 9.2H7v4.2H4.5z',
	refresh: 'M13.5 3v4h-4l1.5-1.5A4.5 4.5 0 1 0 12.4 10l1.3.6A6 6 0 1 1 12 4.5z',
	lock: 'M5 7V5a3 3 0 0 1 6 0v2h1v7H4V7zm1.5 0h3V5a1.5 1.5 0 0 0-3 0z',
	close: 'M3.5 2.4L8 6.9l4.5-4.5 1.1 1.1L9.1 8l4.5 4.5-1.1 1.1L8 9.1l-4.5 4.5-1.1-1.1L6.9 8 2.4 3.5z',
};

export const Icon = ( { name, className = '' } ) => (
	<svg className={ `ssgsw-sheet-demo__icon ${ className }` } viewBox="0 0 16 16" aria-hidden="true" focusable="false">
		<path d={ PATHS[ name ] } fill="currentColor" />
	</svg>
);

const SIDE_TABS = [
	[ 'overview', __( 'Overview', TEXT_DOMAIN ) ],
	[ 'skus', __( 'SKUs', TEXT_DOMAIN ) ],
	[ 'stock', __( 'Stock', TEXT_DOMAIN ) ],
	[ 'forecast', __( 'Forecast', TEXT_DOMAIN ) ],
	[ 'trends', __( 'Trends', TEXT_DOMAIN ) ],
	[ 'ai', __( 'Ask AI', TEXT_DOMAIN ) ],
	[ 'reports', __( 'Reports', TEXT_DOMAIN ) ],
	[ 'settings', __( 'Settings', TEXT_DOMAIN ) ],
];

/* ---- Pieces ------------------------------------------------------------------------------------ */

function Callout( { children, className = '' } ) {
	return <span className={ `ssgsw-sheet-demo__callout ${ className }` }>{ children }</span>;
}

function Kpi( { label, target, format, change, previous, invert, animate } ) {
	const value = useCountUp( target, animate );
	const up = change > 0;
	const good = up !== invert;
	return (
		<div className="ssgsw-sheet-demo__kpi">
			<span className="ssgsw-sheet-demo__kpi-label">{ label }</span>
			<strong className="ssgsw-sheet-demo__kpi-value">{ format( value ) }</strong>
			<span className="ssgsw-sheet-demo__kpi-meta">
				<span className={ `ssgsw-sheet-demo__delta ${ good ? 'is-good' : 'is-bad' }` }>{ up ? '▲' : '▼' } { Math.abs( change ).toFixed( 1 ) }%</span>
				{ ' ' }
				<span>{ sprintf( /* translators: %s: value in the previous period */ __( 'was %s', TEXT_DOMAIN ), format( previous ) ) }</span>
			</span>
		</div>
	);
}

function Spark() {
	const w = 260;
	const h = 56;
	const max = Math.max( ...REVENUE );
	const step = w / ( REVENUE.length - 1 );
	const pts = REVENUE.map( ( v, i ) => `${ ( i * step ).toFixed( 1 ) },${ ( h - 4 - ( v / max ) * ( h - 10 ) ).toFixed( 1 ) }` );
	return (
		<svg className="ssgsw-sheet-demo__spark" viewBox={ `0 0 ${ w } ${ h }` } preserveAspectRatio="none" aria-hidden="true" focusable="false">
			<polygon points={ `0,${ h } ${ pts.join( ' ' ) } ${ w },${ h }` } fill="rgba(150, 28, 246, 0.12)" />
			<polyline points={ pts.join( ' ' ) } fill="none" stroke="#961cf6" strokeWidth="2" strokeLinejoin="round" vectorEffect="non-scaling-stroke" />
		</svg>
	);
}

function Grid( { rows } ) {
	const list = PRODUCTS.slice( 0, rows );
	const head = [ __( 'ID', TEXT_DOMAIN ), __( 'Type', TEXT_DOMAIN ), __( 'Name', TEXT_DOMAIN ), __( 'Stock', TEXT_DOMAIN ), __( 'Regular price', TEXT_DOMAIN ), __( 'Sale price', TEXT_DOMAIN ), __( 'SKU', TEXT_DOMAIN ) ];
	const blank = LETTERS.length - head.length;
	return (
		<div className="ssgsw-sheet-demo__grid-wrap">
			<table className="ssgsw-sheet-demo__grid">
				<thead>
					<tr className="ssgsw-sheet-demo__letters">
						<th className="ssgsw-sheet-demo__corner" aria-hidden="true"></th>
						{ LETTERS.map( ( l ) => <th key={ l } scope="col" aria-hidden="true">{ l }</th> ) }
					</tr>
					<tr className="ssgsw-sheet-demo__head">
						<th className="ssgsw-sheet-demo__rownum" aria-hidden="true">1</th>
						{ head.map( ( h ) => <th key={ h } scope="col">{ h }</th> ) }
						{ Array.from( { length: blank }, ( _, i ) => <td key={ i } className="is-blank"></td> ) }
					</tr>
				</thead>
				<tbody>
					{ list.map( ( p, r ) => (
						<tr key={ p[ 0 ] }>
							<th className="ssgsw-sheet-demo__rownum" scope="row">{ r + 2 }</th>
							<td className="is-num">{ p[ 0 ] }</td>
							<td>{ p[ 1 ] }</td>
							<td className="is-name">{ p[ 2 ] }</td>
							<td className={ p[ 3 ] === 'in' ? 'is-instock' : 'is-num' }>{ p[ 3 ] === 'in' ? __( 'In Stock', TEXT_DOMAIN ) : p[ 3 ] }</td>
							<td className="is-num">{ p[ 4 ] }</td>
							<td className="is-num">{ p[ 5 ] }</td>
							<td>{ p[ 6 ] }</td>
							{ Array.from( { length: blank }, ( _, i ) => <td key={ i }></td> ) }
						</tr>
					) ) }
					{ Array.from( { length: EMPTY_ROWS }, ( _, e ) => (
						<tr key={ `e${ e }` } aria-hidden="true">
							<th className="ssgsw-sheet-demo__rownum">{ list.length + e + 2 }</th>
							{ LETTERS.map( ( l ) => <td key={ l }></td> ) }
						</tr>
					) ) }
				</tbody>
			</table>
		</div>
	);
}

function Sidebar( { compact, animate } ) {
	const kpis = compact ? KPIS.slice( 0, 4 ) : KPIS;
	return (
		<aside className="ssgsw-sheet-demo__side" aria-label={ __( 'FlexStock Analytics sidebar (sample)', TEXT_DOMAIN ) }>
			<div className="ssgsw-sheet-demo__side-head">
				<div>
					<strong>{ __( 'FlexStock Analytics', TEXT_DOMAIN ) }</strong>
					<span>{ __( 'Store · +00:00', TEXT_DOMAIN ) }</span>
				</div>
				<Icon name="refresh" />
				{ ! compact && <Callout className="is-head">{ __( 'Your numbers, inside your own sheet', TEXT_DOMAIN ) }</Callout> }
			</div>
			<div className="ssgsw-sheet-demo__side-body">
				{ ! compact && (
					<div className="ssgsw-sheet-demo__chips">
						{ [ __( '7 days', TEXT_DOMAIN ), __( '14 days', TEXT_DOMAIN ), __( '28 days', TEXT_DOMAIN ), __( '90 days', TEXT_DOMAIN ), __( 'Custom', TEXT_DOMAIN ) ].map( ( c, i ) => (
							<span key={ c } className={ `ssgsw-sheet-demo__chip${ 2 === i ? ' is-active' : '' }` }>{ c }</span>
						) ) }
					</div>
				) }
				{ ! compact && (
					<div className="ssgsw-sheet-demo__compare">
						<span className="ssgsw-sheet-demo__check" aria-hidden="true">✓</span>
						{ __( 'Compare to previous period', TEXT_DOMAIN ) }
						<Callout className="is-compare">{ __( 'Compare to the previous period', TEXT_DOMAIN ) }</Callout>
					</div>
				) }
				<div className="ssgsw-sheet-demo__tabs">
					{ SIDE_TABS.map( ( [ id, label ] ) => (
						<span key={ id } className={ `ssgsw-sheet-demo__tab${ 'overview' === id ? ' is-active' : '' }` } title={ label }>
							<Icon name={ id } />
							<span className="screen-reader-text">{ label }</span>
						</span>
					) ) }
				</div>
				<p className="ssgsw-sheet-demo__caption">{ __( 'Oct 21 – Nov 17 vs the previous 28 days', TEXT_DOMAIN ) }</p>
				<div className="ssgsw-sheet-demo__kpis">
					{ kpis.map( ( [ label, target, format, change, previous, invert ] ) => (
						<Kpi key={ label } label={ label } target={ target } format={ format } change={ change } previous={ previous } invert={ invert } animate={ animate } />
					) ) }
				</div>
				<div className="ssgsw-sheet-demo__section">
					<span className="ssgsw-sheet-demo__section-title">{ __( 'Revenue per day', TEXT_DOMAIN ) }</span>
					<Spark />
				</div>
				{ ! compact && (
					<div className="ssgsw-sheet-demo__section ssgsw-sheet-demo__alerts">
						<span className="ssgsw-sheet-demo__section-title">{ __( 'Stock alerts', TEXT_DOMAIN ) }</span>
						<div className="ssgsw-sheet-demo__alert-row">
							<span className="is-bad"><strong>3</strong> { __( 'Out of stock', TEXT_DOMAIN ) }</span>
							<span className="is-warn"><strong>7</strong> { __( 'Low stock', TEXT_DOMAIN ) }</span>
							<span className="is-warn"><strong>4</strong> { __( 'At risk', TEXT_DOMAIN ) }</span>
						</div>
						<Callout className="is-alerts">{ __( 'Stock alerts without leaving the sheet', TEXT_DOMAIN ) }</Callout>
					</div>
				) }
			</div>
		</aside>
	);
}

/**
 * The sheet mockup. `compact` = small static teaser; otherwise the full demo (animated, with callouts).
 */
export function SheetMock( { compact = false } ) {
	const animate = ! compact;
	const menus = [ __( 'File', TEXT_DOMAIN ), __( 'Edit', TEXT_DOMAIN ), __( 'View', TEXT_DOMAIN ), __( 'Insert', TEXT_DOMAIN ), __( 'Format', TEXT_DOMAIN ), __( 'Data', TEXT_DOMAIN ), __( 'Tools', TEXT_DOMAIN ), __( 'Extensions', TEXT_DOMAIN ), __( 'Help', TEXT_DOMAIN ) ];
	return (
		<div className={ `ssgsw-sheet-demo${ compact ? ' is-compact' : ' is-animated' }` }>
			<div className="ssgsw-sheet-demo__chrome">
				<div className="ssgsw-sheet-demo__titlebar">
					<SheetIcon />
					<div>
						<span className="ssgsw-sheet-demo__filename">{ __( 'Store Stock Sync', TEXT_DOMAIN ) }</span>
						{ ! compact && (
							<span className="ssgsw-sheet-demo__menus" aria-hidden="true">
								{ menus.map( ( item ) => <span key={ item }>{ item }</span> ) }
								<span className="is-plugin">{ __( 'Stock Sync', TEXT_DOMAIN ) }</span>
							</span>
						) }
					</div>
				</div>
				<div className="ssgsw-sheet-demo__toolbar" aria-hidden="true">
					{ [ 18, 18, 18, 30, 12, 40, 18, 18, 18, 12, 18, 18, 18 ].map( ( w, i ) => <span key={ i } style={ { width: w } }></span> ) }
				</div>
				<div className="ssgsw-sheet-demo__formula" aria-hidden="true">
					<span>A1</span>
					<span className="ssgsw-sheet-demo__fx">fx</span>
					<span>{ __( 'ID', TEXT_DOMAIN ) }</span>
				</div>
			</div>
			<div className="ssgsw-sheet-demo__body">
				<Grid rows={ compact ? 7 : PRODUCTS.length } />
				<Sidebar compact={ compact } animate={ animate } />
			</div>
		</div>
	);
}

const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';

/**
 * Modal with the full demo. Mounted only while open. Traps focus, closes on Escape and backdrop click,
 * and gives focus back to the element that opened it.
 */
export function SheetDemoModal( { onClose, onUpgrade, upgradeLabel } ) {
	const ref = useRef( null );
	const titleId = useId();

	useEffect( () => {
		const opener = document.activeElement;
		const items = () => [ ...ref.current.querySelectorAll( FOCUSABLE ) ];
		( items()[ 0 ] || ref.current ).focus();
		const overflow = document.body.style.overflow;
		document.body.style.overflow = 'hidden';

		const onKeyDown = ( event ) => {
			if ( 'Escape' === event.key ) {
				event.stopPropagation();
				onClose();
				return;
			}
			if ( 'Tab' !== event.key ) {
				return;
			}
			const list = items();
			if ( ! list.length ) {
				event.preventDefault();
				return;
			}
			const first = list[ 0 ];
			const last = list[ list.length - 1 ];
			if ( event.shiftKey && ( document.activeElement === first || ! ref.current.contains( document.activeElement ) ) ) {
				event.preventDefault();
				last.focus();
			} else if ( ! event.shiftKey && document.activeElement === last ) {
				event.preventDefault();
				first.focus();
			}
		};
		document.addEventListener( 'keydown', onKeyDown, true );
		return () => {
			document.removeEventListener( 'keydown', onKeyDown, true );
			document.body.style.overflow = overflow;
			if ( opener && typeof opener.focus === 'function' ) {
				opener.focus();
			}
		};
	}, [ onClose ] );

	return (
		<Portal>
			<div className="ssgsw-sheet-modal" role="presentation" onMouseDown={ ( event ) => event.target === event.currentTarget && onClose() }>
				<div ref={ ref } className="ssgsw-sheet-modal__dialog" role="dialog" aria-modal="true" aria-labelledby={ titleId } tabIndex={ -1 }>
					<div className="ssgsw-sheet-modal__head">
						<div>
							<h2 id={ titleId } className="ssgsw-sheet-modal__title">{ __( 'FlexStock Analytics in your Google Sheet', TEXT_DOMAIN ) }</h2>
							<span className="ssgsw-locked__pill">{ __( 'Demo preview with sample data', TEXT_DOMAIN ) }</span>
						</div>
						<button type="button" className="ssgsw-sheet-modal__x" onClick={ onClose } aria-label={ __( 'Close demo', TEXT_DOMAIN ) }>
							<Icon name="close" />
						</button>
					</div>
					<div className="ssgsw-sheet-modal__body">
						<SheetMock />
					</div>
					<div className="ssgsw-sheet-modal__foot">
						<button type="button" className="ssgsw-link" onClick={ onClose }>{ __( 'Close', TEXT_DOMAIN ) }</button>
						<button type="button" className="ssgsw-analytics-btn ssgsw-analytics-btn--primary" onClick={ onUpgrade }>{ upgradeLabel }</button>
					</div>
				</div>
			</div>
		</Portal>
	);
}
