var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
        r = Reflect.decorate(decorators, target, key, desc);
    else
        for (var i = decorators.length - 1; i >= 0; i--)
            if (d = decorators[i])
                r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { h, Host, } from "@stencil/core";
import { Operator, SelectLimeTypes as Limetypes, } from "@limetech/lime-web-components";
import { getPropertyFromPath } from "../property-resolution";
import { getActualPropertyType, mapPropertyTypeToPickerType, } from "../type-resolution";
/**
 * Query Value Input Component
 *
 * Renders an appropriate input control based on the property type and operator.
 * This component automatically adapts its UI to match the data type of the selected
 * property, providing a better user experience and data validation.
 *
 * Supported input types:
 * - **String/Text**: Standard text input field
 * - **Integer/Decimal**: Number input with appropriate step values
 * - **Date**: Date picker returning ISO date strings
 * - **Time**: Time input field
 * - **Boolean (yesno)**: True/False dropdown
 * - **Option**: Dropdown populated with valid options from property definition
 * - **IN operator**: Comma-separated input for multiple values (any type)
 * - **Placeholder mode**: Select properties from active object using %activeObject%
 *
 * The component handles type conversions automatically:
 * - Numbers are parsed from string inputs
 * - Dates are converted to/from ISO strings
 * - Booleans are converted to/from strings for dropdown compatibility
 *
 * @private
 */
