import { h, Host } from "@stencil/core";
import { deleteField, getTemplate, updateField, VerdocsEndpoint } from "@verdocs/js-sdk";
import { SDKError } from "../../../utils/errors";
import { Store } from "../../../utils/Datastore";
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
const TrashIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="#a50021"><path stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" /></svg>`;
const HelpIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path d="M11.925 18q.55 0 .938-.387.387-.388.387-.938 0-.55-.387-.925-.388-.375-.938-.375-.55 0-.925.375t-.375.925q0 .55.375.938.375.387.925.387Zm-.95-3.85h1.95q0-.8.2-1.287.2-.488 1.025-1.288.65-.625 1.025-1.213.375-.587.375-1.437 0-1.425-1.025-2.175Q13.5 6 12.1 6q-1.425 0-2.35.775t-1.275 1.85l1.775.7q.125-.45.55-.975.425-.525 1.275-.525.725 0 1.1.412.375.413.375.888 0 .475-.287.9-.288.425-.713.775-1.075.95-1.325 1.475-.25.525-.25 1.875ZM12 22.2q-2.125 0-3.988-.8-1.862-.8-3.237-2.175Q3.4 17.85 2.6 15.988 1.8 14.125 1.8 12t.8-3.988q.8-1.862 2.175-3.237Q6.15 3.4 8.012 2.6 9.875 1.8 12 1.8t3.988.8q1.862.8 3.237 2.175Q20.6 6.15 21.4 8.012q.8 1.863.8 3.988t-.8 3.988q-.8 1.862-2.175 3.237Q17.85 20.6 15.988 21.4q-1.863.8-3.988.8Zm0-2.275q3.325 0 5.625-2.3t2.3-5.625q0-3.325-2.3-5.625T12 4.075q-3.325 0-5.625 2.3T4.075 12q0 3.325 2.3 5.625t5.625 2.3ZM12 12Z"/></svg>';
/**
 * Displays an edit form that allows the user to adjust a field's settings.
 */
