/**
 * Date filter chip — inline editor for date range filters.
 *
 * @package RawTypeOE
 */

import { useCallback, useMemo, useState } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { Button, DateField, Select } from '@rawtype/ui';

const DATE_FIELDS = {
	orders: [
		{ value: 'date_created', label: __('Creation date', 'rawtype-order-exporter-woocommerce') },
		{ value: 'date_modified', label: __('Modification date', 'rawtype-order-exporter-woocommerce') },
		{ value: 'date_paid', label: __('Payment date', 'rawtype-order-exporter-woocommerce') },
		{ value: 'date_completed', label: __('Completion date', 'rawtype-order-exporter-woocommerce') },
	],
	products: [
		{ value: 'date_created', label: __('Publication date', 'rawtype-order-exporter-woocommerce') },
		{ value: 'date_modified', label: __('Modification date', 'rawtype-order-exporter-woocommerce') },
	],
	customers: [
		{ value: 'date_registered', label: __('Registration date', 'rawtype-order-exporter-woocommerce') },
		{ value: 'last_order_date', label: __('Last order date', 'rawtype-order-exporter-woocommerce') },
	],
	'cross-entity': [
		{ value: 'date_created', label: __('Order date', 'rawtype-order-exporter-woocommerce') },
	],
};

const OPERATORS = [
	{ value: 'is', label: __('is', 'rawtype-order-exporter-woocommerce') },
	{ value: 'after', label: __('is after', 'rawtype-order-exporter-woocommerce') },
	{ value: 'before', label: __('is before', 'rawtype-order-exporter-woocommerce') },
	{ value: 'between', label: __('is between', 'rawtype-order-exporter-woocommerce') },
];

function getPresetDates(presetKey) {
	const now = new Date();
	const today = now.toISOString().split('T')[0];

	const daysAgo = (days) => {
		const d = new Date(now);
		d.setDate(d.getDate() - days);
		return d.toISOString().split('T')[0];
	};

	const firstOfMonth = () => {
		const d = new Date(now.getFullYear(), now.getMonth(), 1);
		return d.toISOString().split('T')[0];
	};

	const firstOfPrevMonth = () => {
		const d = new Date(now.getFullYear(), now.getMonth() - 1, 1);
		return d.toISOString().split('T')[0];
	};

	const lastOfPrevMonth = () => {
		const d = new Date(now.getFullYear(), now.getMonth(), 0);
		return d.toISOString().split('T')[0];
	};

	const firstOfQuarter = () => {
		const quarter = Math.floor(now.getMonth() / 3) * 3;
		const d = new Date(now.getFullYear(), quarter, 1);
		return d.toISOString().split('T')[0];
	};

	const firstOfYear = () => {
		return now.getFullYear() + '-01-01';
	};

	const firstOfPrevYear = () => {
		return (now.getFullYear() - 1) + '-01-01';
	};

	const lastOfPrevYear = () => {
		return (now.getFullYear() - 1) + '-12-31';
	};

	switch (presetKey) {
		case 'today':
			return [today, today];
		case 'last7':
			return [daysAgo(7), today];
		case 'last30':
			return [daysAgo(30), today];
		case 'this_month':
			return [firstOfMonth(), today];
		case 'prev_month':
			return [firstOfPrevMonth(), lastOfPrevMonth()];
		case 'this_quarter':
			return [firstOfQuarter(), today];
		case 'this_year':
			return [firstOfYear(), today];
		case 'prev_year':
			return [firstOfPrevYear(), lastOfPrevYear()];
		default:
			return ['', ''];
	}
}

const PRESETS = [
	{ key: 'today', label: __('Today', 'rawtype-order-exporter-woocommerce') },
	{ key: 'last7', label: __('Last 7 days', 'rawtype-order-exporter-woocommerce') },
	{ key: 'last30', label: __('Last 30 days', 'rawtype-order-exporter-woocommerce') },
	{ key: 'this_month', label: __('This month', 'rawtype-order-exporter-woocommerce') },
	{ key: 'prev_month', label: __('Previous month', 'rawtype-order-exporter-woocommerce') },
	{ key: 'this_quarter', label: __('This quarter', 'rawtype-order-exporter-woocommerce') },
	{ key: 'this_year', label: __('This year', 'rawtype-order-exporter-woocommerce') },
	{ key: 'prev_year', label: __('Previous year', 'rawtype-order-exporter-woocommerce') },
];

