import { useCallback, useEffect, useRef, useState } from '@wordpress/element';
import { __, _n, sprintf } from '@wordpress/i18n';
import { DatePicker, ConfigProvider } from 'antd';
import dayjs from 'dayjs';
import { fetchAnalyticsSettings } from '../api';
import { rangeText } from '../format';
import {
	COMPARE_OPTIONS,
	MAX_RANGE_DAYS,
	PRESETS,
	loadRange,
	presetLabel,
	presetRange,
	rangeDates,
	saveRange,
} from './rangeUtils';

const TEXT_DOMAIN = 'stock-sync-with-google-sheet-for-woocommerce';
const PICKER_THEME = { token: { colorPrimary: '#686de0', borderRadius: 6, fontSize: 13 } };

const CalendarIcon = () => (
	<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true" focusable="false">
		<rect x="2" y="3" width="12" height="11" rx="2" stroke="currentColor" strokeWidth="1.4" />
		<path d="M2 6.5h12M5.5 1.8v2.4M10.5 1.8v2.4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
	</svg>
);
const Chevron = () => (
	<svg width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true" focusable="false">
		<path d="M3 4.5 6 7.5l3-3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
	</svg>
);

/** Restore the remembered range once per page load, while the range is still the untouched default. */
let restored = false;

/** Store timezone for the footnote, read once from the analytics settings when no page data has it. */
let tzPromise = null;
const loadTimezone = () => {
	if ( ! tzPromise ) {
		tzPromise = fetchAnalyticsSettings()
			.then( ( d ) => ( d && d.meta && d.meta.timezone ) || '' )
			.catch( () => '' );
	}
	return tzPromise;
};

/**
 * A dropdown button with a menu of choices (role=menu). Arrow keys move, Enter picks, Escape closes
 * and gives focus back to the button; a click outside closes it.
 */
function Dropdown( { label, title, icon, className = '', align = 'right', onClose, children } ) {
	const [ open, setOpen ] = useState( false );
	const wrap = useRef( null );
	const btn = useRef( null );
	const menuRef = useRef( null );

	const close = useCallback( ( refocus ) => {
		setOpen( false );
		if ( refocus && btn.current ) {
			btn.current.focus();
		}
	}, [] );

	useEffect( () => {
		if ( ! open && onClose ) {
			onClose();
		}
	}, [ open ] ); // eslint-disable-line react-hooks/exhaustive-deps

	useEffect( () => {
		if ( ! open ) {
			return undefined;
		}
		const outside = ( e ) => wrap.current && ! wrap.current.contains( e.target ) && setOpen( false );
		document.addEventListener( 'mousedown', outside );
		return () => document.removeEventListener( 'mousedown', outside );
	}, [ open ] );

	// Move focus into the menu: the selected item, else the first.
	useEffect( () => {
		if ( open && menuRef.current ) {
			const items = menuRef.current.querySelectorAll( '[role^="menuitem"]' );
			const sel = menuRef.current.querySelector( '[aria-checked="true"]' ) || items[ 0 ];
			if ( sel ) {
				sel.focus();
			}
		}
	}, [ open ] );

	const onMenuKey = ( e ) => {
		const items = Array.from( menuRef.current ? menuRef.current.querySelectorAll( '[role^="menuitem"]' ) : [] );
		const i = items.indexOf( document.activeElement );
		const typing = e.target && /^(INPUT|TEXTAREA)$/.test( e.target.tagName );
		if ( e.key === 'Escape' ) {
			e.stopPropagation();
			close( true );
		} else if ( typing || ! items.length ) {
			return;
		} else if ( e.key === 'ArrowDown' ) {
			e.preventDefault();
			items[ ( i + 1 ) % items.length ].focus();
		} else if ( e.key === 'ArrowUp' ) {
			e.preventDefault();
			items[ ( i - 1 + items.length ) % items.length ].focus();
		} else if ( e.key === 'Home' ) {
			e.preventDefault();
			items[ 0 ].focus();
		} else if ( e.key === 'End' ) {
			e.preventDefault();
			items[ items.length - 1 ].focus();
		} else if ( e.key === 'Tab' ) {
			setOpen( false );
		}
	};

	return (
		<div className={ `ssgsw-drb__wrap ${ className }` } ref={ wrap }>
			<button
				ref={ btn }
				type="button"
				className={ `ssgsw-drb__btn${ open ? ' is-open' : '' }` }
				aria-haspopup="menu"
				aria-expanded={ open }
				title={ title }
				onClick={ () => setOpen( ( o ) => ! o ) }
				onKeyDown={ ( e ) => {
					if ( e.key === 'ArrowDown' && ! open ) {
						e.preventDefault();
						setOpen( true );
					} else if ( e.key === 'Escape' && open ) {
						close( true );
					}
				} }
			>
				{ icon }
				<span className="ssgsw-drb__label">{ label }</span>
				<Chevron />
			</button>
			{ open && (
				<div className={ `ssgsw-drb__pop is-${ align }` } ref={ menuRef } onKeyDown={ onMenuKey }>
					{ children( close ) }
				</div>
			) }
		</div>
	);
}

