import { Host, h, Fragment } from "@stencil/core";
import { deviceModeStore, userAddressStore } from "../../store/store";
import { ZInput } from "../internal-component/z-input";
import { ZDatePicker } from "../internal-component/z-date-picker";
import { ZButton } from "../internal-component/z-button";
import { ZInputArea } from "../internal-component/z-input-area";
import { getDialogEditorSchema } from "../../validations/schema";
import { useTranslation } from "../../utils/utils";
import { CUSTOM_FIELD_CONFIG_TYPE } from "../../store/zdesk.type";
export class DialogEditor {
    dialogType = 'input';
    label;
    headerTitle;
    field;
    value;
    allowEmpty = false;
    options;
    customSubmitName;
    limit;
    data = '';
    tempData = '';
    error = null;
    originalValue = '';
    cancel;
    save;
    async componentWillLoad() {
        // Store original value for change detection
        this.originalValue = this.value || '';
        if ((this.dialogType === 'full_address' || this.dialogType === 'order_address') && typeof this.value === 'object' && !Array.isArray(this.value)) {
            const defaultAddress = {
                name: this.value ? this.value.name || '' : '',
                phone_number: this.value ? this.value.phone_number || '' : '',
                address: this.value ? this.value.address || '' : '',
                province: this.value ? this.value.province || '' : '',
                district: this.value ? this.value.district || '' : '',
                sub_district: this.value ? this.value.sub_district || '' : '',
                zip_code: this.value ? this.value.zip_code || '' : '',
            };
            userAddressStore.set('userAddress', defaultAddress);
        }
        else {
            this.data = this.value || '';
        }
    }
    handleResetData = () => {
        if (this.dialogType === 'full_address' || this.dialogType === 'order_address') {
            userAddressStore.reset();
        }
        else {
            this.data = '';
        }
    };
    handleCancel = (event) => {
        event.stopPropagation();
        this.handleResetData();
        this.cancel.emit();
    };
    handleChange = (val) => {
        this.data = val;
    };
    handleChangeAddress = (value, key) => {
        const oldAddress = structuredClone(userAddressStore.get('userAddress'));
        const editAddress = {
            ...oldAddress,
            [key]: value,
        };
        switch (key) {
            case 'province':
                editAddress.district = '';
                editAddress.sub_district = '';
                editAddress.zip_code = '';
                break;
            case 'district':
                editAddress.sub_district = '';
                editAddress.zip_code = '';
                break;
            case 'sub_district':
                editAddress.zip_code = '';
                break;
        }
        userAddressStore.set('userAddress', editAddress);
    };
    hasDataChanged = () => {
        if (this.dialogType === 'full_address' || this.dialogType === 'order_address') {
            const currentAddress = userAddressStore.get('userAddress');
            const originalAddress = typeof this.originalValue === 'object' && !Array.isArray(this.originalValue) ? this.originalValue : null;
            if (!originalAddress) {
                // If there was no original address, check if current has any non-empty values
                return !!(currentAddress && (currentAddress.name !== '' ||
                    currentAddress.phone_number !== '' ||
                    currentAddress.address !== '' ||
                    currentAddress.province !== '' ||
                    currentAddress.district !== '' ||
                    currentAddress.sub_district !== '' ||
                    currentAddress.zip_code !== ''));
            }
            // Compare each field
            return (currentAddress.name !== originalAddress.name ||
                currentAddress.phone_number !== originalAddress.phone_number ||
                currentAddress.address !== originalAddress.address ||
                currentAddress.province !== originalAddress.province ||
                currentAddress.district !== originalAddress.district ||
                currentAddress.sub_district !== originalAddress.sub_district ||
                currentAddress.zip_code !== originalAddress.zip_code);
        }
        // For string and array types, simple comparison
        return this.data !== this.originalValue;
    };
    handleSubmit = () => {
        const t = useTranslation();
        const schema = getDialogEditorSchema(t, this.dialogType, this.field, this.allowEmpty);
        let values = this.dialogType === 'file' ? this.tempData : this.data;
        if (['full_address', 'order_address'].includes(this.dialogType)) {
            const address = userAddressStore.get('userAddress');
            values = {
                ...(this.dialogType === 'order_address' && address.name && address.name.trim().length && { name: address.name }),
                ...(this.dialogType === 'order_address' && address.phone_number && address.phone_number.trim().length && { phone_number: address.phone_number }),
                ...(address.address && address.address.trim().length && { address: address.address }),
                ...(address.province && address.province.trim().length && { province: address.province }),
                ...(address.district && address.district.trim().length && { district: address.district }),
                ...(address.sub_district && address.sub_district.trim().length && { sub_district: address.sub_district }),
                ...(address.zip_code && address.zip_code.trim().length && { zip_code: address.zip_code }),
            };
            values = Object.values(values).length ? values : null;
        }
        const validator = schema.safeParse({ [this.field]: values });
        if (!validator.success) {
            this.error = validator.error.issues[0].message;
        }
        else {
            this.error = null;
            this.save.emit(values);
            this.handleResetData();
        }
    };
    renderNormalInput() {
        let render = null;
        if (this.dialogType === CUSTOM_FIELD_CONFIG_TYPE.DATE && typeof this.data === 'string') {
            render = h(ZDatePicker, { autoFocus: true, id: this.field, label: this.label, value: this.data, onChange: val => this.handleChange(val), error: this.error });
        }
        else if (['input', 'text', 'email', 'number', 'phone', 'url'].includes(this.dialogType) && typeof this.data === 'string') {
            let type = 'text';
            if ([this.dialogType, this.field.toLowerCase()].includes('email')) {
                type = 'email';
            }
            if (this.dialogType === CUSTOM_FIELD_CONFIG_TYPE.NUMBER) {
                type = 'number';
            }
            if (this.dialogType === CUSTOM_FIELD_CONFIG_TYPE.PHONE) {
                type = 'tel';
            }
            if (this.dialogType === CUSTOM_FIELD_CONFIG_TYPE.URL) {
                type = 'url';
            }
            render = h(ZInput, { autoFocus: true, id: this.field, label: this.label, placeholder: this.label, value: this.data, onChange: val => this.handleChange(val), type: type, error: this.error });
        }
        return render;
    }
    renderTextAreaInput() {
        if (['textarea', 'address'].includes(this.dialogType) && typeof this.data === 'string') {
            return (h("div", { class: "mb-2" }, h(ZInputArea, { autoFocus: true, id: this.field, label: this.label, placeholder: this.label, value: this.data, onChange: val => this.handleChange(val), error: this.error, limit: this.limit })));
        }
        else {
            return null;
        }
    }
    renderFullAddressInput() {
        const userAddress = userAddressStore.get('userAddress');
        if (['full_address', 'order_address'].includes(this.dialogType) && userAddress) {
            const t = useTranslation();
            return h(Fragment, null, this.dialogType === 'order_address' && (h(Fragment, null, h(ZInput, { autoFocus: true, id: "name", label: t('name'), placeholder: t('name'), value: userAddress.name, onChange: val => this.handleChangeAddress(val, 'name'), error: this.error }), h(ZInput, { id: "phone_number", label: t('tel'), placeholder: t('tel'), value: userAddress.phone_number, onChange: val => this.handleChangeAddress(val, 'phone_number'), error: this.error }))), h(ZInputArea, { autoFocus: this.dialogType === 'full_address', id: this.field, label: this.label, placeholder: this.label, value: userAddress.address, onChange: val => this.handleChangeAddress(val, 'address'), error: this.error }), h("div", { class: "dialog-editor-address-wrapper" }, h("autocomplete-address", { field: "p", value: userAddress.province, placeholder: 'province', onSelecting: ({ detail }) => this.handleChangeAddress(detail, 'province'), referenceSelector: "profile-address-province" }), h("autocomplete-address", { field: "a", value: userAddress.district, placeholder: 'district', onSelecting: ({ detail }) => this.handleChangeAddress(detail, 'district'), referenceSelector: "profile-address-district" }), h("autocomplete-address", { field: "d", value: userAddress.sub_district, placeholder: 'sub_district', onSelecting: ({ detail }) => this.handleChangeAddress(detail, 'sub_district'), referenceSelector: "profile-address-sub_district" }), h("autocomplete-address", { field: "z", value: userAddress.zip_code, placeholder: 'zip_code', onSelecting: ({ detail }) => this.handleChangeAddress(detail, 'zip_code'), referenceSelector: "profile-address-zip_code" })));
        }
        else {
            return null;
        }
    }
    renderDropdownInput() {
        if (this.dialogType === 'dropdown' && this.options) {
            const inputId = `${this.field}-dropdown`;
            const value = typeof this.data === 'string' ? this.data : '';
            return (h("div", { class: "mb-2", id: inputId }, h("autocomplete-select", { value: value, showClearButton: true, fetchItems: () => Promise.resolve((this.options).map(({ label, value }) => ({ id: value, name: label }))), onSelecting: item => {
                    const value = item.detail.id;
                    this.handleChange(value);
                }, type: "status", referenceSelector: inputId, hideLabelUsed: true })));
        }
        else {
            return null;
        }
    }
    renderMultipleDropdownInput() {
        if (this.dialogType === 'multiselect' && this.options) {
            const inputId = `${this.field}-dropdown`;
            const value = Array.isArray(this.data) ? this.data : [];
            return (h("div", { class: "mb-2", id: inputId }, h("autocomplete-multiple-select", { selectedIds: value, fetchItems: () => Promise.resolve((this.options).map(({ label, value }) => ({ id: value, name: label }))), onSelecting: item => {
                    const values = this.options.filter(option => item.detail.includes(option.value)) || [];
                    this.handleChange(values);
                }, referenceSelector: inputId, showClearButton: true })));
        }
        else {
            return null;
        }
    }
    renderRadioInput() {
        if (this.dialogType === 'radio' && this.options) {
            const inputId = `${this.field}-dropdown`;
            const value = typeof this.data === 'string' ? this.data : '';
            return (h("div", { class: "mb-2 flex flex-col gap-4", id: inputId }, h("span", { class: "text-sm text-surface cursor-pointer", onClick: () => this.handleChange("") }, "\u0E25\u0E49\u0E32\u0E07\u0E17\u0E31\u0E49\u0E07\u0E2B\u0E21\u0E14"), this.options.map((option) => (h("div", { key: option.value, class: "flex items-center" }, h("input", { type: "radio", id: option.value, name: this.field, checked: value === option.value, onChange: () => this.handleChange(option.value) }), h("label", { htmlFor: option.value, class: "text-surface text-sm ml-2" }, option.label))))));
        }
        else {
            return null;
        }
    }
    renderCheckboxInput() {
        if (this.dialogType === 'checkbox' && this.options) {
            const inputId = `${this.field}-dropdown`;
            const value = Array.isArray(this.data) && this.data.every(item => typeof item === 'string') ? this.data : [];
            return (h("div", { class: "mb-2 flex flex-col gap-4", id: inputId }, h("span", { class: "text-sm text-surface cursor-pointer", onClick: () => this.handleChange([]) }, "\u0E25\u0E49\u0E32\u0E07\u0E17\u0E31\u0E49\u0E07\u0E2B\u0E21\u0E14"), this.options.map((option) => (h("div", { key: option.value, class: "flex items-center" }, h("input", { type: "checkbox", id: option.value, name: this.field, value: option.value, checked: value.includes(option.value), onChange: () => {
                    const newValue = value.includes(option.value)
                        ? value.filter((v) => v !== option.value)
                        : [...value, option.value];
                    const values = this.options.filter(option => newValue.includes(option.value)) || [];
                    this.handleChange(values);
                } }), h("label", { htmlFor: option.value, class: "text-surface text-sm ml-2" }, option.label))))));
        }
        else {
            return null;
        }
    }
    renderUploadInput() {
        if (this.dialogType === 'file' && Array.isArray(this.data) && this.data.every(item => typeof item === 'string')) {
            return h("div", { class: "dialog-editor-file-wrapper" }, h("quick-message-file", { isMaster: true, selectedUrl: this.data, onSelectedFiles: event => {
                    const values = event.detail.map(item => ({
                        id: item.file.id,
                        name: item.file.name,
                        type: 'file',
                        url: item.file.url
                    }));
                    this.tempData = values;
                    this.handleChange(values.map(item => item.url));
                } }));
        }
    }
    isDisabledSubmit() {
        const userAddress = userAddressStore.get('userAddress');
        return this.allowEmpty
            ? false
            : this.dialogType === 'order_address'
                ? !userAddress || userAddress.name === '' || userAddress.phone_number === '' || userAddress.address === '' || userAddress.province === '' || userAddress.district === '' || userAddress.sub_district === '' || userAddress.zip_code === '' || !this.hasDataChanged()
                : this.dialogType === 'full_address'
                    ? !userAddress || userAddress.address === '' || userAddress.province === '' || userAddress.district === '' || userAddress.sub_district === '' || userAddress.zip_code === '' || !this.hasDataChanged()
                    : typeof this.data === 'string'
                        ? this.data.trim().length === 0 || !this.hasDataChanged()
                        : (Array.isArray(this.data) && this.data.length === 0) || !this.hasDataChanged();
    }
    render() {
        const t = useTranslation();
        return (h(Host, { key: 'b7eff86499c7e31acda0932c72bd942a784c1d0a' }, h("div", { key: '1fd5a304dd0723b79303f5d96cb2766b30f33f42', class: `dialog-editor ${deviceModeStore.get('mode') === 'mobile' ? 'w-xs' : 'w-xl'}` }, h("h2", { key: '7e39516fc38cd29b12777e661f687db459d2ccb0', class: "dialog-editor-title" }, this.headerTitle ?? `${t('edit')} ${this.label}`), this.renderNormalInput(), this.renderTextAreaInput(), this.renderFullAddressInput(), this.renderDropdownInput(), this.renderMultipleDropdownInput(), this.renderRadioInput(), this.renderCheckboxInput(), this.renderUploadInput(), h("div", { key: 'f371857b5172c88bc2ce746629aada5a4d885960', class: "dialog-editor-action-wrapper" }, h(ZButton, { key: '6478c64ceb67b4249ed9b400d61e21b375acbd91', label: t('cancel'), variant: "outlined", fullWidth: true, onClick: (event) => this.handleCancel(event) }), h(ZButton, { key: 'b23d16775eb3a5424f85386616135de370079396', label: this.customSubmitName ? this.customSubmitName : t('save'), fullWidth: true, onClick: () => this.handleSubmit(), disabled: this.isDisabledSubmit() })))));
    }
    static get is() { return "dialog-editor"; }
    static get originalStyleUrls() {
        return {
            "$": ["dialog-editor.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["dialog-editor.css"]
        };
    }
    static get properties() {
        return {
            "dialogType": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "TDialogType",
                    "resolved": "\"full_address\" | \"input\" | \"order_address\" | \"textarea\" | CUSTOM_FIELD_CONFIG_TYPE.ADDRESS | CUSTOM_FIELD_CONFIG_TYPE.CHECKBOX | CUSTOM_FIELD_CONFIG_TYPE.DATE | CUSTOM_FIELD_CONFIG_TYPE.DROPDOWN | CUSTOM_FIELD_CONFIG_TYPE.EMAIL | CUSTOM_FIELD_CONFIG_TYPE.FILE | CUSTOM_FIELD_CONFIG_TYPE.MULTISELECT | CUSTOM_FIELD_CONFIG_TYPE.NUMBER | CUSTOM_FIELD_CONFIG_TYPE.PHONE | CUSTOM_FIELD_CONFIG_TYPE.RADIO | CUSTOM_FIELD_CONFIG_TYPE.TEXT | CUSTOM_FIELD_CONFIG_TYPE.URL",
                    "references": {
                        "TDialogType": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::TDialogType",
                            "referenceLocation": "TDialogType"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "dialog-type",
                "defaultValue": "'input'"
            },
            "label": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "label"
            },
            "headerTitle": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "header-title"
            },
            "field": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "field"
            },
            "value": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "TValueType",
                    "resolved": "BusinessFile[] | OptionValue[] | QuickMessageLibraryFile[] | string | string[] | { name?: string; phone_number?: string; address: string; district: string; sub_district: string; subdistrict?: string; province: string; zip_code: string; }",
                    "references": {
                        "TValueType": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::TValueType",
                            "referenceLocation": "TValueType"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "value"
            },
            "allowEmpty": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "allow-empty",
                "defaultValue": "false"
            },
            "options": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "OptionValue[]",
                    "resolved": "OptionValue[]",
                    "references": {
                        "OptionValue": {
                            "location": "import",
                            "path": "../../store/zdesk.type",
                            "id": "src/store/zdesk.type.ts::OptionValue",
                            "referenceLocation": "OptionValue"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "customSubmitName": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "custom-submit-name"
            },
            "limit": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "limit"
            }
        };
    }
    static get states() {
        return {
            "data": {},
            "tempData": {},
            "error": {},
            "originalValue": {}
        };
    }
    static get events() {
        return [{
                "method": "cancel",
                "name": "cancel",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }, {
                "method": "save",
                "name": "save",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "TValueType",
                    "resolved": "BusinessFile[] | OptionValue[] | QuickMessageLibraryFile[] | string | string[] | { name?: string; phone_number?: string; address: string; district: string; sub_district: string; subdistrict?: string; province: string; zip_code: string; }",
                    "references": {
                        "TValueType": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::TValueType",
                            "referenceLocation": "TValueType"
                        }
                    }
                }
            }];
    }
}