export class VerdocsTemplateFieldProperties {
    constructor() {
        this.templateListenerId = null;
        /**
         * The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used.
         */
        this.endpoint = VerdocsEndpoint.getDefault();
        /**
         * The template ID to edit.
         */
        this.templateId = '';
        /**
         * The field to configure.
         */
        this.fieldName = '';
        /**
         * If specified, the properties card will have a "back" side with the help text as its content.
         */
        this.helpText = '';
        this.dirty = false;
        this.label = '';
        this.type = 'textbox';
        this.name = '';
        this.required = false;
        this.roleName = '';
        this.group = '';
        this.fieldType = '';
        this.options = [];
        this.placeholder = '';
        this.defaultValue = '';
        this.showingHelp = false;
        this.loading = true;
        this.template = null;
    }
    disconnectedCallback() {
        this.unlistenToTemplate();
    }
    async listenToTemplate() {
        console.log('[SENT] Loading template', this.templateId);
        this.unlistenToTemplate();
        Store.subscribe('templates', this.templateId, () => getTemplate(this.endpoint, this.templateId), false, (template) => {
            console.log('[SEND] Template Updated', template);
            this.template = template;
            this.loading = false;
            this.resetForm();
        });
    }
    unlistenToTemplate() {
        if (this.templateListenerId) {
            Store.store.delListener(this.templateListenerId);
            this.templateListenerId = null;
        }
    }
    async componentWillLoad() {
        var _a, _b, _c;
        try {
            this.endpoint.loadSession();
            if (!this.templateId) {
                console.log(`[FIELD PROPERTIES] Missing required template ID ${this.templateId}`);
                return;
            }
            if (!this.fieldName) {
                console.error(`[FIELD PROPERTIES] Missing required field name`);
                return;
            }
            if (!this.endpoint.session) {
                console.log('[FIELD PROPERTIES] Unable to start builder session, must be authenticated');
                return;
            }
            this.listenToTemplate();
        }
        catch (e) {
            console.log('[FIELD PROPERTIES] Error loading template', e);
            this.loading = false;
            (_a = this.sdkError) === null || _a === void 0 ? void 0 : _a.emit(new SDKError(e.message, (_b = e.response) === null || _b === void 0 ? void 0 : _b.status, (_c = e.response) === null || _c === void 0 ? void 0 : _c.data));
        }
    }
    resetForm() {
        var _a;
        const field = (((_a = this.template) === null || _a === void 0 ? void 0 : _a.fields) || []).find(field => field.name === this.fieldName);
        if (!field) {
            console.log(`[FIELD PROPERTIES] Unable to find field "${this.fieldName}" in fields`);
            return;
        }
        this.type = field.type;
        this.name = field.name;
        this.label = field.label;
        this.group = field.group;
        this.roleName = field.role_name;
        this.required = field.required;
        this.fieldType = field.type;
        this.options = field.options || [];
        this.placeholder = field.placeholder || '';
        this.defaultValue = field.default || '';
        this.dirty = false;
        this.loading = false;
        this.cleanupOptions();
    }
    handleCancel(e) {
        var _a, _b;
        e.stopPropagation();
        this.resetForm();
        (_a = this.close) === null || _a === void 0 ? void 0 : _a.emit();
        (_b = document.getElementById('verdocs-template-field-properties')) === null || _b === void 0 ? void 0 : _b.remove();
    }
    handleSave(e) {
        e.stopPropagation();
        const newProperties = {
            name: this.name,
            role_name: this.roleName,
            required: this.required,
            label: this.label,
            group: this.group,
            placeholder: this.placeholder,
            default: this.defaultValue,
            options: this.options,
        };
        this.cleanupOptions();
        console.log('[FIELD PROPERTIES] Will update', this.fieldName, newProperties);
        updateField(this.endpoint, this.templateId, this.fieldName, newProperties)
            .then(updatedField => {
            var _a, _b, _c;
            console.log('[FIELD PROPERTIES] Updated', updatedField);
            const newTemplate = JSON.parse(JSON.stringify(this.template));
            const fieldIndex = newTemplate.fields.findIndex(field => field.name === this.fieldName);
            if (fieldIndex > -1) {
                newTemplate.fields[fieldIndex] = updatedField;
            }
            Store.updateTemplate(this.templateId, newTemplate);
            (_a = this.settingsChanged) === null || _a === void 0 ? void 0 : _a.emit({ fieldName: this.fieldName, field: updatedField });
            (_b = this.close) === null || _b === void 0 ? void 0 : _b.emit();
            (_c = document.getElementById('verdocs-template-field-properties')) === null || _c === void 0 ? void 0 : _c.remove();
        })
            .catch(() => {
            console.log('[FIELD PROPERTIES] Update failed', e);
        });
    }
    async handleDelete(e) {
        e.stopPropagation();
        deleteField(this.endpoint, this.templateId, this.fieldName)
            .then(() => {
            var _a, _b;
            const newTemplate = JSON.parse(JSON.stringify(this.template));
            newTemplate.fields = newTemplate.fields.filter(field => field.name !== this.fieldName);
            Store.updateTemplate(this.templateId, newTemplate);
            (_a = this.delete) === null || _a === void 0 ? void 0 : _a.emit({ templateId: this.templateId, roleName: this.roleName });
            (_b = document.getElementById('verdocs-template-field-properties')) === null || _b === void 0 ? void 0 : _b.remove();
        })
            .catch(e => {
            console.log('[FIELD PROPERTIES] Deletion error', e);
        });
    }
    cleanupOptions() {
        this.options = [...this.options.filter(opt => (opt.id || '').trim() !== '' || (opt.label || '').trim() !== '')];
        if (!this.options.find(opt => !opt.id && !opt.label)) {
            this.options = [...this.options, { id: '', label: '' }];
        }
    }
    render() {
        var _a, _b;
        if (this.loading) {
            return (h(Host, null, h("verdocs-loader", null)));
        }
        if (!this.endpoint.session) {
            return (h(Host, null, h("verdocs-component-error", { message: "You must be authenticated to use this module." })));
        }
        // This is meant to be a companion for larger visual experiences so we just go blank on errors for now.
        if (!this.endpoint.session || !(((_a = this.template) === null || _a === void 0 ? void 0 : _a.fields) || []).some(field => field.name === this.fieldName)) {
            return h(Host, { class: "empty" });
        }
        if (this.helpText && this.showingHelp) {
            return (h(Host, null, h("h6", null, capitalize(this.fieldType), " Settings ", h("div", { style: { flex: '1' } }), h("div", { class: "help-icon", innerHTML: HelpIcon, onClick: () => (this.showingHelp = false) })), h("p", { class: "instructions", innerHTML: this.helpText })));
        }
        const hasOptions = this.options.filter(opt => (opt.id || '').trim() !== '' || (opt.label || '').trim() !== '').length > 0;
        const saveDisabled = !this.dirty || (this.type === 'dropdown' && !hasOptions);
        return (h(Host, { id: "verdocs-template-field-properties" }, h("h6", null, capitalize(this.fieldType.replace(/_/g, ' ')), " Settings ", h("div", { style: { flex: '1' } }), this.helpText && h("div", { class: "help-icon", innerHTML: HelpIcon, onClick: () => (this.showingHelp = true) })), h("form", { onSubmit: e => e.preventDefault(), onClick: e => e.stopPropagation(), autocomplete: "off" }, h("div", { class: "row" }, h("verdocs-text-input", { id: "verdocs-field-name", label: "Field Name", value: this.name, autocomplete: "off",
            //              helpText="The internal name of the field. Must be unique, and contain only letters, numbers, and dashes. After an envelope is completed, the value entered by the signer will be tagged with this key."
            placeholder: "Field Name...", onInput: (e) => {
                this.name = e.target.value;
                this.dirty = true;
            } })), h("div", { class: "row" }, h("verdocs-text-input", { id: "verdocs-field-label", label: "Optional Label", value: this.label, autocomplete: "off", placeholder: "Optional Label...", onInput: (e) => {
                this.label = e.target.value;
                this.dirty = true;
            } })), h("div", { class: "row" }, h("div", { class: "input-label" }, "Role:"), h("verdocs-select-input", { value: this.roleName, options: (((_b = this.template) === null || _b === void 0 ? void 0 : _b.roles) || []).map(role => ({ label: role.name, value: role.name })), onInput: (e) => {
                this.roleName = e.target.value;
                this.dirty = true;
            } })), ['textbox', 'textarea'].includes(this.type) && (h("div", { class: "row", style: { marginTop: '10px', marginBottom: '10px' } }, h("verdocs-text-input", { id: "verdocs-field-value", label: "Default Value", value: this.defaultValue, autocomplete: "off", placeholder: "Pre-filled value...", onInput: (e) => {
                this.defaultValue = e.target.value;
                this.dirty = true;
            } }))), this.type === 'radio' && (h("div", { class: "row" }, h("verdocs-text-input", { id: "verdocs-field-label", label: "Group", value: this.group, autocomplete: "off", helpText: "Enable exclusive selections. Only one option within the same group may be selected at a time.", placeholder: "Group...", onInput: (e) => {
                this.group = (e.target.value || '')
                    .trim()
                    .toLowerCase()
                    .replace(/[^a-z0-9]/g, '');
                this.dirty = true;
            } }))), ['textbox', 'textarea'].includes(this.type) && (h("div", { class: "row", style: { marginTop: '10px', marginBottom: '10px' } }, h("verdocs-text-input", { id: "verdocs-field-placeholder", label: "Placeholder", value: this.placeholder, autocomplete: "off", placeholder: "Placeholder...", onInput: (e) => {
                this.placeholder = e.target.value;
                this.dirty = true;
            } }))), h("div", { class: "row", style: { marginTop: '15px', marginBottom: '15px' } }, h("label", { htmlFor: "verdocs-is-required", class: "input-label" }, "Required"), h("verdocs-checkbox", { id: "verdocs-is-required", name: "is-required", checked: this.required, value: "on", onInput: (e) => {
                this.required = e.target.checked;
                this.dirty = true;
            } })), this.type === 'dropdown' && (h("div", { class: "row", style: { marginTop: '15px', marginBottom: '15px' } }, h("label", { htmlFor: "verdocs-is-required", class: "input-label" }, "Options"))), this.type === 'dropdown' && (h("div", { class: "options" }, h("div", { class: "options-header" }, h("div", { class: "options-header-label" }, "ID"), h("dev", { class: "options-header-label" }, "Label")), this.options.map((option, index) => (h("div", { class: "row option-row", key: index }, h("verdocs-text-input", { value: option.id, placeholder: "Unique ID", onInput: (e) => {
                this.options[index].id = e.target.value;
                this.dirty = true;
                this.cleanupOptions();
            } }), h("verdocs-text-input", { value: option.label, placeholder: "Display label", onInput: (e) => {
                this.options[index].label = e.target.value;
                this.dirty = true;
                this.cleanupOptions();
            } }), h("button", { innerHTML: TrashIcon, class: "remove-button", onClick: () => {
                this.options = this.options.filter(opt => opt.id !== option.id);
                this.dirty = true;
                this.cleanupOptions();
            } })))))), h("div", { class: "buttons" }, h("button", { class: "delete-button", disabled: this.dirty, onClick: e => this.handleDelete(e), innerHTML: TrashIcon }), h("div", { style: { flex: '1' } }), h("verdocs-button", { size: "small", variant: "outline", label: "Cancel", disabled: !this.dirty, onClick: e => this.handleCancel(e) }), h("verdocs-button", { size: "small", label: "Save", disabled: saveDisabled, onClick: e => !saveDisabled && this.handleSave(e) })))));
    }
    static get is() { return "verdocs-template-field-properties"; }
    static get originalStyleUrls() {
        return {
            "$": ["verdocs-template-field-properties.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["verdocs-template-field-properties.css"]
        };
    }
    static get properties() {
        return {
            "endpoint": {
                "type": "unknown",
                "attribute": "endpoint",
                "mutable": false,
                "complexType": {
                    "original": "VerdocsEndpoint",
                    "resolved": "VerdocsEndpoint",
                    "references": {
                        "VerdocsEndpoint": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::VerdocsEndpoint"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used."
                },
                "getter": false,
                "setter": false,
                "defaultValue": "VerdocsEndpoint.getDefault()"
            },
            "templateId": {
                "type": "string",
                "attribute": "template-id",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The template ID to edit."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "''"
            },
            "fieldName": {
                "type": "string",
                "attribute": "field-name",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The field to configure."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "''"
            },
            "helpText": {
                "type": "string",
                "attribute": "help-text",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "If specified, the properties card will have a \"back\" side with the help text as its content."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "''"
            }
        };
    }
    static get states() {
        return {
            "dirty": {},
            "label": {},
            "type": {},
            "name": {},
            "required": {},
            "roleName": {},
            "group": {},
            "fieldType": {},
            "options": {},
            "placeholder": {},
            "defaultValue": {},
            "showingHelp": {},
            "loading": {},
            "template": {}
        };
    }
    static get events() {
        return [{
                "method": "close",
                "name": "close",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user cancels the dialog."
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "delete",
                "name": "delete",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user deletes the role. The parent should update its UI to reflect the removal. When this event is emitted,\nthe role will have already been deleted server-side."
                },
                "complexType": {
                    "original": "{templateId: string; roleName: string}",
                    "resolved": "{ templateId: string; roleName: string; }",
                    "references": {}
                }
            }, {
                "method": "settingsChanged",
                "name": "settingsChanged",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the field's settings are changed."
                },
                "complexType": {
                    "original": "{fieldName: string; field: ITemplateField}",
                    "resolved": "{ fieldName: string; field: ITemplateField; }",
                    "references": {
                        "ITemplateField": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::ITemplateField"
                        }
                    }
                }
            }, {
                "method": "sdkError",
                "name": "sdkError",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired if an error occurs. The event details will contain information about the error. Most errors will\nterminate the process, and the calling application should correct the condition and re-render the component."
                },
                "complexType": {
                    "original": "SDKError",
                    "resolved": "SDKError",
                    "references": {
                        "SDKError": {
                            "location": "import",
                            "path": "../../../utils/errors",
                            "id": "src/utils/errors.ts::SDKError"
                        }
                    }
                }
            }];
    }
    static get elementRef() { return "el"; }
}
//# sourceMappingURL=verdocs-template-field-properties.js.map