const Item = ( { checked, onClick, children } ) => (
	<button type="button" role="menuitemradio" aria-checked={ checked } tabIndex={ -1 } className={ `ssgsw-drb__item${ checked ? ' is-selected' : '' }` } onClick={ onClick }>
		{ children }
	</button>
);

/** Custom range: the Start date → End date picker with the two-month calendar. */
function CustomPicker( { range, onPick, onBack } ) {
	const holder = useRef( null );
	const [ f, t ] = rangeDates( range );
	return (
		<div className="ssgsw-drb__custom" ref={ holder }>
			<div className="ssgsw-drb__custom-head">
				<button type="button" className="ssgsw-link" onClick={ onBack }>{ __( '← Back', TEXT_DOMAIN ) }</button>
				<strong>{ __( 'Custom range', TEXT_DOMAIN ) }</strong>
			</div>
			<ConfigProvider theme={ PICKER_THEME }>
				<DatePicker.RangePicker
					className="ssgsw-an-picker ssgsw-drb__picker"
					open
					autoFocus
					defaultValue={ range.preset === 'custom' ? [ dayjs( f ), dayjs( t ) ] : null }
					placeholder={ [ __( 'Start date', TEXT_DOMAIN ), __( 'End date', TEXT_DOMAIN ) ] }
					format="MMM D, YYYY"
					allowClear
					getPopupContainer={ () => holder.current }
					disabledDate={ ( current, info ) => {
						if ( current && current.isAfter( dayjs(), 'day' ) ) {
							return true;
						}
						const start = info && info.from;
						return !! ( start && Math.abs( current.diff( start, 'day' ) ) >= MAX_RANGE_DAYS );
					} }
					onOpenChange={ () => {} }
					onChange={ ( dates ) => onPick( dates && dates[ 0 ] && dates[ 1 ] ? [ dates[ 0 ].format( 'YYYY-MM-DD' ), dates[ 1 ].format( 'YYYY-MM-DD' ) ] : null ) }
					aria-label={ __( 'Custom date range', TEXT_DOMAIN ) }
				/>
			</ConfigProvider>
		</div>
	);
}

/**
 * Header date controls: a period button ("Last 30 days") and a compare button ("vs Previous period").
 * Props: range, onChange(range), timezone (store time zone for the footnote), showCompare.
 */
