/*!
 * Built by ShiftSoftware
 * Copyright (c)
 */
import { Host, h } from "@stencil/core";
import cn from "../../global/lib/cn";
import { getInputLocalization } from "../../features/form-hook/index";
import { FormInputLabel } from "./components/form-input-label";
import { FormInputPrefix } from "./components/form-input-prefix";
import { FormErrorMessage } from "./components/form-error-message";
import { decodeTimeOffset } from "../../global/lib/decode-time-offset";
import { format, parse } from "date-fns";
const partKeyPrefix = 'form-picker-';
export class FormPickerInput {
    constructor() {
        this.inputProps = {};
        this.type = 'datetime-local';
        this.localization = {};
        this.iconPosition = 'end';
        this.prefixWidth = 0;
        this.updateDisplayValue = () => {
            var _a;
            this.displayedValue = ((_a = this.inputRef) === null || _a === void 0 ? void 0 : _a.value) || '';
            if (this.displayedValue && (this.formatter || this.format)) {
                if (this.formatter)
                    this.displayedValue = this.formatter(this.displayedValue);
                if (this.format)
                    this.displayedValue = format(new Date(this.displayedValue), this.format);
                this.form.context[`${this.name}-format`] = this.displayedValue;
            }
            else {
                delete this.form.context[`${this.name}-format`];
            }
        };
        this.onInputChange = (event) => {
            const target = event.target;
            if (this.inputRef)
                this.inputRef.value = target.value;
            this.updateDisplayValue();
        };
        this.onInputClick = (event) => {
            event.preventDefault();
            if (this.inputRef) {
                // Try showPicker first (works on Chrome, Firefox, modern Safari)
                if (typeof this.inputRef.showPicker === 'function') {
                    try {
                        this.inputRef.showPicker();
                        return;
                    }
                    catch (e) {
                        // Fall through to alternative methods
                    }
                }
                // Fallback for iOS and older browsers
                this.inputRef.focus();
                this.inputRef.click();
            }
        };
        this.onInputBlur = () => {
            // Ensure picker closes on blur for Safari
            if (this.inputRef) {
                this.inputRef.blur();
            }
        };
        this.parseToDate = (v) => {
            if (!v)
                return false;
            if (typeof v !== 'string')
                return v;
            if (this.format) {
                return parse(v, this.format, new Date());
            }
            return new Date(v);
        };
        this.fmt = (value) => {
            if (!value)
                return '';
            const dateValue = value instanceof Date ? value : this.parseToDate(value);
            return this.format ? format(dateValue, this.format) : dateValue.toISOString();
        };
        this.withSlots = (template) => {
            const resolvedMin = Array.isArray(this.min) ? decodeTimeOffset({ offsets: this.min, type: this.type }) : this.min;
            const resolvedMax = Array.isArray(this.max) ? decodeTimeOffset({ offsets: this.max, type: this.type }) : this.max;
            const minDate = this.parseToDate(resolvedMin);
            const maxDate = this.parseToDate(resolvedMax);
            let base = typeof template === 'string' ? template : '';
            if (minDate)
                base = base.replace('$minDate$', this.fmt(minDate));
            if (maxDate)
                base = base.replace('$maxDate$', this.fmt(maxDate));
            return base;
        };
        this.partialValidation = (v) => {
            const resolvedMin = Array.isArray(this.min) ? decodeTimeOffset({ offsets: this.min, type: this.type }) : this.min;
            const resolvedMax = Array.isArray(this.max) ? decodeTimeOffset({ offsets: this.max, type: this.type }) : this.max;
            const minDate = this.parseToDate(resolvedMin);
            const maxDate = this.parseToDate(resolvedMax);
            const allowEmpty = (value) => value === null || value === undefined || value === '';
            // Only min
            if (minDate && !maxDate) {
                v = v.test('min-date', 'minMessage', (value) => {
                    if (allowEmpty(value))
                        return true;
                    const current = this.parseToDate(value);
                    if (!current || Number.isNaN(current.getTime()))
                        return false;
                    return current.getTime() >= minDate.getTime();
                });
            }
            // Only max
            if (!minDate && maxDate) {
                v = v.test('max-date', 'maxMessage', (value) => {
                    if (allowEmpty(value))
                        return true;
                    const current = this.parseToDate(value);
                    if (!current || Number.isNaN(current.getTime()))
                        return false;
                    return current.getTime() <= maxDate.getTime();
                });
            }
            // Between
            if (minDate && maxDate) {
                v = v.test('between-date', 'betweenMessage', (value) => {
                    if (allowEmpty(value))
                        return true;
                    const current = this.parseToDate(value);
                    if (!current || Number.isNaN(current.getTime()))
                        return false;
                    const time = current.getTime();
                    return time >= minDate.getTime() && time <= maxDate.getTime();
                });
            }
            return v;
        };
    }
    async componentWillLoad() {
        this.form.subscribe(this.name, this);
        this.onStaticValueChange(this.staticValue, false);
        this.updateDisplayValue();
    }
    async onStaticValueChange(newStaticValue, notInitialLoad = true) {
        if (!!newStaticValue) {
            this.defaultValue = newStaticValue;
            this.inputRef.value = newStaticValue;
        }
        else if (notInitialLoad) {
            this.defaultValue = '';
            this.inputRef.value = '';
        }
        this.updateDisplayValue();
    }
    async componentDidLoad() {
        const prefix = this.el.getElementsByClassName('prefix')[0];
        this.prefixWidth = prefix ? prefix.getBoundingClientRect().width : 0;
        this.inputRef = this.el.getElementsByClassName(partKeyPrefix + this.name)[0];
        this.updateDisplayValue();
    }
    async disconnectedCallback() {
        this.form.unsubscribe(this.name);
    }
    reset(newValue) {
        const value = newValue || this.defaultValue || '';
        this.inputRef.value = value;
        this.updateDisplayValue();
    }
    render() {
        var _a, _b;
        const { disabled, isRequired, meta, isError, errorMessage } = this.form.getInputState(this.name);
        const [locale] = this.form.getFormLocale();
        const part = partKeyPrefix + this.name;
        const { label, placeholder, errorTextMessage } = getInputLocalization(this, meta, errorMessage);
        const isDisabled = disabled || this.isLoading || !!this.staticValue || this.isDisabled;
        const isRtl = ((_a = locale === null || locale === void 0 ? void 0 : locale.sharedFormLocales) === null || _a === void 0 ? void 0 : _a.direction) === 'rtl';
        const isIconStart = this.iconPosition === 'start';
        const iconPaddingSide = isIconStart ? (isRtl ? 'paddingRight' : 'paddingLeft') : isRtl ? 'paddingLeft' : 'paddingRight';
        const iconClass = cn('form-input-icon', {
            'form-input-icon-start': isIconStart,
            'form-input-icon-end': !isIconStart,
            'form-input-icon-interactive': !!this.iconAction,
        });
        const renderIcon = () => this.iconAction ? (h("button", { type: "button", disabled: isDisabled, onClick: this.iconAction, part: `${this.name}-icon form-input-icon`, class: iconClass }, this.icon)) : (h("span", { part: `${this.name}-icon form-input-icon`, class: iconClass }, this.icon));
        return (h(Host, { key: '41642c79e3344981ab8d44503933e8de5b1e266f', translate: "no" }, h("label", { key: '6575d57adabc4a4681624f9bb0d7a6bcab4b7a1d', part: this.name, id: this.wrapperId, class: cn('form-input-label-container', this.wrapperClass, { disabled: isDisabled }) }, h(FormInputLabel, { key: '3c073e7a1a66dbf97045221af27512ebaa52439b', isRequired: isRequired, label: label }), h("div", { key: '1470af0d443481a1a13ac58ed3d20cd819f4c9a8', part: `${this.name}-container form-input-container relative`, class: "form-input-container" }, h(FormInputPrefix, { key: '161ee44ff9af294493c13079db2138f4e78ced34', name: this.name, direction: (_b = locale === null || locale === void 0 ? void 0 : locale.sharedFormLocales) === null || _b === void 0 ? void 0 : _b.direction, prefix: this.inputPrefix }), h("input", { key: 'dda51f4751fa1fdd57da443c5c283ed215f351d3', type: "text", readonly: true, tabIndex: -1, part: `form-input`, disabled: isDisabled, value: this.displayedValue, onClick: this.onInputClick, onKeyDown: e => e.preventDefault(), placeholder: placeholder || (meta === null || meta === void 0 ? void 0 : meta.placeholder), style: Object.assign(Object.assign(Object.assign({}, (this.prefixWidth ? { [isRtl ? 'paddingRight' : 'paddingLeft']: `${this.prefixWidth}px` } : {})), (this.icon ? { [iconPaddingSide]: '40px' } : {})), { pointerEvents: 'none' }), class: cn('form-input-style enabled:cursor-pointer', {
                'form-input-error-style': isError,
            }) }), h("input", Object.assign({ key: 'cee456f43f6d7f52aeee287b8866b949efe2653e', type: this.type, name: this.name }, this.inputProps, { onBlur: this.onInputBlur, onClick: this.onInputClick, onInput: this.onInputChange, part: `${this.name}-input ${part}`, class: cn('shadow-input size-full absolute top-0 left-0 opacity-0 cursor-pointer', part), min: Array.isArray(this.min) ? decodeTimeOffset({ offsets: this.min, type: this.type }) : this.min, max: Array.isArray(this.max) ? decodeTimeOffset({ offsets: this.max, type: this.type }) : this.max })), this.icon && renderIcon()), h(FormErrorMessage, { key: '977a6d3726902f9e92cdbcf96d0a38589528e941', name: this.name, isError: isError, errorMessage: errorTextMessage }))));
    }
    static get is() { return "form-picker-input"; }
    static get originalStyleUrls() {
        return {
            "$": ["form-inputs.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["form-inputs.css"]
        };
    }
    static get properties() {
        return {
            "name": {
                "type": "string",
                "attribute": "name",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "format": {
                "type": "string",
                "attribute": "format",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "wrapperId": {
                "type": "string",
                "attribute": "wrapper-id",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "isLoading": {
                "type": "boolean",
                "attribute": "is-loading",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "isDisabled": {
                "type": "boolean",
                "attribute": "is-disabled",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "form": {
                "type": "unknown",
                "attribute": "form",
                "mutable": false,
                "complexType": {
                    "original": "FormHook<any>",
                    "resolved": "FormHook<any>",
                    "references": {
                        "FormHook": {
                            "location": "import",
                            "path": "~features/form-hook/form-hook",
                            "id": "src/features/form-hook/form-hook.ts::FormHook"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "inputPrefix": {
                "type": "string",
                "attribute": "input-prefix",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "wrapperClass": {
                "type": "string",
                "attribute": "wrapper-class",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "staticValue": {
                "type": "string",
                "attribute": "static-value",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "inputProps": {
                "type": "any",
                "attribute": "input-props",
                "mutable": false,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "{}"
            },
            "max": {
                "type": "string",
                "attribute": "max",
                "mutable": false,
                "complexType": {
                    "original": "string | number[]",
                    "resolved": "number[] | string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "min": {
                "type": "string",
                "attribute": "min",
                "mutable": false,
                "complexType": {
                    "original": "string | number[]",
                    "resolved": "number[] | string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "type": {
                "type": "string",
                "attribute": "type",
                "mutable": false,
                "complexType": {
                    "original": "DateTypes",
                    "resolved": "\"date\" | \"datetime-local\" | \"time\"",
                    "references": {
                        "DateTypes": {
                            "location": "import",
                            "path": "~lib/decode-time-offset",
                            "id": "src/global/lib/decode-time-offset.ts::DateTypes"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'datetime-local'"
            },
            "defaultValue": {
                "type": "string",
                "attribute": "default-value",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "formatter": {
                "type": "unknown",
                "attribute": "formatter",
                "mutable": false,
                "complexType": {
                    "original": "(value: string) => string",
                    "resolved": "(value: string) => string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "localization": {
                "type": "unknown",
                "attribute": "localization",
                "mutable": false,
                "complexType": {
                    "original": "FormInputLocalization",
                    "resolved": "{ [lang: string]: { label?: string; placeholder?: string; require?: string; format?: string; minMessage: string; maxMessage: string; betweenMessage: string; }; }",
                    "references": {
                        "FormInputLocalization": {
                            "location": "import",
                            "path": "~features/form-hook",
                            "id": "src/features/form-hook/index.ts::FormInputLocalization"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "defaultValue": "{}"
            },
            "icon": {
                "type": "any",
                "attribute": "icon",
                "mutable": false,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "iconAction": {
                "type": "unknown",
                "attribute": "icon-action",
                "mutable": false,
                "complexType": {
                    "original": "() => void",
                    "resolved": "() => void",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "iconPosition": {
                "type": "string",
                "attribute": "icon-position",
                "mutable": false,
                "complexType": {
                    "original": "'start' | 'end'",
                    "resolved": "\"end\" | \"start\"",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'end'"
            }
        };
    }
    static get states() {
        return {
            "prefixWidth": {},
            "displayedValue": {}
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "staticValue",
                "methodName": "onStaticValueChange"
            }];
    }
}