export class LimeQueryValueInput {
    constructor() {
        /**
         * Optional label for the input
         */
        this.label = 'Value';
        this.inputMode = 'value';
        this.handleTextChange = (event) => {
            event.stopPropagation();
            // Try to parse as number for number inputs
            const value = event.detail;
            const numValue = Number(value);
            if (!Number.isNaN(numValue) && value !== '') {
                this.change.emit(numValue);
            }
            else {
                this.change.emit(value);
            }
        };
        this.handleSelectChange = (event) => {
            event.stopPropagation();
            const detail = event.detail;
            if (Array.isArray(detail)) {
                this.change.emit(detail.map((o) => o.value));
            }
            else {
                this.change.emit(detail === null || detail === void 0 ? void 0 : detail.value);
            }
        };
        this.handleBooleanChange = (event) => {
            event.stopPropagation();
            const detail = event.detail;
            if (!Array.isArray(detail)) {
                // Convert string back to boolean
                this.change.emit((detail === null || detail === void 0 ? void 0 : detail.value) === 'true');
            }
        };
        this.handleDateChange = (event) => {
            event.stopPropagation();
            // Convert Date to ISO string for storage
            const date = event.detail;
            this.change.emit(date ? date.toISOString() : null);
        };
        this.handleMultiValueChange = (event) => {
            event.stopPropagation();
            // Split by comma and trim whitespace
            const values = event.detail
                .split(',')
                .map((v) => v.trim())
                .filter((v) => v.length > 0);
            this.change.emit(values);
        };
        this.handleModeToggle = () => {
            if (this.inputMode === 'value') {
                // Switching to placeholder mode
                this.inputMode = 'placeholder';
                // Emit placeholder value (empty initially)
                this.change.emit('%activeObject%');
            }
            else {
                // Switching to value mode
                this.inputMode = 'value';
                // Emit empty value
                this.change.emit('');
            }
        };
        this.handlePlaceholderPropertyChange = (event) => {
            event.stopPropagation();
            const propertyPath = event.detail;
            const placeholderValue = this.buildPlaceholderValue(propertyPath);
            this.change.emit(placeholderValue);
        };
    }
    componentWillLoad() {
        // Detect if the current value is a placeholder
        if (this.isPlaceholder(this.value)) {
            this.inputMode = 'placeholder';
        }
    }
    componentWillUpdate() {
        // Update mode if value changes externally
        if (this.isPlaceholder(this.value) &&
            this.inputMode !== 'placeholder') {
            this.inputMode = 'placeholder';
        }
        else if (!this.isPlaceholder(this.value) &&
            this.inputMode === 'placeholder') {
            this.inputMode = 'value';
        }
    }
    isPlaceholder(value) {
        return typeof value === 'string' && value.startsWith('%activeObject%');
    }
    parsePlaceholderPath(value) {
        if (!this.isPlaceholder(value)) {
            return '';
        }
        // Extract path after %activeObject%. (e.g., "%activeObject%.company.name" → "company.name")
        return value.replace(/^%activeObject%\.?/, '');
    }
    buildPlaceholderValue(propertyPath) {
        if (!propertyPath) {
            return '%activeObject%';
        }
        return `%activeObject%.${propertyPath}`;
    }
    render() {
        if (!this.operator) {
            return null;
        }
        return (h(Host, null, this.renderModeToggle(), this.renderInputByMode()));
    }
    renderInputByMode() {
        if (this.inputMode === 'placeholder') {
            return this.renderPlaceholderInput();
        }
        return this.renderValueInputByType();
    }
    renderModeToggle() {
        // Only show toggle if activeLimetype is set
        if (!this.activeLimetype) {
            return null;
        }
        const isPlaceholderMode = this.inputMode === 'placeholder';
        const buttonLabel = isPlaceholderMode ? 'Use Value' : 'Use Placeholder';
        const buttonIcon = isPlaceholderMode ? 'text' : 'link';
        return (h("limel-icon-button", { class: "mode-toggle", icon: buttonIcon, label: buttonLabel, onClick: this.handleModeToggle }));
    }
    renderPlaceholderInput() {
        const propertyPath = this.parsePlaceholderPath(this.value);
        return (h("div", { class: "placeholder-input" }, h("limebb-property-selector", { platform: this.platform, context: this.context, limetype: this.activeLimetype, label: "Active Object Property", value: propertyPath, required: false, helperText: "Select property from the active object", onChange: this.handlePlaceholderPropertyChange }), this.renderPlaceholderPreview()));
    }
    renderPlaceholderPreview() {
        if (!this.isPlaceholder(this.value)) {
            return;
        }
        return (h("div", { class: "placeholder-preview" }, h("limel-icon", { name: "info", size: "small" }), h("span", null, "Placeholder: ", this.value)));
    }
    renderValueInputByType() {
        // Special handling for IN operator - always use chip set for arrays
        if (this.operator === Operator.IN) {
            return this.renderMultiValueInput();
        }
        const property = this.getProperty();
        if (!property) {
            return this.renderTextInput();
        }
        // Resolve 'system' type to actual type
        const actualType = getActualPropertyType(property);
        switch (actualType) {
            case 'integer':
            case 'decimal': {
                return this.renderNumberInput(actualType);
            }
            case 'yesno': {
                return this.renderBooleanInput();
            }
            case 'option': {
                return this.renderOptionInput(property);
            }
            case 'date':
            case 'time':
            case 'timeofday':
            case 'year':
            case 'month':
            case 'quarter': {
                return this.renderDateTimeInput(actualType);
            }
            default: {
                return this.renderTextInput();
            }
        }
    }
    renderTextInput() {
        var _a;
        return (h("limel-input-field", { label: this.label, value: ((_a = this.value) === null || _a === void 0 ? void 0 : _a.toString()) || '', placeholder: "Enter value", onChange: this.handleTextChange }));
    }
    renderNumberInput(type) {
        var _a;
        const step = type === 'integer' ? 1 : 0.01;
        return (h("limel-input-field", { label: this.label, type: "number", value: ((_a = this.value) === null || _a === void 0 ? void 0 : _a.toString()) || '', step: step, onChange: this.handleTextChange }));
    }
    renderBooleanInput() {
        const options = [
            { text: 'True', value: 'true' },
            { text: 'False', value: 'false' },
        ];
        const valueAsString = this.value === true || this.value === 'true' ? 'true' : 'false';
        const selectedOption = options.find((o) => o.value === valueAsString);
        return (h("limel-select", { label: this.label, options: options, value: selectedOption, onChange: this.handleBooleanChange }));
    }
    renderOptionInput(property) {
        if (!property.options || property.options.length === 0) {
            return this.renderTextInput();
        }
        const options = property.options.map((opt) => ({
            text: opt.text || opt.key,
            value: opt.key,
        }));
        const selectedOption = options.find((o) => o.value === this.value);
        return (h("limel-select", { label: this.label, options: options, value: selectedOption, onChange: this.handleSelectChange }));
    }
    renderDateTimeInput(type) {
        // Convert string to Date if needed
        const dateValue = typeof this.value === 'string' ? new Date(this.value) : this.value;
        const pickerType = mapPropertyTypeToPickerType(type);
        return (h("limel-date-picker", { label: this.label, value: dateValue, type: pickerType, onChange: this.handleDateChange }));
    }
    renderMultiValueInput() {
        // For IN operator, allow comma-separated values
        const displayValue = Array.isArray(this.value)
            ? this.value.join(', ')
            : this.value || '';
        return (h("limel-input-field", { label: this.label + ' (comma-separated)', value: displayValue, placeholder: "e.g., won, lost, tender", onChange: this.handleMultiValueChange }));
    }
    getProperty() {
        if (!this.limetypes || !this.limetype || !this.propertyPath) {
            return;
        }
        return getPropertyFromPath(this.limetypes, this.limetype, this.propertyPath);
    }
    static get is() { return "limebb-lime-query-value-input"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["lime-query-value-input.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["lime-query-value-input.css"]
        };
    }
    static get properties() {
        return {
            "platform": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "LimeWebComponentPlatform",
                    "resolved": "LimeWebComponentPlatform",
                    "references": {
                        "LimeWebComponentPlatform": {
                            "location": "import",
                            "path": "@limetech/lime-web-components",
                            "id": "node_modules::LimeWebComponentPlatform",
                            "referenceLocation": "LimeWebComponentPlatform"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Platform service provider"
                },
                "getter": false,
                "setter": false
            },
            "context": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "LimeWebComponentContext",
                    "resolved": "LimeWebComponentContext",
                    "references": {
                        "LimeWebComponentContext": {
                            "location": "import",
                            "path": "@limetech/lime-web-components",
                            "id": "node_modules::LimeWebComponentContext",
                            "referenceLocation": "LimeWebComponentContext"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Component context"
                },
                "getter": false,
                "setter": false
            },
            "limetype": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The limetype being queried"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "limetype"
            },
            "activeLimetype": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string | undefined",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "The limetype of the active object (for %activeObject% placeholders)"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "active-limetype"
            },
            "propertyPath": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The property path (e.g., \"dealstatus\", \"company.name\")"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "property-path"
            },
            "operator": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "Operator",
                    "resolved": "Operator.AND | Operator.BEGINS | Operator.ENDS | Operator.EQUALS | Operator.GREATER | Operator.GREATER_OR_EQUAL | Operator.IN | Operator.LESS | Operator.LESS_OR_EQUAL | Operator.LIKE | Operator.NOT | Operator.NOT_EQUALS | Operator.OR",
                    "references": {
                        "Operator": {
                            "location": "import",
                            "path": "@limetech/lime-web-components",
                            "id": "node_modules::Operator",
                            "referenceLocation": "Operator"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The operator being used"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "operator"
            },
            "value": {
                "type": "any",
                "mutable": false,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The current value"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "value"
            },
            "label": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Optional label for the input"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "label",
                "defaultValue": "'Value'"
            }
        };
    }
    static get states() {
        return {
            "limetypes": {},
            "inputMode": {}
        };
    }
    static get events() {
        return [{
                "method": "change",
                "name": "change",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when the value changes"
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
}
__decorate([
    Limetypes()
], LimeQueryValueInput.prototype, "limetypes", void 0);
