import { useState,useEffect } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import {Button ,Panel, PanelBody, PanelRow,TextControl,CustomSelectControl,CheckboxControl,SelectControl,ToggleControl} from '@wordpress/components';
import { getSettings,useSaveSettings} from '../utils/utils';
import { MultiSelectControl } from '@codeamp/block-components';
import LogViewer from './LogViewer';
import Notices from './Notice'

// 内置时间单位选项
const timeUnitOptions = [
	{
		key: 'seconds',
		name: __('Seconds', 'post-flow'),
	},
	{
		key: 'minutes',
		name: __('Minutes', 'post-flow'),
	},
	{
		key: 'hours',
		name: __('Hours', 'post-flow'),
	},
	{
		key: 'days',
		name: __('Days', 'post-flow'),
	},
];

const scheduleOptions = {
	type: {
		label: __('Type', 'post-flow'),
		options: [
			{
				label: __('Disallow', 'post-flow'),
				value: false
			},
			{
				label: __('Allow', 'post-flow'),
				value: true
			},
		],
	},
	weekday: {
		label: __('Weekday', 'post-flow'),
		options: [
			{label: __('All Weekday', 'post-flow'), value: 0},
			{label: __('Monday', 'post-flow'), value: 1},
			{label: __('Tuesday', 'post-flow'), value: 2},
			{label: __('Wednesday', 'post-flow'), value: 3},
			{label: __('Thursday', 'post-flow'), value: 4},
			{label: __('Friday', 'post-flow'), value: 5},
			{label: __('Saturday', 'post-flow'), value: 6},
			{label: __('Sunday', 'post-flow'), value: 7},
		],
	},
	timefrom: {
		label: __('Time From', 'post-flow'),
		type: 'time',
		placeholder: '00:00',
	},
	timeto: {
		label: __('Time To', 'post-flow'),
		type: 'time',
		placeholder: '23:59',
	},
};


