import React, { useState } from 'react';
import { Popover } from 'antd';
import {
	LEASE_VEHICLE_BRAND_MODEL_CATALOG,
	formatBrandModelPair,
} from '../lease-contract-management/lease-order-vars.js';
import {
	VEHICLE_BINDING_ALL_BRAND,
	isAllVehicleBindings,
	vehicleBindingKey,
} from './vehicle-binding-utils.js';

function SearchIcon() {
	return React.createElement('svg', {
		width: 16,
		height: 16,
		viewBox: '0 0 24 24',
		fill: 'none',
		stroke: 'currentColor',
		strokeWidth: 2,
		'aria-hidden': true,
	},
		React.createElement('circle', { cx: 11, cy: 11, r: 7 }),
		React.createElement('path', { d: 'M20 20l-3-3' })
	);
}

function CloseIcon() {
	return React.createElement('svg', {
		width: 14,
		height: 14,
		viewBox: '0 0 24 24',
		fill: 'none',
		stroke: 'currentColor',
		strokeWidth: 2,
		'aria-hidden': true,
	},
		React.createElement('path', { d: 'M18 6L6 18M6 6l12 12' })
	);
}

function ChevronDownIcon() {
	return React.createElement('svg', {
		width: 14,
		height: 14,
		viewBox: '0 0 24 24',
		fill: 'none',
		stroke: 'currentColor',
		strokeWidth: 2,
		'aria-hidden': true,
	},
		React.createElement('path', { d: 'M6 9l6 6 6-6' })
	);
}

