import { format } from "date-fns";
import { getTemplate, VerdocsEndpoint } from "@verdocs/js-sdk";
import { h, Host } from "@stencil/core";
import { VerdocsToast } from "../../../utils/Toast";
import { SDKError } from "../../../utils/errors";
import { Store } from "../../../utils/Datastore";
const HelpIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24" fill="#5c6575"><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>';
const CopyIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125h-9.75a1.125 1.125 0 0 1-1.125-1.125V7.875c0-.621.504-1.125 1.125-1.125H6.75a9.06 9.06 0 0 1 1.5.124m7.5 10.376h3.375c.621 0 1.125-.504 1.125-1.125V11.25c0-4.46-3.243-8.161-7.5-8.876a9.06 9.06 0 0 0-1.5-.124H9.375c-.621 0-1.125.504-1.125 1.125v3.5m7.5 10.375H9.375a1.125 1.125 0 0 1-1.125-1.125v-9.25m12 6.625v-1.875a3.375 3.375 0 0 0-3.375-3.375h-1.5a1.125 1.125 0 0 1-1.125-1.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H9.75" /></svg>`;
const STEPS = ['attachments', 'roles', 'settings', 'fields', 'preview'];
/**
 * Display a set of tabs for the template builder.
 */
export class VerdocsTemplateBuildTabs {
    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 ID of the template to create the document from. Unlike most other components, this is an optional parameter here.
         * If the template ID is known, `step` may also be specified to force displaying a specific step in the creation process.
         * If it is not specified, `step` will be ignored and the create step will be shown.
         */
        this.templateId = null;
        /**
         * The step in the creation process to display.
         */
        this.step = 'preview';
        this.loading = true;
        this.template = null;
    }
    disconnectedCallback() {
        this.unlistenToTemplate();
    }
    async listenToTemplate() {
        this.unlistenToTemplate();
        Store.subscribe('templates', this.templateId, () => getTemplate(this.endpoint, this.templateId), false, (template) => {
            this.template = template;
            this.loading = false;
        });
    }
    unlistenToTemplate() {
        if (this.templateListenerId) {
            Store.store.delListener(this.templateListenerId);
            this.templateListenerId = null;
        }
    }
    onTemplateIdChanged(newTemplateId) {
        console.log('[BUILD_TABS] Template ID changed', newTemplateId);
        this.listenToTemplate();
    }
    onStepChanged(newStep) {
        console.log('[BUILD_TABS] Step changed', newStep);
    }
    async componentWillLoad() {
        var _a, _b, _c;
        try {
            this.endpoint.loadSession();
            if (!this.endpoint.session) {
                console.log('[BUILD_TABS] Unable to start builder session, must be authenticated');
                return;
            }
            if (!this.templateId) {
                this.step = 'attachments';
                console.log('[BUILD_TABS] Missing required template ID, forcing view to attachments');
                return;
            }
            this.listenToTemplate();
        }
        catch (e) {
            console.log('[BUILD_TABS] Error loading template', e);
            (_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));
        }
    }
    setStep(e) {
        var _a;
        console.log('[BUILD_TABS] Selected step', e.detail.tab.id);
        e.stopPropagation();
        e.preventDefault();
        this.step = e.detail.tab.id;
        (_a = this.stepChanged) === null || _a === void 0 ? void 0 : _a.emit(e.detail.tab.id);
    }
    copyTemplateId() {
        navigator.clipboard
            .writeText(this.templateId)
            .then(() => {
            VerdocsToast('Template ID copied', { style: 'success', duration: 3000 });
        })
            .catch(e => {
            var _a;
            console.warn('[BUILD_TABS] Error copying to clipboard', e);
            (_a = this.sdkError) === null || _a === void 0 ? void 0 : _a.emit(e);
        });
    }
    render() {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j;
        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." })));
        }
        const canEditRoles = (((_a = this.template) === null || _a === void 0 ? void 0 : _a.documents) || []).length > 0;
        let canEditFields = canEditRoles && (((_b = this.template) === null || _b === void 0 ? void 0 : _b.roles) || []).length > 0;
        const canPreview = canEditFields && (((_c = this.template) === null || _c === void 0 ? void 0 : _c.fields) || []).length > 0;
        let selectedStepIndex = Math.max(STEPS.indexOf(this.step), 0);
        if (!canPreview && selectedStepIndex >= 4) {
            selectedStepIndex = 3;
        }
        if (!canEditFields && selectedStepIndex >= 3) {
            selectedStepIndex = 1;
        }
        if (!canEditRoles && selectedStepIndex >= 1) {
            selectedStepIndex = 0;
        }
        return (h(Host, null, h("verdocs-tabs", { onSelectTab: e => this.setStep(e), selectedTab: selectedStepIndex, tabs: [
                { id: 'attachments', disabled: false, label: 'Attachment(s)' },
                { id: 'roles', disabled: !canEditRoles, label: 'Roles' },
                { id: 'settings', disabled: !canEditFields, label: 'Settings' },
                { id: 'fields', disabled: !canEditFields, label: 'Fields' },
                { id: 'preview', disabled: !canPreview, label: 'Preview/Send' },
            ] }), this.templateId && (h("div", { class: "info" }, h("verdocs-button-panel", { icon: HelpIcon }, h("div", { class: "template-details-panel" }, h("h6", null, "Template Details"), h("div", { class: "row" }, h("label", null, "ID:"), h("div", { class: "value" }, this.templateId), h("div", { class: "icon-button", innerHTML: CopyIcon, onClick: () => this.copyTemplateId() })), h("div", { class: "row" }, h("label", null, "Name:"), h("div", { class: "value" }, (_d = this.template) === null || _d === void 0 ? void 0 : _d.name)), h("div", { class: "row" }, h("label", null, "Visibility:"), h("div", { class: "value" }, ((_e = this.template) === null || _e === void 0 ? void 0 : _e.is_public) ? 'Public' : ((_f = this.template) === null || _f === void 0 ? void 0 : _f.is_personal) ? 'Private' : 'Shared')), h("div", { class: "row" }, h("label", null, "Created:"), h("div", { class: "value" }, ((_g = this.template) === null || _g === void 0 ? void 0 : _g.counter) ? format(new Date((_h = this.template) === null || _h === void 0 ? void 0 : _h.created_at), 'P p') : '')), h("div", { class: "row" }, h("label", null, "Used:"), h("div", { class: "value" }, (_j = this.template) === null || _j === void 0 ? void 0 :
            _j.counter, " time(s)"))))))));
    }
    static get is() { return "verdocs-template-build-tabs"; }
    static get originalStyleUrls() {
        return {
            "$": ["verdocs-template-build-tabs.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["verdocs-template-build-tabs.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": true,
                "complexType": {
                    "original": "string | null",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The ID of the template to create the document from. Unlike most other components, this is an optional parameter here.\nIf the template ID is known, `step` may also be specified to force displaying a specific step in the creation process.\nIf it is not specified, `step` will be ignored and the create step will be shown."
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "defaultValue": "null"
            },
            "step": {
                "type": "string",
                "attribute": "step",
                "mutable": true,
                "complexType": {
                    "original": "TVerdocsBuildStep",
                    "resolved": "\"attachments\" | \"fields\" | \"preview\" | \"roles\" | \"settings\"",
                    "references": {
                        "TVerdocsBuildStep": {
                            "location": "local",
                            "path": "/Users/chad/projects/verdocs/web-sdk/verdocs-web-sdk/src/components/templates/verdocs-template-build-tabs/verdocs-template-build-tabs.tsx",
                            "id": "src/components/templates/verdocs-template-build-tabs/verdocs-template-build-tabs.tsx::TVerdocsBuildStep"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The step in the creation process to display."
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "defaultValue": "'preview'"
            }
        };
    }
    static get states() {
        return {
            "loading": {},
            "template": {}
        };
    }
    static get events() {
        return [{
                "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"
                        }
                    }
                }
            }, {
                "method": "stepChanged",
                "name": "stepChanged",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user selects a different step."
                },
                "complexType": {
                    "original": "TVerdocsBuildStep",
                    "resolved": "\"attachments\" | \"fields\" | \"preview\" | \"roles\" | \"settings\"",
                    "references": {
                        "TVerdocsBuildStep": {
                            "location": "local",
                            "path": "/Users/chad/projects/verdocs/web-sdk/verdocs-web-sdk/src/components/templates/verdocs-template-build-tabs/verdocs-template-build-tabs.tsx",
                            "id": "src/components/templates/verdocs-template-build-tabs/verdocs-template-build-tabs.tsx::TVerdocsBuildStep"
                        }
                    }
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "templateId",
                "methodName": "onTemplateIdChanged"
            }, {
                "propName": "step",
                "methodName": "onStepChanged"
            }];
    }
}
//# sourceMappingURL=verdocs-template-build-tabs.js.map
