import { __ } from '@wordpress/i18n';
import { Plus, Trash2, ChevronUp, ChevronDown } from 'lucide-react';
import AsyncMultiSelect from '../components/AsyncMultiSelect';
import TagInput from '../components/TagInput';
import SchemaSections from '../components/SchemaSections';

/**
 * Condition types come from the server (EDFW_Helper::capabilities), so an add-on can
 * register a new type without this file changing. Labels and placeholders are
 * translated in PHP — passing a variable to __() here would produce a string the
 * i18n tooling cannot extract, so those strings could never actually be translated.
 */
const FALLBACK_TYPES = {
	product: { label: 'Product', placeholder: 'Any product', source: 'search' },
};

function randomKey() {
	return 'r' + Math.random().toString( 36 ).slice( 2, 8 );
}

function ConditionValue( { cond, meta, def, onChange } ) {
	const vals = cond.vals || [];
	const placeholder = def?.placeholder || __( 'Any', 'wpactpro-estimated-delivery-date' );

	switch ( def?.source ) {
		case 'zones': {
			const opts = Object.entries( meta.zones || {} ).map( ( [ value, label ] ) => ( { value, label } ) );
			return <AsyncMultiSelect staticOptions={ opts } values={ vals } onChange={ onChange } placeholder={ placeholder } />;
		}
		case 'methods': {
			const opts = Object.entries( meta.methods || {} ).map( ( [ value, m ] ) => ( { value, label: m.title || value } ) );
			return <AsyncMultiSelect staticOptions={ opts } values={ vals } onChange={ onChange } placeholder={ placeholder } />;
		}
		case 'options':
			return <AsyncMultiSelect staticOptions={ def.options || [] } values={ vals } onChange={ onChange } placeholder={ placeholder } />;
		case 'tags':
			return <TagInput values={ vals } onChange={ onChange } placeholder={ placeholder } hint={ def.hint } />;
		default:
			return <AsyncMultiSelect type={ cond.type } values={ vals } onChange={ onChange } placeholder={ placeholder } />;
	}
}

