import { Host, h } from "@stencil/core";
import { businessStore } from "../../store/store";
import { TICKET_STATUS_SETTING } from "../../store/zdesk.type";
import { useTranslation } from "../../utils/utils";
import { ZIconButton } from "../internal-component/z-icon-button";
/**
 * Reusable ticket status field.
 * - Display mode: shows color dot + label from businessStore settings.
 * - Edit mode (editMode=true): inline autocomplete-select with save/cancel.
 *
 * When the user saves, emits `statusChanged` with { id, ticket_status }.
 * Parent is responsible for the API call and optimistic update.
 */
export class TicketStatusField {
    /** Current status UUID (ITicketStatusSetting.id) */
    statusId;
    /** Current status enum value (for fallback when store is empty) */
    ticketStatus;
    /** Current status display name (ITicket.status.status) */
    statusName;
    /** Unique key for referenceSelector (e.g. ticket.id) */
    referenceKey;
    /** Whether the field is currently in edit mode */
    editMode = false;
    /** Emitted when save is clicked with a valid selection */
    statusChanged;
    /** Emitted when cancel is clicked */
    cancelEdit;
    /** Emitted when pencil is clicked (parent controls editMode prop) */
    startEdit;
    pendingStatusId = null;
    pendingStatus = null;
    get storeSettings() {
        return businessStore.get('ticketStatusSettings');
    }
    getStatusOptions() {
        const t = useTranslation();
        const settings = this.storeSettings;
        if (settings.length > 0) {
            return settings
                .filter(s => !s.is_hidden)
                .sort((a, b) => a.order_index - b.order_index)
                .map(s => ({
                id: s.id,
                name: s.created_by === 'system' ? t(`ticket_status.${s.ticket_status}`) : s.status,
                color: s.color,
                disabled: s.ticket_status === TICKET_STATUS_SETTING.OPEN && this.ticketStatus === TICKET_STATUS_SETTING.IN_PROGRESS,
            }));
        }
        return Object.values(TICKET_STATUS_SETTING).map(status => ({
            id: status,
            name: t(`ticket_status.${status}`),
            color: undefined,
        }));
    }
    getCurrentSetting() {
        return this.storeSettings.find(s => s.id === this.statusId);
    }
    getDisplayLabel() {
        const t = useTranslation();
        const setting = this.getCurrentSetting();
        if (setting) {
            return setting.created_by === 'system'
                ? t(`ticket_status.${setting.ticket_status}`)
                : setting.status;
        }
        return t(`ticket_status.${this.ticketStatus}`);
    }
    handleCancel = () => {
        this.pendingStatus = null;
        this.pendingStatusId = null;
        this.cancelEdit.emit();
    };
    handleSave = () => {
        if (this.pendingStatus && this.pendingStatusId) {
            this.statusChanged.emit({
                id: this.pendingStatusId,
                ticket_status: this.pendingStatus,
                isClosing: this.pendingStatus === TICKET_STATUS_SETTING.CLOSED,
            });
        }
        this.pendingStatus = null;
        this.pendingStatusId = null;
    };
    render() {
        const displayColor = this.getCurrentSetting()?.color;
        const displayLabel = this.getDisplayLabel();
        const inputId = `status-dropdown-${this.referenceKey}`;
        const currentId = this.pendingStatusId ?? this.storeSettings.find(s => s.id === this.statusId)?.id ?? this.statusName;
        if (this.editMode) {
            return (h(Host, { class: "ticket-status-field-edit" }, h("div", { class: "status-inline-dropdown", id: inputId }, h("autocomplete-select", { value: currentId, showClearButton: false, fetchItems: () => Promise.resolve(this.getStatusOptions()), onSelecting: (item) => {
                    const setting = this.storeSettings.find(s => s.id === item.detail.id);
                    this.pendingStatusId = item.detail.id;
                    this.pendingStatus = setting?.ticket_status ?? null;
                }, type: "status", referenceSelector: inputId, hideLabelUsed: true })), h("div", { class: "flex gap-2 items-center" }, h(ZIconButton, { variant: "text", iconName: "X", addClassIcon: "size-4 text-primary", noPadding: true, noPaddingY: true, onClick: this.handleCancel }), h(ZIconButton, { variant: "text", iconName: "Save", addClassIcon: "size-4 text-primary", noPadding: true, noPaddingY: true, onClick: this.handleSave }))));
        }
        return (h(Host, { class: "ticket-status-field-display" }, h("div", { class: "status-badge" }, displayColor && h("span", { class: "rounded-dot", style: { backgroundColor: displayColor } }), h("span", { class: "text-surface" }, displayLabel)), h(ZIconButton, { variant: "text", iconName: "Pencil", addClassIcon: "size-4", noPadding: true, noPaddingY: true, disabled: [TICKET_STATUS_SETTING.CANCELED, TICKET_STATUS_SETTING.CLOSED].includes(this.ticketStatus), onClick: () => this.startEdit.emit() })));
    }
    static get is() { return "ticket-status-field"; }
    static get originalStyleUrls() {
        return {
            "$": ["ticket-status-field.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["ticket-status-field.css"]
        };
    }
    static get properties() {
        return {
            "statusId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Current status UUID (ITicketStatusSetting.id)"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "status-id"
            },
            "ticketStatus": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "TICKET_STATUS_SETTING",
                    "resolved": "TICKET_STATUS_SETTING.CANCELED | TICKET_STATUS_SETTING.CLOSED | TICKET_STATUS_SETTING.IN_PROGRESS | TICKET_STATUS_SETTING.OPEN",
                    "references": {
                        "TICKET_STATUS_SETTING": {
                            "location": "import",
                            "path": "../../store/zdesk.type",
                            "id": "src/store/zdesk.type.ts::TICKET_STATUS_SETTING",
                            "referenceLocation": "TICKET_STATUS_SETTING"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Current status enum value (for fallback when store is empty)"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "ticket-status"
            },
            "statusName": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Current status display name (ITicket.status.status)"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "status-name"
            },
            "referenceKey": {
                "type": "any",
                "mutable": false,
                "complexType": {
                    "original": "string | number",
                    "resolved": "number | string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Unique key for referenceSelector (e.g. ticket.id)"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "reference-key"
            },
            "editMode": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Whether the field is currently in edit mode"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "edit-mode",
                "defaultValue": "false"
            }
        };
    }
    static get states() {
        return {
            "pendingStatusId": {},
            "pendingStatus": {}
        };
    }
    static get events() {
        return [{
                "method": "statusChanged",
                "name": "statusChanged",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when save is clicked with a valid selection"
                },
                "complexType": {
                    "original": "{ id: string; ticket_status: TICKET_STATUS_SETTING; isClosing: boolean }",
                    "resolved": "{ id: string; ticket_status: TICKET_STATUS_SETTING; isClosing: boolean; }",
                    "references": {
                        "TICKET_STATUS_SETTING": {
                            "location": "import",
                            "path": "../../store/zdesk.type",
                            "id": "src/store/zdesk.type.ts::TICKET_STATUS_SETTING",
                            "referenceLocation": "TICKET_STATUS_SETTING"
                        }
                    }
                }
            }, {
                "method": "cancelEdit",
                "name": "cancelEdit",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when cancel is clicked"
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }, {
                "method": "startEdit",
                "name": "startEdit",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when pencil is clicked (parent controls editMode prop)"
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }];
    }
}
