import { __, sprintf } from '@wordpress/i18n';
import { CheckMarkIcon, ScheduleIcon, SheetIcon } from '../../../Settings/icons';
import SyncStatus from '../../SyncStatus';
import { useAnalyticsSettings } from '../SettingsStore';
import { Advanced, Card, Notice, PageHeader, SettingRow, SettingsLayout, Select, SwitchRow } from '../controls';
import SheetPreview from '../preview/SheetPreview';
import { HOURS } from './shared';

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

const FREQUENCIES = [
	{ value: 'daily', label: __( 'Once a day', TEXT_DOMAIN ) },
	{ value: '6h', label: __( 'Every 6 hours', TEXT_DOMAIN ) },
	{ value: 'hourly', label: __( 'Every hour', TEXT_DOMAIN ) },
];

const METHODS = [
	{
		value: 'cron',
		icon: <ScheduleIcon />,
		title: __( 'Your website', TEXT_DOMAIN ),
		recommended: true,
		text: __( 'Your website updates the sheet by itself. The sheet does not need to be open.', TEXT_DOMAIN ),
	},
	{
		value: 'apps_script',
		icon: <SheetIcon />,
		title: __( 'Google Sheets', TEXT_DOMAIN ),
		recommended: false,
		text: __( 'The sheet updates itself using a timer in your Google account. Choose this only if your website cannot connect to Google.', TEXT_DOMAIN ),
	},
];

export default function SheetSync() {
	const { v, set, saved, meta } = useAnalyticsSettings();
	const syncOn = v( 'sync.enabled' );
	const method = v( 'sync.method' );
	const isWordPress = method === 'cron';

	return (
		<SettingsLayout preview={ <SheetPreview page="sync" /> }>
			<PageHeader
				title={ __( 'Keep the sheet updated', TEXT_DOMAIN ) }
				description={ __( 'Choose when new sales are added to your sheet, and who does it.', TEXT_DOMAIN ) }
			/>

			<Card>
				<SwitchRow
					id="sync.enabled"
					label={ __( 'Keep the sheet updated automatically', TEXT_DOMAIN ) }
					help={ __( 'New days are added on a schedule.', TEXT_DOMAIN ) }
					checked={ syncOn }
					onChange={ set( 'sync.enabled' ) }
				/>
			</Card>

			{ syncOn && (
				<>
					<Card title={ __( 'Who updates the sheet', TEXT_DOMAIN ) } description={ __( 'Pick where the schedule runs.', TEXT_DOMAIN ) }>
						<fieldset className="ssgsw-ui-choices">
							<legend className="screen-reader-text">{ __( 'Who updates the sheet', TEXT_DOMAIN ) }</legend>
							{ METHODS.map( ( item ) => (
								<label key={ item.value } className={ `ssgsw-ui-choice${ method === item.value ? ' is-on' : '' }` }>
									<input type="radio" name="ssgsw-an-method" value={ item.value } checked={ method === item.value } onChange={ () => set( 'sync.method' )( item.value ) } className="ssgsw-ui-sr" />
									<span className="ssgsw-ui-choice__icon">{ item.icon }</span>
									<span className="ssgsw-ui-choice__text">
										<strong>
											{ item.title }
											{ item.recommended && <span className="ssgsw-ui-badge ssgsw-ui-badge--brand">{ __( 'Recommended', TEXT_DOMAIN ) }</span> }
										</strong>
										<span>{ item.text }</span>
									</span>
									<span className="ssgsw-ui-choice__check"><CheckMarkIcon /></span>
								</label>
							) ) }
						</fieldset>
					</Card>

					<Card title={ __( 'When it updates', TEXT_DOMAIN ) }>
						<SettingRow id="sync.frequency" label={ __( 'How often', TEXT_DOMAIN ) } help={ __( 'Once a day suits most stores.', TEXT_DOMAIN ) }>
							<Select id="sync.frequency" value={ v( 'sync.frequency' ) } onChange={ set( 'sync.frequency' ) } options={ FREQUENCIES } />
						</SettingRow>
						{ v( 'sync.frequency' ) === 'daily' && (
							<SettingRow id="sync.hour" label={ __( 'Time of day', TEXT_DOMAIN ) } help={ sprintf( /* translators: %s: store timezone */ __( 'Uses your store time (%s).', TEXT_DOMAIN ), meta.timezone ) }>
								<Select id="sync.hour" value={ v( 'sync.hour' ) } onChange={ ( value ) => set( 'sync.hour' )( Number( value ) ) } options={ HOURS } />
							</SettingRow>
						) }
						<SwitchRow
							id="sync.rerecord_recent"
							label={ __( 'Correct recent days every night', TEXT_DOMAIN ) }
							help={ __( 'Picks up orders that were cancelled or refunded later.', TEXT_DOMAIN ) }
							checked={ v( 'sync.rerecord_recent' ) }
							onChange={ set( 'sync.rerecord_recent' ) }
						/>
						{ isWordPress && (
							<SwitchRow
								id="sync.on_order_change"
								label={ __( 'Update the sheet within a minute of each order', TEXT_DOMAIN ) }
								help={ __( 'Sends more requests to Google on busy stores.', TEXT_DOMAIN ) }
								checked={ v( 'sync.on_order_change' ) }
								onChange={ set( 'sync.on_order_change' ) }
							/>
						) }
						{ isWordPress && meta.wp_cron_disabled && (
							<Notice tone="warning">{ __( 'Scheduled tasks are turned off on this website (DISABLE_WP_CRON). Ask your host to run wp-cron.php every few minutes, otherwise the sheet will not update by itself.', TEXT_DOMAIN ) }</Notice>
						) }
					</Card>

					{ ! isWordPress && (
						<Card title={ __( 'Set up the timer in Google Sheets', TEXT_DOMAIN ) } description={ __( 'The sheet creates the timer with one click.', TEXT_DOMAIN ) }>
							<ol className="ssgsw-ui-steps">
								<li>{ __( 'Make sure the latest FlexStock script is installed in your spreadsheet (Extensions → Apps Script).', TEXT_DOMAIN ) }</li>
								<li>{ __( 'Open the sheet, then Stock Sync → Sales Analytics → Settings, and press “Turn on sync trigger”. Google asks you to allow it once.', TEXT_DOMAIN ) }</li>
								<li>{ __( 'Done. The timer follows the schedule you choose here.', TEXT_DOMAIN ) }</li>
							</ol>
							<Advanced>
								<p className="ssgsw-ui-muted">{ __( 'If you switch back to “Your website” later, the old timer turns itself off the next time it runs, so the sheet is never written twice. Updating within a minute of each order needs “Your website”.', TEXT_DOMAIN ) }</p>
							</Advanced>
						</Card>
					) }

					<Card title={ __( 'Update status', TEXT_DOMAIN ) } description={ __( 'Update now, or add past sales (30, 90 or 365 days).', TEXT_DOMAIN ) }>
						<SyncStatus method={ saved.sync.method } canRun={ !! saved.enabled && !! saved.sync.enabled } />
					</Card>
				</>
			) }
		</SettingsLayout>
	);
}
