import { h } from "@stencil/core";
import { selectedChatStore } from "../../store/store";
import { ZIconButton } from "../internal-component/z-icon-button";
import { PaginationOrder } from "../../store/zdesk.type";
import { getCustomerComment } from "../../api/zdesk/customer";
import { getConnectionId, getConnectionItem } from "../../utils/func";
import { getBusinessUser } from "../profile-ticket/utils";
import { handleError } from "../../store/dialog";
import { debounce } from "../../utils/helpers";
import { Icon } from "../internal-component/icon";
export class CustomerInfoComment {
    user;
    readOnly = false;
    customerComments = [];
    customerCommentPagination = { page: 1, totalPage: 1, hasNextPage: true };
    isCommentLoading = false;
    isDrawerOpen = false;
    editNotes;
    showDialog = { open: false };
    async watchUserHandler(newValue, oldValue) {
        if (newValue?.id !== oldValue?.id) {
            await this.loadCustomerComments(true);
        }
    }
    async componentWillLoad() {
        if (this.user) {
            const selectedChat = selectedChatStore.get('selectedChat');
            if (!selectedChat)
                return;
            await this.loadCustomerComments(true);
        }
    }
    async loadCustomerComments(reset = false) {
        const user = this.user;
        if (!user)
            return;
        if (this.isCommentLoading && !reset)
            return; // Prevent concurrent loading unless reset
        if (reset) {
            this.customerComments = [];
            this.customerCommentPagination.page = 1;
            this.customerCommentPagination.hasNextPage = true;
        }
        if (!this.customerCommentPagination.hasNextPage)
            return;
        const selectedChat = selectedChatStore.get('selectedChat');
        if (!selectedChat)
            return;
        const connectionItem = getConnectionItem();
        const connectionId = getConnectionId(connectionItem);
        const businessUser = getBusinessUser(connectionItem);
        if (!businessUser)
            return;
        try {
            this.isCommentLoading = true;
            const { data, meta } = await getCustomerComment({ connectionId }, {
                customer_id: user.id.toString(),
                business_id: businessUser.business_id,
                order: PaginationOrder.DESC,
                order_by: 'created_at',
                page: this.customerCommentPagination.page,
                limit: 5
            });
            this.customerComments = [...this.customerComments, ...data];
            this.customerCommentPagination.totalPage = meta.page_count;
            this.customerCommentPagination.hasNextPage = meta.has_next_page;
            this.customerCommentPagination.page++;
        }
        catch (error) {
            handleError(error, 'Failed to load Customer Comments');
        }
        finally {
            this.isCommentLoading = false;
        }
    }
    handleScroll = debounce((e) => {
        const target = e.target;
        if (target.scrollTop + target.clientHeight >= target.scrollHeight - 50) {
            this.loadCustomerComments();
        }
    }, 200);
    handleEdit = () => {
        this.isDrawerOpen = true;
        this.editNotes.emit();
    };
    handleDrawerClose = () => {
        this.isDrawerOpen = false;
    };
    handleCommentUpdated = () => {
        this.loadCustomerComments(true);
    };
    handleOpenDialog = ({ url, type }) => {
        this.showDialog = { open: true, url, type };
    };
    handleCloseDialog = () => {
        this.showDialog = { open: false };
    };
    render() {
        const renderCommentItem = (comment, isReply = false, isLastReply = false) => {
            return (h("comment-item", { key: comment.id, comment: comment, isReply: isReply, isLastReply: isLastReply, hasActionParams: false, onOpenMedia: (e) => { e.stopPropagation(); this.handleOpenDialog({ url: e.detail.url, type: e.detail.type }); } }, comment?.customer_reply_comments && comment.customer_reply_comments.length > 0 && (h("div", { class: "replies-container" }, comment.customer_reply_comments.map((reply, index, arr) => renderCommentItem(reply, true, index === arr.length - 1))))));
        };
        return (h("div", { class: "customer-info-comment-wrapper" }, h("div", { class: "customer-info-subheader" }, this.customerComments.length > 0 && (h("span", { class: "customer-info-count" }, "\u0E42\u0E19\u0E49\u0E15 (", this.customerComments.length, ")")), !this.readOnly && (h("div", { class: "customer-info-actions" }, h(ZIconButton, { variant: "text", iconName: "Pencil", addClassIcon: "size-4", onClick: this.handleEdit })))), h("div", { class: "customer-info-notes flex-1 overflow-y-auto max-h-80", onScroll: (e) => this.handleScroll(e) }, this.customerComments.length === 0 ? (h("div", { class: "customer-info-empty" }, h("span", { class: "text-sm text-theme-gray" }, "-"))) : (this.customerComments.map((comment) => renderCommentItem(comment))), this.isCommentLoading && (h("div", { class: "flex justify-center p-2 text-theme-gray w-full" }, h(Icon, { name: "Loader2", addClass: "animate-spin size-6" })))), h("customer-info-comment-drawer", { user: this.user, isOpen: this.isDrawerOpen, onClose: this.handleDrawerClose, onCommentUpdated: this.handleCommentUpdated }), this.showDialog.open && (h("div", { class: "dialog-backdrop z-200", onClick: (e) => e.stopPropagation() }, h("dialog-preview-media", { dialogType: this.showDialog.type, url: this.showDialog.url || '', onClose: this.handleCloseDialog })))));
    }
    static get is() { return "customer-info-comment"; }
    static get originalStyleUrls() {
        return {
            "$": ["customer-info-comment.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["customer-info-comment.css"]
        };
    }
    static get properties() {
        return {
            "user": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "UserItem",
                    "resolved": "{ id: string; channel: ChannelType; user_id?: string; picture_url?: string; name: string; nickname: string; email?: string | string[]; phone_number?: string | string[]; address?: UserAddress; gender?: string; locale: string; note?: string; status?: TTagOrStatusItem; tags: TTagOrStatusItem[]; last_active_at: Date; created_at: Date; created_by: string; last_updated_at: Date; last_updated_by: string; summarized_message?: UserSummarizedMessage; match_users?: MatchUserItem[]; zignal_user_id?: string; associated_users?: AssociatedUser[]; context?: string; summarize_messages: TTagOrStatusItem[]; session?: UserSession; }",
                    "references": {
                        "UserItem": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::UserItem",
                            "referenceLocation": "UserItem"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "readOnly": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "read-only",
                "defaultValue": "false"
            }
        };
    }
    static get states() {
        return {
            "customerComments": {},
            "customerCommentPagination": {},
            "isCommentLoading": {},
            "isDrawerOpen": {},
            "showDialog": {}
        };
    }
    static get events() {
        return [{
                "method": "editNotes",
                "name": "editNotes",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "user",
                "methodName": "watchUserHandler"
            }];
    }
}
