import { useEffect, useMemo } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { useAnalyticsSettings } from '../SettingsStore';
import { Card, ChipGroup, InlineSentence, Notice, NumberInput, PageHeader, SettingRow, SettingsLayout, Select } from '../controls';
import SheetPreview from '../preview/SheetPreview';
import { CategoryPicker, SkuList, STOCK_STATUS_LABELS, categoryTree } from './shared';

const TEXT_DOMAIN = 'stock-sync-with-google-sheet-for-woocommerce';
const COMPARE_DAYS = [ 7, 14, 28 ];

/** One report tab of the sheet. Focusing anything inside it makes the preview show that tab. */
const Section = ( { id, title, sheetTab, label, children } ) => {
	const { focusTab, setFocusTab } = useAnalyticsSettings();
	return (
		<div id={ `ssgsw-tabcard-${ id }` } onFocusCapture={ () => setFocusTab( id ) } onMouseEnter={ () => setFocusTab( id ) }>
			<Card
				className={ focusTab === id ? 'is-focus' : '' }
				title={ <>{ title } <span className="ssgsw-ui-sheettag">{ sheetTab }</span></> }
				description={ label ? /* translators: %s: summary of the saved filter, e.g. "Last 90 days · Shoes" */ sprintf( __( 'Saved: %s', TEXT_DOMAIN ), label ) : undefined }
			>
				{ children }
			</Card>
		</div>
	);
};