export default function RulesTab( { state, dispatch, accent } ) {
	const rules = state.rules || {};
	const keys = Object.keys( rules );
	const meta = state.meta || {};

	const conditionTypes = state.capabilities?.ruleConditions && Object.keys( state.capabilities.ruleConditions ).length
		? state.capabilities.ruleConditions
		: FALLBACK_TYPES;
	const typeKeys = Object.keys( conditionTypes );
	const defaultType = ( slug ) => ( typeKeys.includes( slug ) ? slug : typeKeys[ 0 ] );

	const patchRule = ( key, patch ) => dispatch( { type: 'SET_RULE', key, patch } );
	const setConds = ( key, conditions ) => patchRule( key, { conditions } );
	const removeRule = ( key ) => dispatch( { type: 'REMOVE_RULE', key } );
	const addRule = () => dispatch( {
		type: 'ADD_RULE',
		key: randomKey(),
		rule: { conditions: [ { type: defaultType( 'product_cat' ), op: 'is', vals: [] } ], min: '3', max: '7', scheduled: '' },
	} );

	const moveRule = ( key, dir ) => {
		const order = [ ...keys ];
		const i = order.indexOf( key );
		const j = i + dir;
		if ( j < 0 || j >= order.length ) return;
		[ order[ i ], order[ j ] ] = [ order[ j ], order[ i ] ];
		const next = {};
		order.forEach( ( k ) => { next[ k ] = rules[ k ]; } );
		dispatch( { type: 'SET_RULES', rules: next } );
	};

	return (
		<>
			<div className="edfw-card">
				<div className="edfw-card__title">{ __( 'Delivery rules', 'wpactpro-estimated-delivery-date' ) }</div>
				<div className="edfw-card__desc" style={ { marginBottom: 18 } }>{ __( 'Build each rule from one or more conditions. A rule matches only when ALL its conditions are true (AND). Use “is not” to exclude, and leave a value on “Any” to match everything — a rule like “Product is Any → 2–5” is your store-wide default. The most specific matching rule wins automatically: a Product rule beats a Category/Class rule beats an “Any” default, so you don’t need to order them. Use ↑ / ↓ only to break ties between equally-specific rules. A product matching no rule shows no estimate. Set a scheduled start date to count business days from that date instead of today — useful for pre-orders, restocks and launches.', 'wpactpro-estimated-delivery-date' ) }</div>

				{ keys.length === 0 && (
					<p className="edfw-empty">{ __( 'No rules yet. Add one to show a delivery estimate.', 'wpactpro-estimated-delivery-date' ) }</p>
				) }

				{ keys.map( ( key, ri ) => {
					const rule = rules[ key ];
					const conditions = Array.isArray( rule.conditions ) ? rule.conditions : [];
					const setCond = ( idx, patch ) => setConds( key, conditions.map( ( c, i ) => ( i === idx ? { ...c, ...patch } : c ) ) );
					const addCond = () => setConds( key, [ ...conditions, { type: defaultType( 'zone' ), op: 'is', vals: [] } ] );
					const removeCond = ( idx ) => setConds( key, conditions.filter( ( _, i ) => i !== idx ) );

					return (
						<div className="edfw-rulecard" key={ key }>
							<div className="edfw-rule-reorder">
								<button className="edfw-mini" disabled={ ri === 0 } aria-label={ __( 'Move up', 'wpactpro-estimated-delivery-date' ) } onClick={ () => moveRule( key, -1 ) }><ChevronUp size={ 15 } /></button>
								<button className="edfw-mini" disabled={ ri === keys.length - 1 } aria-label={ __( 'Move down', 'wpactpro-estimated-delivery-date' ) } onClick={ () => moveRule( key, 1 ) }><ChevronDown size={ 15 } /></button>
							</div>

							<div className="edfw-rule-body">
								{ conditions.map( ( c, idx ) => (
									<div className="edfw-condrow" key={ idx }>
										{ idx > 0 && <span className="edfw-and">{ __( 'AND', 'wpactpro-estimated-delivery-date' ) }</span> }
										<select className="edfw-select edfw-cond-type" value={ c.type } onChange={ ( e ) => setCond( idx, { type: e.target.value, vals: [] } ) }>
											{ typeKeys.map( ( v ) => <option key={ v } value={ v }>{ conditionTypes[ v ]?.label || v }</option> ) }
										</select>
										<select className="edfw-select edfw-cond-op" value={ c.op || 'is' } onChange={ ( e ) => setCond( idx, { op: e.target.value } ) }>
											<option value="is">{ __( 'is', 'wpactpro-estimated-delivery-date' ) }</option>
											<option value="is_not">{ __( 'is not', 'wpactpro-estimated-delivery-date' ) }</option>
										</select>
										<ConditionValue cond={ c } meta={ meta } def={ conditionTypes[ c.type ] } onChange={ ( vals ) => setCond( idx, { vals } ) } />
										{ conditions.length > 1 && (
											<button className="edfw-x" aria-label={ __( 'Remove condition', 'wpactpro-estimated-delivery-date' ) } onClick={ () => removeCond( idx ) }>✕</button>
										) }
									</div>
								) ) }

								<button className="edfw-andbtn" onClick={ addCond }>
									<Plus size={ 14 } />{ __( 'AND another condition', 'wpactpro-estimated-delivery-date' ) }
								</button>

								<div className="edfw-rule-foot">
									<div className="edfw-rulefield edfw-rulefield--sm">
										<span className="edfw-field-label">{ __( 'Min days', 'wpactpro-estimated-delivery-date' ) }</span>
										<input className="edfw-input" type="number" min="0" value={ rule.min ?? 2 } onChange={ ( e ) => patchRule( key, { min: e.target.value } ) } />
									</div>
									<div className="edfw-rulefield edfw-rulefield--sm">
										<span className="edfw-field-label">{ __( 'Max days', 'wpactpro-estimated-delivery-date' ) }</span>
										<input className="edfw-input" type="number" min="0" value={ rule.max ?? 5 } onChange={ ( e ) => patchRule( key, { max: e.target.value } ) } />
									</div>
									<div className="edfw-rulefield">
										<span className="edfw-field-label">{ __( 'Scheduled start (optional)', 'wpactpro-estimated-delivery-date' ) }</span>
										<input className="edfw-input" type="date" value={ rule.scheduled || '' } onChange={ ( e ) => patchRule( key, { scheduled: e.target.value } ) } />
									</div>
									<div style={ { flex: 1 } } />
									<button className="edfw-icon-btn edfw-icon-btn--danger" aria-label={ __( 'Remove rule', 'wpactpro-estimated-delivery-date' ) } onClick={ () => removeRule( key ) }>
										<Trash2 size={ 16 } />
									</button>
								</div>
							</div>
						</div>
					);
				} ) }

				<button className="edfw-addbtn" onClick={ addRule }>
					<Plus size={ 16 } />{ __( 'Add rule', 'wpactpro-estimated-delivery-date' ) }
				</button>
			</div>
			<SchemaSections tab="rules" state={ state } dispatch={ dispatch } accent={ accent } />
		</>
	);
}
