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

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

export const HOURS = Array.from( { length: 24 }, ( _, h ) => ( { value: h, label: `${ String( h ).padStart( 2, '0' ) }:00` } ) );

export const STOCK_STATUS_LABELS = {
	out_of_stock: __( 'Out of stock', TEXT_DOMAIN ),
	low_stock: __( 'Low stock', TEXT_DOMAIN ),
	at_risk: __( 'Will run out soon', TEXT_DOMAIN ),
	overstock: __( 'Too much stock', TEXT_DOMAIN ),
	dead_stock: __( 'Not selling', TEXT_DOMAIN ),
	healthy: __( 'Healthy', TEXT_DOMAIN ),
};

export const sameList = ( a, b ) => JSON.stringify( a || [] ) === JSON.stringify( b || [] );

/** Product categories as an ordered tree: parents first, children indented under them. */
export const categoryTree = ( list ) => {
	const byParent = {};
	( list || [] ).forEach( ( c ) => {
		( byParent[ c.parent ] = byParent[ c.parent ] || [] ).push( c );
	} );
	const ids = new Set( ( list || [] ).map( ( c ) => c.id ) );
	const out = [];
	const walk = ( parent, depth ) => {
		( byParent[ parent ] || [] ).forEach( ( c ) => {
			out.push( { ...c, depth } );
			if ( depth < 10 ) {
				walk( c.id, depth + 1 );
			}
		} );
	};
	walk( 0, 0 );
	( list || [] ).forEach( ( c ) => {
		if ( c.parent && ! ids.has( c.parent ) && ! out.find( ( o ) => o.id === c.id ) ) {
			out.push( { ...c, depth: 0 } );
			walk( c.id, 1 );
		}
	} );
	return out;
};

/** Pick product categories: chosen ones as removable chips plus a dropdown to add more. */
export const CategoryPicker = ( { id, value, onChange, tree } ) => {
	const chosen = Array.isArray( value ) ? value : [];
	const byId = {};
	tree.forEach( ( c ) => {
		byId[ c.id ] = c;
	} );
	return (
		<div className="ssgsw-ui-cats">
			<div className="ssgsw-ui-cats__chosen">
				{ chosen.length === 0 && <span className="ssgsw-ui-muted">{ __( 'All categories', TEXT_DOMAIN ) }</span> }
				{ chosen.map( ( cid ) => (
					<span key={ cid } className="ssgsw-ui-chip is-on ssgsw-ui-chip--removable">
						<span>{ byId[ cid ] ? byId[ cid ].name : `#${ cid }` }</span>
						<button
							type="button"
							aria-label={ sprintf( /* translators: %s: category name */ __( 'Remove %s', TEXT_DOMAIN ), byId[ cid ] ? byId[ cid ].name : cid ) }
							onClick={ () => onChange( chosen.filter( ( x ) => x !== cid ) ) }
						>
							&times;
						</button>
					</span>
				) ) }
			</div>
			<select
				id={ id }
				className="ssgsw-ui-input"
				value=""
				onChange={ ( event ) => {
					const pick = Number( event.target.value );
					if ( pick && ! chosen.includes( pick ) ) {
						onChange( [ ...chosen, pick ] );
					}
				} }
				disabled={ tree.length === 0 }
			>
				<option value="">{ tree.length ? __( 'Add a category…', TEXT_DOMAIN ) : __( 'No product categories found', TEXT_DOMAIN ) }</option>
				{ tree.filter( ( c ) => ! chosen.includes( c.id ) ).map( ( c ) => (
					<option key={ c.id } value={ c.id }>
						{ `${ '  '.repeat( c.depth ) }${ c.depth ? '└ ' : '' }${ c.name }` }
					</option>
				) ) }
			</select>
		</div>
	);
};

/** Product codes (SKUs), one per line. Keeps the typed text so empty lines do not jump away. */
export const SkuList = ( { id, value, onChange } ) => {
	const list = Array.isArray( value ) ? value : [];
	const [ text, setText ] = useState( list.join( '\n' ) );
	const parse = ( t ) => Array.from( new Set( t.split( /[\r\n,]+/ ).map( ( s ) => s.trim() ).filter( Boolean ) ) ).slice( 0, 200 );
	useEffect( () => {
		if ( ! sameList( parse( text ), list ) ) {
			setText( list.join( '\n' ) );
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [ JSON.stringify( list ) ] );
	return (
		<textarea
			id={ id }
			className="ssgsw-ui-input ssgsw-ui-textarea"
			rows={ 3 }
			value={ text }
			placeholder={ __( 'One product code per line. Empty = all products.', TEXT_DOMAIN ) }
			onChange={ ( event ) => {
				setText( event.target.value );
				const next = parse( event.target.value );
				if ( ! sameList( next, list ) ) {
					onChange( next );
				}
			} }
		/>
	);
};