export default function ReportTabs() {
	const { v, set, meta, setFocusTab } = useAnalyticsSettings();
	useEffect( () => () => setFocusTab( 'daily' ), [] ); // eslint-disable-line react-hooks/exhaustive-deps
	const tree = useMemo( () => categoryTree( meta.product_categories || [] ), [ meta.product_categories ] );
	const labels = meta.report_labels || {};
	const statuses = Array.isArray( meta.stock_statuses ) && meta.stock_statuses.length ? meta.stock_statuses : Object.keys( STOCK_STATUS_LABELS );
	const chosenStatuses = v( 'reports.stock_health.statuses' ) || [];
	const mode = v( 'reports.daily.mode' );
	const catHelp = __( 'Child categories are included.', TEXT_DOMAIN );
	const skuHelp = __( 'A parent code includes its variations.', TEXT_DOMAIN );
	const win = meta.daily_window || null;
	const sinceDate = v( 'reports.daily.since' ) || '';
	const selectRolling = () => mode === 'since' && set( 'reports.daily.mode' )( 'rolling' );
	const selectSince = () => mode !== 'since' && set( 'reports.daily.mode' )( 'since' );

	if ( ! v( 'reports' ) ) {
		return null;
	}

	return (
		<SettingsLayout preview={ <SheetPreview page="tabs" /> }>
			<PageHeader
				title={ __( 'Sheet report tabs', TEXT_DOMAIN ) }
				description={ __( 'Choose what each report tab in your sheet shows. A changed filter rebuilds that tab.', TEXT_DOMAIN ) }
			/>

			<Section id="daily" title={ __( 'Daily sales by product', TEXT_DOMAIN ) } sheetTab="SKU Sales (FS)" label={ labels.daily }>
				<InlineSentence id="reports.daily.mode" help={ __( '7 to 730 days. Older rows leave the tab as days pass.', TEXT_DOMAIN ) }>
					<fieldset className="ssgsw-ui-radios ssgsw-ui-radios--inline">
						<legend className="screen-reader-text">{ __( 'Which days to show', TEXT_DOMAIN ) }</legend>
						<div className="ssgsw-ui-radios__opt">
							<input id="ssgsw-an-rep-rolling" type="radio" name="ssgsw-an-rep-mode" checked={ mode !== 'since' } onChange={ () => set( 'reports.daily.mode' )( 'rolling' ) } />
							<label htmlFor="ssgsw-an-rep-rolling">{ __( 'The last', TEXT_DOMAIN ) }</label>
							<NumberInput id="reports.daily.days" inline ariaLabel={ __( 'Number of days', TEXT_DOMAIN ) } value={ v( 'reports.daily.days' ) } onChange={ set( 'reports.daily.days' ) } min={ 7 } max={ 730 } onFocus={ selectRolling } />
							<label htmlFor="ssgsw-an-rep-rolling">{ __( 'days, ending yesterday', TEXT_DOMAIN ) }</label>
						</div>
						<div className="ssgsw-ui-radios__opt">
							<input id="ssgsw-an-rep-since" type="radio" name="ssgsw-an-rep-mode" checked={ mode === 'since' } onChange={ () => set( 'reports.daily.mode' )( 'since' ) } />
							<label htmlFor="ssgsw-an-rep-since">{ __( 'Everything since', TEXT_DOMAIN ) }</label>
							<span className={ `ssgsw-ui-datewrap${ sinceDate ? '' : ' is-empty' }` } data-placeholder={ __( 'first order', TEXT_DOMAIN ) }>
								<input id="reports.daily.since" type="date" className="ssgsw-ui-input ssgsw-ui-input--inline" aria-label={ __( 'Start date (empty = first order)', TEXT_DOMAIN ) } value={ sinceDate } max={ win ? win.to : undefined } onChange={ ( e ) => {
									set( 'reports.daily.since' )( e.target.value );
									selectSince();
								} } />
							</span>
						</div>
					</fieldset>
				</InlineSentence>
				<SettingRow id="reports.daily.categories" label={ __( 'Only these categories', TEXT_DOMAIN ) } help={ catHelp } stacked htmlFor="ssgsw-an-rep-daily-cats">
					<CategoryPicker id="ssgsw-an-rep-daily-cats" value={ v( 'reports.daily.categories' ) } onChange={ set( 'reports.daily.categories' ) } tree={ tree } />
				</SettingRow>
				<SettingRow id="reports.daily.skus" label={ __( 'Only these products', TEXT_DOMAIN ) } help={ skuHelp } stacked htmlFor="ssgsw-an-rep-daily-skus">
					<SkuList id="ssgsw-an-rep-daily-skus" value={ v( 'reports.daily.skus' ) } onChange={ set( 'reports.daily.skus' ) } />
				</SettingRow>
				{ win && win.capped && <Notice>{ sprintf( __( 'Only the last 3 years are kept in the tab (from %s).', TEXT_DOMAIN ), win.from ) }</Notice> }
			</Section>

			<Section id="compare" title={ __( 'Compare with before', TEXT_DOMAIN ) } sheetTab="SKU Compare (FS)" label={ labels.compare }>
				<InlineSentence id="reports.compare.days">
					<label htmlFor="reports.compare.days">{ __( 'Compare the last', TEXT_DOMAIN ) }</label>
					<Select id="reports.compare.days" inline value={ v( 'reports.compare.days' ) } onChange={ ( value ) => set( 'reports.compare.days' )( Number( value ) ) } options={ COMPARE_DAYS.map( ( d ) => ( { value: d, label: String( d ) } ) ) } />
					<span>{ sprintf( /* translators: %d: number of days */ __( 'days with the %d before', TEXT_DOMAIN ), Number( v( 'reports.compare.days' ) ) || 7 ) }</span>
				</InlineSentence>
				<SettingRow id="reports.compare.categories" label={ __( 'Only these categories', TEXT_DOMAIN ) } help={ catHelp } stacked htmlFor="ssgsw-an-rep-cmp-cats">
					<CategoryPicker id="ssgsw-an-rep-cmp-cats" value={ v( 'reports.compare.categories' ) } onChange={ set( 'reports.compare.categories' ) } tree={ tree } />
				</SettingRow>
				<SettingRow id="reports.compare.skus" label={ __( 'Only these products', TEXT_DOMAIN ) } help={ __( 'Must also be in the daily sales tab.', TEXT_DOMAIN ) } stacked htmlFor="ssgsw-an-rep-cmp-skus">
					<SkuList id="ssgsw-an-rep-cmp-skus" value={ v( 'reports.compare.skus' ) } onChange={ set( 'reports.compare.skus' ) } />
				</SettingRow>
			</Section>

			<Section id="dashboard" title={ __( 'Sales dashboard', TEXT_DOMAIN ) } sheetTab="Dashboard (FS)" label={ labels.dashboard }>
				<InlineSentence id="reports.dashboard.days" help={ __( 'Ends yesterday, or on your last day with a sale. 7 to 365.', TEXT_DOMAIN ) }>
					<label htmlFor="reports.dashboard.days">{ __( 'Show the last', TEXT_DOMAIN ) }</label>
					<NumberInput id="reports.dashboard.days" inline value={ v( 'reports.dashboard.days' ) } onChange={ set( 'reports.dashboard.days' ) } min={ 7 } max={ 365 } />
					<span>{ __( 'days', TEXT_DOMAIN ) }</span>
				</InlineSentence>
				<SettingRow id="reports.dashboard.categories" label={ __( 'Only these categories', TEXT_DOMAIN ) } help={ catHelp } stacked htmlFor="ssgsw-an-rep-dash-cats">
					<CategoryPicker id="ssgsw-an-rep-dash-cats" value={ v( 'reports.dashboard.categories' ) } onChange={ set( 'reports.dashboard.categories' ) } tree={ tree } />
				</SettingRow>
			</Section>

			<Section id="stock" title={ __( 'Stock', TEXT_DOMAIN ) } sheetTab="Stock Health (FS)" label={ labels.stock_health }>
				<ChipGroup
					legend={ __( 'Which stock lists to show', TEXT_DOMAIN ) }
					options={ statuses.map( ( key ) => ( { value: key, label: STOCK_STATUS_LABELS[ key ] || key } ) ) }
					value={ chosenStatuses }
					onChange={ ( key, on ) => set( 'reports.stock_health.statuses' )( on ? statuses.filter( ( s ) => s === key || chosenStatuses.includes( s ) ) : chosenStatuses.filter( ( s ) => s !== key ) ) }
				/>
				{ chosenStatuses.length === 0 && <Notice tone="warning">{ __( 'Choose at least one list, otherwise every list except Healthy is shown.', TEXT_DOMAIN ) }</Notice> }
				<SettingRow id="reports.stock_health.categories" label={ __( 'Only these categories', TEXT_DOMAIN ) } help={ catHelp } stacked htmlFor="ssgsw-an-rep-stock-cats">
					<CategoryPicker id="ssgsw-an-rep-stock-cats" value={ v( 'reports.stock_health.categories' ) } onChange={ set( 'reports.stock_health.categories' ) } tree={ tree } />
				</SettingRow>
			</Section>

			<Section id="insights" title={ __( 'Tips and warnings', TEXT_DOMAIN ) } sheetTab="Insights (FS)" label={ labels.insights }>
				<InlineSentence id="reports.insights.days" help={ __( 'Ends yesterday, or on your last day with a sale. 7 to 90.', TEXT_DOMAIN ) }>
					<label htmlFor="reports.insights.days">{ __( 'Look back', TEXT_DOMAIN ) }</label>
					<NumberInput id="reports.insights.days" inline value={ v( 'reports.insights.days' ) } onChange={ set( 'reports.insights.days' ) } min={ 7 } max={ 90 } />
					<span>{ __( 'days', TEXT_DOMAIN ) }</span>
				</InlineSentence>
				<SettingRow id="reports.insights.categories" label={ __( 'Only these categories', TEXT_DOMAIN ) } help={ catHelp } stacked htmlFor="ssgsw-an-rep-ins-cats">
					<CategoryPicker id="ssgsw-an-rep-ins-cats" value={ v( 'reports.insights.categories' ) } onChange={ set( 'reports.insights.categories' ) } tree={ tree } />
				</SettingRow>
			</Section>
		</SettingsLayout>
	);
}
