import { __, _n, sprintf } from '@wordpress/i18n';
import { useAnalyticsSettings } from '../SettingsStore';
import { Advanced, Card, Notice, NumberInput, PageHeader, SettingRow, SettingsLayout, Select, SwitchRow } from '../controls';
import SheetPreview from '../preview/SheetPreview';

const TEXT_DOMAIN = 'stock-sync-with-google-sheet-for-woocommerce';
const HORIZONS = [ 7, 14, 30, 60, 90 ];
const METHOD_LABELS = {
	ses: __( 'Steady sales', TEXT_DOMAIN ),
	holt: __( 'Growing or shrinking sales', TEXT_DOMAIN ),
};

export default function ForecastProfit() {
	const { v, set, meta } = useAnalyticsSettings();
	const found = meta.cost_keys_found && typeof meta.cost_keys_found === 'object' ? Object.entries( meta.cost_keys_found ) : [];
	const costKey = v( 'margin.cost_meta_key' ) || '';
	const horizon = Number( v( 'forecast.horizon' ) );
	const horizons = HORIZONS.includes( horizon ) ? HORIZONS : [ ...HORIZONS, horizon ].sort( ( a, b ) => a - b );
	const methods = Array.isArray( meta.forecast_methods ) && meta.forecast_methods.length ? meta.forecast_methods : [ 'ses', 'holt' ];

	return (
		<SettingsLayout preview={ <SheetPreview page="forecast" /> }>
			<PageHeader
				title={ __( 'Forecast and profit', TEXT_DOMAIN ) }
				description={ __( 'Predict sales, when stock runs out, and profit.', TEXT_DOMAIN ) }
			/>
			<Card title={ __( 'Sales forecast', TEXT_DOMAIN ) } description={ __( 'Shown in the Forecast report.', TEXT_DOMAIN ) }>
				<SwitchRow id="forecast.enabled" label={ __( 'Predict future sales', TEXT_DOMAIN ) } help={ __( 'Turns the Forecast report on.', TEXT_DOMAIN ) } checked={ v( 'forecast.enabled' ) } onChange={ set( 'forecast.enabled' ) } />
				{ v( 'forecast.enabled' ) && (
					<>
						<SettingRow id="forecast.horizon" label={ __( 'Forecast how far ahead', TEXT_DOMAIN ) } help={ __( 'You can change this later in the Forecast report.', TEXT_DOMAIN ) }>
							<Select id="forecast.horizon" value={ v( 'forecast.horizon' ) } onChange={ ( value ) => set( 'forecast.horizon' )( Number( value ) ) } options={ horizons.map( ( d ) => ( { value: d, label: sprintf( __( '%d days', TEXT_DOMAIN ), d ) } ) ) } />
						</SettingRow>
						<SettingRow id="forecast.method" label={ __( 'Forecast style', TEXT_DOMAIN ) } help={ __( 'Pick “growing or shrinking” when sales are clearly going up or down.', TEXT_DOMAIN ) }>
							<Select id="forecast.method" value={ v( 'forecast.method' ) } onChange={ set( 'forecast.method' ) } options={ methods.map( ( m ) => ( { value: m, label: METHOD_LABELS[ m ] || m } ) ) } />
						</SettingRow>
						<Advanced>
							<SettingRow id="forecast.alpha" label={ __( 'How quickly it reacts to change', TEXT_DOMAIN ) } help={ __( '0.01 to 1. Higher reacts faster; 0.3 suits most stores.', TEXT_DOMAIN ) }>
								<NumberInput id="forecast.alpha" value={ v( 'forecast.alpha' ) } onChange={ set( 'forecast.alpha' ) } min={ 0.01 } max={ 1 } step={ 0.05 } />
							</SettingRow>
						</Advanced>
					</>
				) }
			</Card>

			<Card title={ __( 'Profit', TEXT_DOMAIN ) } description={ __( 'Profit = sales minus product cost.', TEXT_DOMAIN ) }>
				<SettingRow id="margin.default_margin_pct" label={ __( 'Profit margin for products without a cost', TEXT_DOMAIN ) } help={ __( 'Used when a product has no cost price. 0 = leave their profit empty.', TEXT_DOMAIN ) }>
					<NumberInput id="margin.default_margin_pct" value={ v( 'margin.default_margin_pct' ) } onChange={ set( 'margin.default_margin_pct' ) } min={ 0 } max={ 95 } step={ 0.5 } suffix="%" />
				</SettingRow>
				<Advanced title={ __( 'Where your cost prices are stored', TEXT_DOMAIN ) }>
					<SettingRow id="margin.cost_meta_key" label={ __( 'Where your cost price is stored', TEXT_DOMAIN ) } help={ __( 'The product field with each unit cost. Empty = detect automatically.', TEXT_DOMAIN ) }>
						<input
							id="margin.cost_meta_key"
							type="text"
							list="ssgsw-an-cost-keys"
							className="ssgsw-ui-input"
							value={ costKey }
							placeholder={ found.length ? found[ 0 ][ 0 ] : '_wc_cog_cost' }
							onChange={ ( event ) => set( 'margin.cost_meta_key' )( event.target.value.replace( /[^A-Za-z0-9_-]/g, '' ).slice( 0, 64 ) ) }
						/>
						<datalist id="ssgsw-an-cost-keys">
							{ ( meta.cost_meta_keys || [] ).map( ( k ) => <option key={ k } value={ k } /> ) }
						</datalist>
					</SettingRow>
					{ found.length > 0 ? (
						<Notice>
							{ __( 'Found on your products:', TEXT_DOMAIN ) }{ ' ' }
							{ found.map( ( [ key, count ], i ) => (
								<span key={ key }>
									{ i > 0 && ', ' }
									<code>{ key }</code> { sprintf( _n( '(%d product)', '(%d products)', count, TEXT_DOMAIN ), count ) }
									{ costKey !== key && (
										<>
											{ ' ' }
											<button type="button" className="ssgsw-ui-linkbtn" onClick={ () => set( 'margin.cost_meta_key' )( key ) }>{ __( 'Use this', TEXT_DOMAIN ) }</button>
										</>
									) }
								</span>
							) ) }
						</Notice>
					) : (
						<p className="ssgsw-ui-muted">{ __( 'No known cost field was found on your products. Enter your own field name, or set a profit margin above.', TEXT_DOMAIN ) }</p>
					) }
				</Advanced>
			</Card>
		</SettingsLayout>
	);
}