export default function VehicleBrandModelPicker(props) {
	var value = props.value || [];
	var onChange = props.onChange;
	var openState = useState(false);
	var activeBrandState = useState(VEHICLE_BINDING_ALL_BRAND);
	var queryState = useState('');
	var open = openState[0];
	var setOpen = openState[1];
	var activeBrand = activeBrandState[0];
	var setActiveBrand = activeBrandState[1];
	var query = queryState[0];
	var setQuery = queryState[1];
	var searchText = query.trim();
	var isSearchMode = searchText.length > 0;
	var isAllMode = isAllVehicleBindings(value);
	var isBrowsingAllTab = !isSearchMode && activeBrand === VEHICLE_BINDING_ALL_BRAND;
	var resolvedBrand = (activeBrand && activeBrand !== VEHICLE_BINDING_ALL_BRAND)
		? activeBrand
		: (value.length > 0
			? value[0].brand
			: LEASE_VEHICLE_BRAND_MODEL_CATALOG[0].brand);
	var searchLower = searchText.toLowerCase();

	var displayModels = isSearchMode
		? LEASE_VEHICLE_BRAND_MODEL_CATALOG.reduce(function (list, item) {
			return list.concat(item.models.map(function (model) {
				return { brand: item.brand, model: model };
			}));
		}, []).filter(function (item) {
			var label = formatBrandModelPair(item.brand, item.model);
			return label.toLowerCase().indexOf(searchLower) >= 0
				|| item.brand.toLowerCase().indexOf(searchLower) >= 0;
		})
		: (function () {
			var group = LEASE_VEHICLE_BRAND_MODEL_CATALOG.find(function (node) {
				return node.brand === resolvedBrand;
			});
			if (!group) return [];
			return group.models.map(function (model) {
				return { brand: group.brand, model: model };
			});
		})();

	function handleOpenChange(nextOpen) {
		setOpen(nextOpen);
		if (nextOpen) {
			if (isAllVehicleBindings(value)) {
				setActiveBrand(VEHICLE_BINDING_ALL_BRAND);
			} else if (value.length > 0) {
				setActiveBrand(value[0].brand);
			} else {
				setActiveBrand(VEHICLE_BINDING_ALL_BRAND);
			}
		} else {
			setQuery('');
		}
	}

	function selectAllBrands() {
		onChange([]);
		setActiveBrand(VEHICLE_BINDING_ALL_BRAND);
		setQuery('');
	}

	function isSelected(brand, model) {
		var key = vehicleBindingKey({ brand: brand, model: model });
		return value.some(function (item) {
			return vehicleBindingKey(item) === key;
		});
	}

	function togglePair(brand, model) {
		var key = vehicleBindingKey({ brand: brand, model: model });
		if (isSelected(brand, model)) {
			var next = value.filter(function (item) {
				return vehicleBindingKey(item) !== key;
			});
			onChange(next);
			if (!next.length) {
				setActiveBrand(VEHICLE_BINDING_ALL_BRAND);
			}
			return;
		}
		onChange(isAllMode ? [{ brand: brand, model: model }] : value.concat([{ brand: brand, model: model }]));
		setActiveBrand(brand);
	}

	function removeBinding(binding) {
		var key = vehicleBindingKey(binding);
		var next = value.filter(function (item) {
			return vehicleBindingKey(item) !== key;
		});
		onChange(next);
		if (!next.length) {
			setActiveBrand(VEHICLE_BINDING_ALL_BRAND);
		}
	}

	function clearAll(event) {
		event.preventDefault();
		event.stopPropagation();
		selectAllBrands();
	}

	var panelContent = React.createElement('div', {
		className: 'vm-operate-city-edit-body vm-operate-city-picker-panel ct-vehicle-brand-model-panel',
	},
		React.createElement('label', { className: 'vm-operate-city-edit-search' },
			React.createElement('span', { className: 'vm-operate-city-edit-search-icon', 'aria-hidden': true },
				React.createElement(SearchIcon)
			),
			React.createElement('input', {
				type: 'text',
				className: 'vm-operate-city-edit-search-input',
				value: query,
				placeholder: '输入品牌或型号名称快速筛选',
				'aria-label': '筛选品牌型号',
				autoComplete: 'off',
				onChange: function (e) { setQuery(e.target.value); },
			}),
			query
				? React.createElement('button', {
					type: 'button',
					className: 'vm-operate-city-edit-search-clear',
					onClick: function (e) {
						e.preventDefault();
						e.stopPropagation();
						setQuery('');
					},
					'aria-label': '清空搜索',
				}, React.createElement(CloseIcon))
				: null
		),
		value.length > 0
			? React.createElement('div', { className: 'vm-operate-city-edit-selected', 'aria-live': 'polite' },
				React.createElement('span', { className: 'vm-operate-city-edit-selected-label' }, '已选'),
				React.createElement('div', { className: 'ct-vehicle-brand-model-panel__selected-list' },
					value.map(function (item) {
						var label = formatBrandModelPair(item.brand, item.model);
						return React.createElement('span', {
							key: vehicleBindingKey(item),
							className: 'ct-vehicle-brand-model-panel__selected-tag',
						},
							label,
							React.createElement('button', {
								type: 'button',
								'aria-label': '移除' + label,
								onMouseDown: function (e) { e.preventDefault(); },
								onClick: function () { removeBinding(item); },
							}, React.createElement(CloseIcon))
						);
					})
				)
			)
			: isAllMode
				? React.createElement('div', { className: 'vm-operate-city-edit-selected', 'aria-live': 'polite' },
					React.createElement('span', { className: 'vm-operate-city-edit-selected-label' }, '已选'),
					React.createElement('div', { className: 'ct-vehicle-brand-model-panel__selected-list' },
						React.createElement('span', {
							className: 'ct-vehicle-brand-model-panel__selected-tag ct-vehicle-brand-model-panel__selected-tag--all',
						}, '全部')
					)
				)
				: null,
		React.createElement('div', {
			className: 'vm-operate-city-edit-main' + (isSearchMode ? ' is-search' : ''),
		},
			!isSearchMode
				? React.createElement('div', { className: 'vm-operate-city-edit-step vm-operate-city-edit-step--province' },
					React.createElement('span', { className: 'vm-operate-city-step-label' }, '品牌'),
					React.createElement('div', {
						className: 'vm-operate-city-edit-chips',
						role: 'tablist',
						'aria-label': '品牌列表',
					},
						React.createElement('button', {
							key: VEHICLE_BINDING_ALL_BRAND,
							type: 'button',
							role: 'tab',
							'aria-selected': isBrowsingAllTab,
							className: 'vm-operate-city-chip ct-vehicle-brand-model-picker__all-brand'
								+ (isBrowsingAllTab ? ' active' : ''),
							onClick: selectAllBrands,
						}, '全部'),
						LEASE_VEHICLE_BRAND_MODEL_CATALOG.map(function (item) {
							var active = activeBrand === item.brand;
							return React.createElement('button', {
								key: item.brand,
								type: 'button',
								role: 'tab',
								'aria-selected': active,
								className: 'vm-operate-city-chip' + (active ? ' active' : ''),
								onClick: function () {
									setActiveBrand(item.brand);
									setQuery('');
								},
							}, item.brand);
						})
					)
				)
				: null,
			React.createElement('div', { className: 'vm-operate-city-edit-step vm-operate-city-edit-step--city' },
				React.createElement('span', { className: 'vm-operate-city-step-label' },
					isSearchMode ? ('搜索结果（' + displayModels.length + '）') : '型号',
				),
				React.createElement('div', {
					className: 'vm-operate-city-edit-chips',
					role: 'listbox',
					'aria-label': '型号列表',
					'aria-multiselectable': true,
				},
					isBrowsingAllTab && isAllMode
						? React.createElement('p', { className: 'vm-operate-city-empty ct-vehicle-brand-model-picker__all-hint' },
							'当前章节适用于全部品牌、全部型号；如需限定车型，请先选择左侧品牌'
						)
						: displayModels.length === 0
							? React.createElement('p', { className: 'vm-operate-city-empty' },
								isSearchMode ? '未找到匹配型号，请换个关键词' : '暂无型号'
							)
							: displayModels.map(function (item) {
								var checked = isSelected(item.brand, item.model);
								return React.createElement('button', {
									key: vehicleBindingKey(item),
									type: 'button',
									role: 'option',
									'aria-selected': checked,
									className: 'vm-operate-city-chip' + (checked ? ' active' : ''),
									onClick: function () { togglePair(item.brand, item.model); },
								}, item.model);
							})
				)
			)
		)
	);

	return React.createElement('div', { className: 'vm-operate-city-field ct-vehicle-brand-model-picker' },
		React.createElement(Popover, {
			trigger: 'click',
			placement: 'bottomLeft',
			open: open,
			onOpenChange: handleOpenChange,
			overlayClassName: 'ct-vehicle-brand-model-popover',
			getPopupContainer: function () { return document.body; },
			content: panelContent,
		},
			React.createElement('div', {
				className: 'vm-filter-picker-control ct-vehicle-brand-model-picker__trigger' + (open ? ' open' : ''),
				role: 'combobox',
				'aria-label': '品牌型号',
				'aria-expanded': open,
				tabIndex: 0,
				onKeyDown: function (e) {
					if (e.key === 'Enter' || e.key === ' ') {
						e.preventDefault();
						setOpen(true);
					}
				},
			},
				isAllMode
					? React.createElement('span', {
						className: 'ct-vehicle-brand-model-picker__summary-tag ct-vehicle-brand-model-picker__summary-tag--all',
						title: '全部品牌、全部型号',
					}, '全部')
					: value.length > 0
						? React.createElement('div', { className: 'ct-vehicle-brand-model-picker__summary-tags' },
							value.map(function (item) {
								var label = formatBrandModelPair(item.brand, item.model);
								return React.createElement('span', {
									key: vehicleBindingKey(item),
									className: 'ct-vehicle-brand-model-picker__summary-tag',
									title: label,
								},
									React.createElement('span', { className: 'ct-vehicle-brand-model-picker__summary-tag-brand' }, item.brand),
									React.createElement('span', { className: 'ct-vehicle-brand-model-picker__summary-tag-sep', 'aria-hidden': true }, '·'),
									React.createElement('span', { className: 'ct-vehicle-brand-model-picker__summary-tag-model' }, item.model)
								);
							})
						)
						: React.createElement('span', {
							className: 'vm-filter-picker-input ct-vehicle-brand-model-picker__summary is-placeholder',
						}, '请选择品牌 / 型号'),
				!isAllMode && value.length > 0
					? React.createElement('button', {
						type: 'button',
						className: 'vm-filter-picker-clear',
						onClick: clearAll,
						'aria-label': '清空品牌型号',
						tabIndex: -1,
					}, React.createElement(CloseIcon))
					: null,
				React.createElement('span', { className: 'vm-filter-picker-chevron' },
					React.createElement(ChevronDownIcon)
				)
			)
		)
	);
}
