import { __ } from '@wordpress/i18n';
import { useEffect, useRef } from '@wordpress/element';
import { InspectorControls } from '@wordpress/block-editor';
import {
	PanelBody,
	TextControl,
	SelectControl,
	ToggleControl,
	DateTimePicker,
	TextareaControl,
	FormTokenField,
} from '@wordpress/components';
import AnimationControls from '../components/animations/AnimationControl';
import AnimatedBlockWrapper from '../components/animations/AnimatedBlockWrapper';
import { createSingleCountdown, TIME_UNITS } from "./script";
import VisibilityControls from "../components/visibility/VisibilityControls";
import {getVisibilityClasses} from "../components/blockStyleUtils";

const AFTER_EXPIRE_ACTIONS = [
	{ value: 'redirect', label: 'Redirect' },
	{ value: 'hide', label: 'Hide' },
	{ value: 'message', label: 'Show message' },
];

const Edit = ({ attributes, setAttributes, clientId }) => {
	const {
		timerType,
		dueDate,
		evergreenHours,
		evergreenMinutes,
		unitsShown = [],
		actionsAfterExpire = [],
		redirectUrl,
		expireMessage,
		showLabels,
		customLabels,
		animationEntrance,
		animationDuration,
		animationDelay,
	} = attributes;

	const effectiveDueDate = dueDate ? new Date(dueDate) : (() => {
		const date = new Date();
		date.setDate(date.getDate() + 1);
		return date.toISOString();
	})();

	const countdownRef = useRef(null);

	const getEvergreenMs = () => {
		const h = parseInt(evergreenHours || 0, 10) * 3600000;
		const m = parseInt(evergreenMinutes || 0, 10) * 60000;
		return h + m;
	};

	const mapValuesToLabels = (values) =>
		Array.isArray(values) ? values.map(v => {
			const found = AFTER_EXPIRE_ACTIONS.find(o => o.value === v);
			return found ? found.label : v;
		}) : [];

	const mapLabelsToValues = (labels) =>
		labels.map(l => {
			const found = AFTER_EXPIRE_ACTIONS.find(o => o.label === l);
			return found ? found.value : l;
		});

	useEffect(() => {
		if ( countdownRef.current ) {
			countdownRef.current.destroy();
		}

		const timerId = `countdown-${clientId}`;
		const element = document.getElementById(timerId);
		countdownRef.current = createSingleCountdown(`#${timerId}`, element);

		element.classList.remove('countdown__timer--hidden');
		const messageEl = document.querySelector('.countdown__message');
		if (messageEl) {
			messageEl.classList.remove('countdown__message--show');
		}
	}, [timerType, dueDate, evergreenHours, evergreenMinutes, showLabels, customLabels, expireMessage, actionsAfterExpire]);

	useEffect(() => {
		if ( ! dueDate ) {
			setAttributes({ dueDate: effectiveDueDate });
		}
	}, []);

	return (
		<AnimatedBlockWrapper
			animationEntrance={animationEntrance}
			animationDuration={animationDuration}
			animationDelay={animationDelay}
			attributes={attributes}
			className={`lg-block lg-block__countdown ${getVisibilityClasses(attributes)}`}
		>
			<InspectorControls>
				<PanelBody title={__('Countdown Settings', 'lead-gen')} initialOpen>
					<SelectControl
						label={__('Type', 'lead-gen')}
						value={timerType}
						options={[
							{ label: __('Due Date', 'lead-gen'), value: 'due' },
							{ label: __('Evergreen Timer', 'lead-gen'), value: 'evergreen' },
						]}
						onChange={(val) => setAttributes({ timerType: val })}
					/>
					{timerType === 'due' && (
						<DateTimePicker
							label={__('Select Due Date/Time', 'lead-gen')}
							currentDate={effectiveDueDate}
							onChange={(val) => setAttributes({ dueDate: val })}
						/>
					)}
					{timerType === 'evergreen' && (
						<div className="lg-countdown-evergreen">
							<TextControl
								label={__('Hours', 'lead-gen')}
								type="number"
								value={evergreenHours}
								onChange={(val) => setAttributes({ evergreenHours: Number(val) })}
							/>
							<TextControl
								label={__('Minutes', 'lead-gen')}
								type="number"
								value={evergreenMinutes}
								onChange={(val) => setAttributes({ evergreenMinutes: Number(val) })}
							/>
						</div>
					)}

					<div className="lg-countdown__units" style={{marginBlock: '24px'}}>
						{TIME_UNITS.map(unit => (
							<ToggleControl
								key={unit}
								label={__('Show ' + unit.charAt(0).toUpperCase() + unit.slice(1), 'lead-gen')}
								checked={unitsShown.includes(unit)}
								onChange={(val) => {
									let newLabelsShown = [...unitsShown];
									if (val && !newLabelsShown.includes(unit)) {
										newLabelsShown.push(unit);
									} else if (!val) {
										newLabelsShown = newLabelsShown.filter(u => u !== unit);
									}
									setAttributes({ unitsShown: newLabelsShown });
								}}
							/>
						))}
					</div>

					<FormTokenField
						label={__('Action After Expire', 'lead-gen')}
						value={mapValuesToLabels(actionsAfterExpire)}
						suggestions={AFTER_EXPIRE_ACTIONS.map(o => o.label)}
						__experimentalExpandOnFocus={true}
						onChange={(tokens) => setAttributes({ actionsAfterExpire: mapLabelsToValues(tokens) })}
					/>
					{actionsAfterExpire.includes('redirect') && (
						<TextControl
							label={__('Redirect URL', 'lead-gen')}
							value={redirectUrl}
							onChange={(val) => setAttributes({ redirectUrl: val })}
						/>
					)}
					{actionsAfterExpire.includes('message') && (
						<TextareaControl
							label={__('Message After Expire', 'lead-gen')}
							value={expireMessage}
							onChange={(val) => setAttributes({ expireMessage: val })}
						/>
					)}
					<ToggleControl
						label={__('Show Labels', 'lead-gen')}
						checked={showLabels}
						onChange={(val) => setAttributes({ showLabels: val })}
					/>
					{showLabels && (
						<div className="lg-countdown__labels">
							<TextControl
								label={__('Days Label', 'lead-gen')}
								value={customLabels.days}
								onChange={(val) => setAttributes({ customLabels: { ...customLabels, days: val } })}
							/>
							<TextControl
								label={__('Hours Label', 'lead-gen')}
								value={customLabels.hours}
								onChange={(val) => setAttributes({ customLabels: { ...customLabels, hours: val } })}
							/>
							<TextControl
								label={__('Minutes Label', 'lead-gen')}
								value={customLabels.minutes}
								onChange={(val) => setAttributes({ customLabels: { ...customLabels, minutes: val } })}
							/>
							<TextControl
								label={__('Seconds Label', 'lead-gen')}
								value={customLabels.seconds}
								onChange={(val) => setAttributes({ customLabels: { ...customLabels, seconds: val } })}
							/>
						</div>
					)}
				</PanelBody>
				<VisibilityControls attributes={attributes} setAttributes={setAttributes} />
				<AnimationControls attributes={attributes} setAttributes={setAttributes} />
			</InspectorControls>

			<time
				id={`countdown-${clientId}`}
				className="countdown__timer"
				dateTime={timerType === 'due'
					? effectiveDueDate
					: new Date(Date.now() + getEvergreenMs()).toISOString()
				}
				role="timer"
				data-mode={timerType}
				data-units={JSON.stringify(unitsShown)}
				data-show-label={showLabels}
				data-label-days={customLabels.days}
				data-label-hours={customLabels.hours}
				data-label-minutes={customLabels.minutes}
				data-label-seconds={customLabels.seconds}
				data-after-type={JSON.stringify(actionsAfterExpire)}
				data-after-message={expireMessage}
			>
				{dueDate}
			</time>
			<p className="countdown__message"></p>
		</AnimatedBlockWrapper>
	);
};

export default Edit;