export default function DateRangeButton( { range, onChange, timezone = '', showCompare = true } ) {
	const [ custom, setCustom ] = useState( false );
	const [ tz, setTz ] = useState( timezone );

	useEffect( () => setTz( timezone ), [ timezone ] );
	useEffect( () => {
		if ( ! tz ) {
			loadTimezone().then( ( v ) => v && setTz( v ) );
		}
	}, [ tz ] );

	// Restore the remembered choice once, while the range is untouched.
	useEffect( () => {
		if ( restored ) {
			return;
		}
		restored = true;
		const pristine = ! range.preset && ! range.from && ! range.to && ! range.auto && ! range.stay && ! range.compare;
		const saved = pristine ? loadRange() : null;
		if ( saved ) {
			onChange( { ...range, ...saved } );
		}
	}, [] ); // eslint-disable-line react-hooks/exhaustive-deps

	const apply = ( next ) => {
		saveRange( next );
		onChange( next );
	};

	const [ from, to ] = rangeDates( range );
	const name = presetLabel( range );
	const shifted = !! range.auto && !! range.to;
	let label;
	if ( name && ! shifted ) {
		label = name;
	} else if ( ! range.preset && ! range.from && ! range.to ) {
		label = sprintf( _n( 'Last %d day', 'Last %d days', Number( range.days || 28 ), TEXT_DOMAIN ), range.days || 28 );
	} else {
		label = rangeText( from, to );
	}
	const compare = range.compare || 'previous';
	const compareName = ( COMPARE_OPTIONS.find( ( c ) => c[ 0 ] === compare ) || COMPARE_OPTIONS[ 0 ] )[ 1 ];

	return (
		<div className="ssgsw-drb" role="group" aria-label={ __( 'Date range', TEXT_DOMAIN ) }>
			<Dropdown
				className="ssgsw-drb__period"
				icon={ <CalendarIcon /> }
				label={ <>{ label }{ shifted && <small className="ssgsw-drb__hint">{ __( ' · latest sale', TEXT_DOMAIN ) }</small> }</> }
				title={ rangeText( from, to ) }
				onClose={ () => setCustom( false ) }
			>
				{ ( close ) => ( custom ? (
					<CustomPicker
						range={ range }
						onBack={ () => setCustom( false ) }
						onPick={ ( dates ) => {
							setCustom( false );
							close( true );
							if ( dates ) {
								apply( { ...range, preset: 'custom', from: dates[ 0 ], to: dates[ 1 ], days: Math.round( ( Date.parse( dates[ 1 ] ) - Date.parse( dates[ 0 ] ) ) / 86400000 ) + 1, auto: false, stay: true } );
							} else {
								// Cleared: back to the default period.
								apply( { ...range, preset: undefined, from: null, to: null, days: 28, auto: false, stay: true } );
							}
						} }
					/>
				) : (
					<>
						<div role="presentation" className="ssgsw-drb__list">
							{ PRESETS.map( ( [ id, text ] ) => (
								<Item
									key={ id }
									checked={ ! shifted && ( range.preset === id || ( ! range.preset && ! range.from && presetLabel( range ) === text ) ) }
									onClick={ () => {
										apply( { ...range, ...presetRange( id ) } );
										close( true );
									} }
								>
									{ text }
								</Item>
							) ) }
							<hr className="ssgsw-drb__sep" />
							<Item checked={ range.preset === 'custom' && ! shifted } onClick={ () => setCustom( true ) }>{ __( 'Custom…', TEXT_DOMAIN ) }</Item>
						</div>
						<p className="ssgsw-drb__foot">{ tz ? sprintf( __( 'In store time: %s', TEXT_DOMAIN ), tz ) : __( 'In store time', TEXT_DOMAIN ) }</p>
					</>
				) ) }
			</Dropdown>

			{ showCompare && (
				<Dropdown className="ssgsw-drb__compare" label={ <>{ __( 'vs', TEXT_DOMAIN ) } { compareName }</> } title={ __( 'Compare with', TEXT_DOMAIN ) }>
					{ ( close ) => (
						<div role="presentation" className="ssgsw-drb__list">
							{ COMPARE_OPTIONS.map( ( [ id, text ] ) => (
								<Item
									key={ id }
									checked={ compare === id }
									onClick={ () => {
										apply( { ...range, compare: id } );
										close( true );
									} }
								>
									{ text }
								</Item>
							) ) }
						</div>
					) }
				</Dropdown>
			) }
		</div>
	);
}

export { DateRangeButton };
