import {TimePicker} from '@wordpress/components';
import ButtonGroup from '../components/ButtonGroup';
import {__} from '@wordpress/i18n';
import {useEffect} from '@wordpress/element';

// Helperfunction: Parse String (HH:MM) in date object
const parseTimeToDate = ( timeStr ) => {
	if ( !timeStr ) {
		return null;
	}
	if ( timeStr instanceof Date ) {
		return timeStr;
	}

	const [h, m] = String( timeStr ).split( ':' ).map( Number );
	if ( Number.isNaN( h ) || Number.isNaN( m ) ) {
		return null;
	}

	const d = new Date();
	d.setHours( h, m, 0, 0 );
	return d;
};

// Helperfunction: Format ISO-String back in HH:MM
const formatIsoToTime = ( isoString ) => {
	if ( !isoString ) {
		return '';
	}
	const date = new Date( isoString );

	if ( isNaN( date.getTime() ) ) {
		return '';
	}

	const h = String( date.getHours() ).padStart( 2, '0' );
	const m = String( date.getMinutes() ).padStart( 2, '0' );
	return `${h}:${m}`;
};

const ScheduleTimeField = ( {field, allMetaData, onDataChange} ) => {
	const mode = allMetaData['schedule_time_mode'] || 'all_day';
	const startMeta = allMetaData['schedule_time_start'];
	const endMeta = allMetaData['schedule_time_end'];
	const start = startMeta || '00:00';
	const end = endMeta || '23:59';

	const startDate = parseTimeToDate( start );
	const endDate = parseTimeToDate( end );

	useEffect( () => {
		if ( mode === 'scheduled' ) {
			if ( !startMeta ) {
				onDataChange( 'schedule_time_start', '00:00' );
			}
			if ( !endMeta ) {
				onDataChange( 'schedule_time_end', '23:59' );
			}
		}
	}, [mode, startMeta, endMeta, onDataChange] );

	return (
		<div className="adpresso-schedule-time-wrapper">
			<ButtonGroup
				value={mode}
				options={[
					{key: 'all_day', label: __( 'All day', 'adpresso' )},
					{key: 'scheduled', label: __( 'Scheduled', 'adpresso' )}
				]}
				onChange={( val ) => onDataChange( 'schedule_time_mode', val )}
			/>

			{mode === 'scheduled' && (
				<div className="adpresso-time-inputs">
					<div className="time-input-group adpresso-timepicker-timeonly">
						<label>{__( 'Start', 'adpresso' )}</label>
						<TimePicker
							currentTime={startDate}
							onChange={( newIsoString ) => {
								// newIsoString is here e.g. "2023-10-25T14:00:00"
								const timeString = formatIsoToTime( newIsoString );
								onDataChange( 'schedule_time_start', timeString );
							}}
							is12Hour={false}
						/>
					</div>

					<span className="separator">{__( 'until', 'adpresso' )}</span>

					<div className="time-input-group adpresso-timepicker-timeonly">
						<label>{__( 'End', 'adpresso' )}</label>
						<TimePicker
							currentTime={endDate}
							onChange={( newIsoString ) => {
								const timeString = formatIsoToTime( newIsoString );
								onDataChange( 'schedule_time_end', timeString );
							}}
							is12Hour={false}
						/>
					</div>
				</div>
			)}
		</div>
	);
};

export default ScheduleTimeField;