const Dashboard = () => {
	const [settings, setSettings] = useState(window.postfl_data.default_settings || {});
	const saveSettings = useSaveSettings();

	useEffect( () => {
		getSettings( (data) => {
			if (data) {
				setSettings(data);
			}
		});
    }, [] );

	const [scheduleRow, setScheduleRow] = useState({
		type: false,
		weekday: 1,
		timefrom: '12:00',
		timeto: '13:59',
	});
	const addSchedule = () => {
		const newSchedule = [...settings.schedule, scheduleRow];
		const newSettings = {...settings, schedule: newSchedule};
		setSettings(newSettings);
		saveSettings(newSettings);
		setScheduleRow({
			type: false,
			weekday: 1,
			timefrom: '12:00',
			timeto: '13:59',
		});
	}
	const removeSchedule = (index) => {
		const newSchedule = [...settings.schedule];
		newSchedule.splice(index, 1);
		const newSettings = {...settings, schedule: newSchedule};
		setSettings(newSettings);
		saveSettings(newSettings);
	}
	const displayScheduleRow = (row) => {
		const typeLabel=row.type ? scheduleOptions.type.options[1] : scheduleOptions.type.options[0];
		const weekdayLabel=scheduleOptions.weekday.options.find((item) => item.value == row.weekday);

		return sprintf('%s on %s when %s to %s', typeLabel.label,
			weekdayLabel.label,
			row.timefrom, row.timeto);
	}
	const toggleEnable = () => {
		const { enable } = settings;
		const newSettings = { ...settings, enable: !enable };
		saveSettings(newSettings);
		setSettings(newSettings);
	}

    return (
		<>
			<Notices/>
			<div className="app-header">
				<h2 className='app-title'>Post Flow</h2>
				<ToggleControl
				label={ settings.enable ? __( 'Enabled','post-flow' ): __( 'Disabled', 'post-flow' ) }
				checked={ settings.enable }
				onChange={toggleEnable}
				/>
			</div>
            {settings.enable && <div className="postflow-dashboard">
			<Panel className='dashboard'>
				<PanelBody title={ __( 'Primary Settings', 'post-flow' ) }>
					<PanelRow>
						<div>
							<h4>{__( 'Trigger Interval', 'post-flow' ) }</h4>
							<div className="form-row">
								<TextControl
									onChange={(number) => {setSettings({...settings, trigger: {...settings.trigger, value: number}})}}
									value={settings.trigger && settings.trigger.value ? settings.trigger.value : 1}
									type="number"
									hideLabelFromVision={true}
									__nextHasNoMarginBottom={true}
								/>
								<CustomSelectControl
									onChange={(v) => {setSettings({...settings, trigger: {...settings.trigger, unit: v.selectedItem.key}})}}
									options={timeUnitOptions}
									hideLabelFromVision={true}
									value={(settings.trigger && settings.trigger.unit) ? timeUnitOptions.find((item) => item.key ===settings.trigger.unit) : timeUnitOptions[0]}
								/>
							</div>
							<div className="help-text">{__( 'Set how often the trigger runs', 'post-flow' )}</div>
						</div>
					</PanelRow>
					<PanelRow>
						<div className="form-row">
							<TextControl
								onChange={(text)=>{setSettings({...settings, publish_count: text})}}
								value={settings.publish_count || 1}
								label={__( 'Items per Publish', 'post-flow' )}
								help={__( 'Number of items to publish each time', 'post-flow' )}
								type="number"
								min={1}
								__nextHasNoMarginBottom={true}
							/>
							<TextControl
								onChange={(text)=>{setSettings({...settings, daily_limit: text})}}
								value={settings.daily_limit || 0}
								label={__( 'Daily Publish Limit', 'post-flow' )}
								help={__( 'Maximum items to publish per day (0 for unlimited)', 'post-flow' )}
								type="number"
								min={0}
								__nextHasNoMarginBottom={true}
							/>
						</div>
					</PanelRow>
					<PanelRow>
						<CheckboxControl
							__nextHasNoMarginBottom
							checked={settings.random_mode || false}
							help={__('Publish random items; otherwise, the oldest items will be published first','post-flow')}
							label={__('Publish Randomly?','post-flow')}
							onChange={(val) => {setSettings({...settings, random_mode: val})}}
							/>
					</PanelRow>
					<PanelRow>
						<CheckboxControl
							__nextHasNoMarginBottom
							checked={settings.restart_on_manual || false}
							help={__('Restart the schedule if a post is published manually or by another plugin','post-flow')}
							label={__('Restart Schedule on Manual Publish?','post-flow')}
							onChange={(val) => {setSettings({...settings, restart_on_manual: val})
							}}
							/>
					</PanelRow>
					<PanelRow>
						<CheckboxControl
							__nextHasNoMarginBottom
							checked={settings.debug_mode || false}
							help={__('Log more information for debugging','post-flow')}
							label={__('Enable Debug Mode?','post-flow')}
							onChange={(val) => {setSettings({...settings, debug_mode: val})}}
							/>
					</PanelRow>

					<PanelRow>
						<CheckboxControl
							__nextHasNoMarginBottom
							checked={settings.recycle.enable || false}
							help={__('Recycle the oldest published items','post-flow')}
							label={__('Enable Recycle Mode?','post-flow')}
							onChange={(val) => {setSettings({...settings, recycle: {...settings.recycle, enable: val}});}}
							/>
					</PanelRow>
					{settings.recycle.enable && <div>
						<div className="form-row">
							<CheckboxControl
								__nextHasNoMarginBottom
								checked={settings.recycle.as_new || false}
								label={__( 'Treat as New', 'post-flow' )}
								help={__( 'If checked, items will be re-saved as "published" to trigger hooks; otherwise, only the published date will be updated to now.', 'post-flow' )}
								onChange={(val) => {setSettings({...settings, recycle: {...settings.recycle, as_new: val}})}}
							/>
							<CheckboxControl
								__nextHasNoMarginBottom
								checked={settings.recycle.history_day || false}
								label={__( 'Only recycle items published on this day in previous years', 'post-flow' )}
								help={__( 'Recycle items published on the same date in previous years', 'post-flow' )}
								onChange={(val) => {setSettings({...settings, recycle: {...settings.recycle, history_day: val}})}}
							/>
						</div>
						{!settings.recycle.history_day &&<div>
							<h4>{__( 'Minimum Time Gap for Recycling', 'post-flow' ) }</h4>
							<div className="form-row">
								<TextControl
									value={settings.recycle.min_age.value || 0}
									type="number"
									hideLabelFromVision={true}
									__nextHasNoMarginBottom={true}
									onChange={(val) => {setSettings({...settings, recycle: {...settings.recycle, min_age: {...settings.recycle.min_age, value: val}}})}}
								/>
								<CustomSelectControl
									options={timeUnitOptions}
									hideLabelFromVision={true}
									value={timeUnitOptions.find((item) => item.key === settings.recycle.min_age.unit) || timeUnitOptions[0]}
									onChange={(val) => {setSettings({...settings, recycle: {...settings.recycle, min_age: {...settings.recycle.min_age, unit: val.selectedItem.key}}})}}
								/>
							</div>
							<div className="help-text">{__( '0 for no limit', 'post-flow' )}</div>
						</div>}
					</div>}
				</PanelBody>
				<PanelBody
					title={ __( 'Schedule', 'post-flow' ) }
					initialOpen={ false }
				>
					<div>
						{settings.schedule.map((item,index) => (
							<div className={item.type ? "schedule-row allow-bg":"schedule-row disallow-bg"}>
								{displayScheduleRow(item)}
								<Button  onClick={() =>{removeSchedule(index)}} className="delete-icon" icon="trash" size='small'/>
							</div>
						))}
					</div>
					<PanelRow>
						<div className="form-row">
							<SelectControl
								label={__( scheduleOptions.type.label, 'post-flow' )}
								onChange={(val) => {setScheduleRow({...scheduleRow, type: val})}}
								value={scheduleRow.type}
								options={scheduleOptions.type.options.map(option => ({
									...option,
									label: __( option.label, 'post-flow' )
								}))}
							/>
							<SelectControl
								label={__( scheduleOptions.weekday.label, 'post-flow' )}
								onChange={(val) => {setScheduleRow({...scheduleRow, weekday: val})}}
								options={scheduleOptions.weekday.options.map(option => ({
									...option,
									label: __( option.label, 'post-flow' )
								}))}
							/>
							<TextControl
								label={__( scheduleOptions.timefrom.label, 'post-flow' )}
								value={scheduleRow.timefrom}
								onChange={(val)=>{setScheduleRow({...scheduleRow, timefrom: val})}}
								type="time"
							/>
							<TextControl
								label={__( scheduleOptions.timeto.label, 'post-flow' )}
								value={scheduleRow.timeto}
								onChange={(val)=>{setScheduleRow({...scheduleRow, timeto: val})}}
								type="time"
							/>
							<Button onClick={addSchedule} icon="plus" size="small" />
					</div>
					</PanelRow>
				</PanelBody>
				<PanelBody
					title={ __( 'Target Filters', 'post-flow' ) }
					initialOpen={ false }
				>
					<PanelRow>
						<div className="form-row">
							<MultiSelectControl
								label={__( 'Post Type', 'post-flow' ) }
								value={ settings.publish_type || [] }
								options={ window.postfl_data.publish_types || [] }
								onChange={ value => setSettings({ ...settings, publish_type: value }) }
							/>

							<MultiSelectControl
								label={__( 'Post Status', 'post-flow' ) }
								value={ settings.publish_status || [] }
								options={ window.postfl_data.publish_status || [] }
								onChange={ value => setSettings({ ...settings, publish_status: value }) }
							/>
							<MultiSelectControl
								label={__( 'Category', 'post-flow' ) }
								value={ settings.publish_cate || [] }
								options={ window.postfl_data.publish_cates || [] }
								onChange={ value => setSettings({ ...settings, publish_cate: value }) }
							/>
							<MultiSelectControl
								label={__( 'Author', 'post-flow' ) }
								value={ settings.publish_author || [] }
								options={ window.postfl_data.publish_authors || [] }
								onChange={ value => setSettings({ ...settings, publish_author: value }) }
							/>
						</div>

					</PanelRow>
					<div className="help-text">{__( 'Leave blank for no limit', 'post-flow' )}</div>
				</PanelBody>
			</Panel>
			<Button
			  	onClick={() => saveSettings(settings)}
				variant="primary"
				className="app-save"
			>
				{ __( 'Save', 'post-flow' ) }
			</Button>
			<LogViewer />
		</div>}
		</>
     );
}

export default Dashboard;