export default function DateFilterChip({ filter, entity, onChange }) {
	const [activePreset, setActivePreset] = useState(null);
	const fields = useMemo(() => DATE_FIELDS[entity] || [], [entity]);

	const field = filter.field || (fields.length ? fields[0].value : '');
	const operator = filter.operator || 'between';
	const value = filter.value || '';
	const isBetween = 'between' === operator;

	const handleFieldChange = useCallback(
		(newField) => {
			onChange({ ...filter, field: newField });
		},
		[filter, onChange],
	);

	const handleOperatorChange = useCallback(
		(newOp) => {
			const newValue = 'between' === newOp ? ['', ''] : '';
			onChange({ ...filter, operator: newOp, value: newValue });
			setActivePreset(null);
		},
		[filter, onChange],
	);

	const handleValueChange = useCallback(
		(newValue) => {
			onChange({ ...filter, value: newValue });
			setActivePreset(null);
		},
		[filter, onChange],
	);

	const handlePreset = useCallback(
		(presetKey) => {
			const [start, end] = getPresetDates(presetKey);
			onChange({
				...filter,
				field: field,
				operator: 'between',
				value: [start, end],
			});
			setActivePreset(presetKey);
		},
		[filter, field, onChange],
	);

	return (
		<div className="roe-date-filter">
			<div className="roe-date-filter-row">
				<Select.Root value={field} onValueChange={handleFieldChange}>
					<Select.Trigger
						placeholder={__('Field', 'rawtype-order-exporter-woocommerce')}
						className="roe-filter-select"
					/>
					<Select.Content>
						{fields.map((f) => (
							<Select.Item key={f.value} value={f.value}>
								{f.label}
							</Select.Item>
						))}
					</Select.Content>
				</Select.Root>

				<Select.Root value={operator} onValueChange={handleOperatorChange}>
					<Select.Trigger
						placeholder={__('Operator', 'rawtype-order-exporter-woocommerce')}
						className="roe-filter-select"
					/>
					<Select.Content>
						{OPERATORS.map((op) => (
							<Select.Item key={op.value} value={op.value}>
								{op.label}
							</Select.Item>
						))}
					</Select.Content>
				</Select.Root>

				{isBetween ? (
					<div className="roe-date-filter-range">
						<DateField
							value={Array.isArray(value) ? value[0] || '' : ''}
							onChange={(e) =>
								handleValueChange([
									e.target.value,
									Array.isArray(value) ? value[1] || '' : '',
								])
							}
						/>
						<span className="roe-date-separator">—</span>
						<DateField
							value={Array.isArray(value) ? value[1] || '' : ''}
							onChange={(e) =>
								handleValueChange([
									Array.isArray(value) ? value[0] || '' : '',
									e.target.value,
								])
							}
						/>
					</div>
				) : (
					<DateField
						value={'string' === typeof value ? value : ''}
						onChange={(e) => handleValueChange(e.target.value)}
					/>
				)}
			</div>

			<div className="roe-date-presets">
				{PRESETS.map((preset) => (
					<Button
						key={preset.key}
						type="button"
						variant={activePreset === preset.key ? 'default' : 'outline'}
						size="sm"
						onClick={() => handlePreset(preset.key)}
					>
						{preset.label}
					</Button>
				))}
			</div>
		</div>
	);
}

/**
 * Get a human-readable summary of a date filter for the chip label.
 *
 * @param {Object} filter The date filter object.
 * @return {string} Summary text.
 */
export function getDateFilterSummary(filter) {
	const operator = filter.operator || 'between';
	const value = filter.value || '';

	// Check presets first.
	for (const preset of PRESETS) {
		const [start, end] = getPresetDates(preset.key);
		if (
			'between' === operator &&
			Array.isArray(value) &&
			value[0] === start &&
			value[1] === end
		) {
			return preset.label;
		}
	}

	switch (operator) {
		case 'is':
			return value || '...';
		case 'after':
			return sprintf(
				/* translators: %s: date */
				__('after %s', 'rawtype-order-exporter-woocommerce'),
				value || '...',
			);
		case 'before':
			return sprintf(
				/* translators: %s: date */
				__('before %s', 'rawtype-order-exporter-woocommerce'),
				value || '...',
			);
		case 'between':
			if (Array.isArray(value) && value[0] && value[1]) {
				return value[0] + ' — ' + value[1];
			}
			return '...';
		default:
			return '...';
	}
}
