import { Host, h } from "@stencil/core";
import { ZIconButton } from "../internal-component/z-icon-button";
import { Icon } from "../internal-component/icon";
import { base64ToFileList, useTranslation } from "../../utils/utils";
import { MESSAGE_TYPE, PaginationOrder } from "../../store/zdesk.type";
import { getCustomerComment, postCustomerComment, patchCustomerComment, deleteCustomerComment, postCustomerCommentReply, patchCustomerCommentReply, deleteCustomerCommentReply } from "../../api/zdesk/customer";
import { getConnectionId, getConnectionItem } from "../../utils/func";
import { debounce } from "../../utils/helpers";
import { getBusinessUser } from "../profile-ticket/utils";
import { selectedChatStore, businessStore } from "../../store/store";
import { closeDialog, handleError, openDialog } from "../../store/dialog";
import { handleGetMediaUrlFromSignKey, uploadFileService } from "../../utils/upload";
export class CustomerInfoCommentDrawer {
    user;
    isOpen = false;
    close;
    commentUpdated;
    isLoading = false;
    isImageLoading = false;
    containerRect = null;
    commentText = '';
    images = [];
    customerComments = [];
    page = 1;
    totalPage = 1;
    hasNextPage = true;
    customerCommentId = '';
    customerReplyCommentId = '';
    isEdit = false;
    showDialog = { open: false };
    inputEl;
    componentDidLoad() {
        this.adjustHeight();
        window.addEventListener('resize', this.updateRect);
    }
    disconnectedCallback() {
        window.removeEventListener('resize', this.updateRect);
    }
    handleOpenDialog = ({ url, type }) => {
        this.showDialog = { open: true, url, type };
    };
    handleCloseDialog = () => {
        this.showDialog = { open: false };
    };
    updateRect = () => {
        const el = document.getElementById('profile-tabs-content');
        if (el) {
            this.containerRect = el.getBoundingClientRect();
        }
    };
    watchIsOpenHandler(newValue) {
        if (newValue) {
            this.updateRect();
            setTimeout(() => {
                this.loadCustomerComments(true);
            });
        }
    }
    async componentWillLoad() {
        if (this.user) {
            await this.loadCustomerComments(true);
        }
    }
    async loadCustomerComments(reset = false) {
        if (this.isLoading && !reset)
            return;
        if (reset) {
            this.customerComments = [];
            this.page = 1;
            this.hasNextPage = true;
        }
        if (!this.hasNextPage)
            return;
        const selectedChat = selectedChatStore.get('selectedChat');
        if (!selectedChat || !this.user)
            return;
        const connectionItem = getConnectionItem();
        const connectionId = getConnectionId(connectionItem);
        const businessUser = getBusinessUser(connectionItem);
        if (!businessUser)
            return;
        try {
            this.isLoading = true;
            const { data, meta } = await getCustomerComment({ connectionId }, {
                customer_id: this.user.id.toString(),
                business_id: businessUser.business_id,
                order: PaginationOrder.DESC,
                order_by: 'created_at',
                page: this.page,
                limit: 5
            });
            this.customerComments = [...this.customerComments, ...data];
            this.totalPage = meta.page_count;
            this.hasNextPage = meta.has_next_page;
            this.page++;
        }
        catch (error) {
            handleError(error, 'Failed to load Customer Comments');
        }
        finally {
            this.isLoading = false;
        }
    }
    async handleCustomerComment() {
        const selectedChat = selectedChatStore.get('selectedChat');
        if (!selectedChat || !this.user)
            return;
        const connectionItem = getConnectionItem();
        const connectionId = getConnectionId(connectionItem);
        const businessUser = getBusinessUser(connectionItem);
        if (!businessUser)
            return;
        try {
            this.isLoading = true;
            let messages = {
                type: MESSAGE_TYPE.TEXT,
                text: this.commentText
            };
            if (this.images.length) {
                const files = base64ToFileList(this.images);
                const url = await this.handleUploadImages(files);
                messages = {
                    url,
                    text: this.commentText || undefined, // Allow captioning images
                    type: MESSAGE_TYPE.IMAGE
                };
            }
            const value = {
                business_id: businessUser.business_id,
                customer_id: this.user.id.toString(),
                business_user_id: businessUser.id,
                messages
            };
            if (this.customerCommentId) {
                if (this.isEdit) {
                    if (this.customerReplyCommentId) {
                        await patchCustomerCommentReply({ connectionId }, { customer_comment_id: this.customerCommentId, id: this.customerReplyCommentId, ...value });
                        this.customerReplyCommentId = '';
                    }
                    else {
                        await patchCustomerComment({ connectionId }, { id: this.customerCommentId, ...value });
                    }
                    this.isEdit = false;
                }
                else {
                    await postCustomerCommentReply({ connectionId }, { customer_comment_id: this.customerCommentId, ...value });
                }
                this.customerCommentId = '';
            }
            else {
                await postCustomerComment({ connectionId }, value);
            }
            if (this.commentText)
                this.commentText = '';
            if (this.images.length)
                this.images = [];
            this.adjustHeight();
            await this.loadCustomerComments(true);
            this.commentUpdated.emit();
        }
        catch (error) {
            handleError(error, 'Failed to update Customer Comment');
        }
        finally {
            this.isLoading = false;
        }
    }
    async handleDeleteCustomerComment() {
        const selectedChat = selectedChatStore.get('selectedChat');
        if (!selectedChat || !this.user)
            return;
        const connectionItem = getConnectionItem();
        const connectionId = getConnectionId(connectionItem);
        const businessUser = getBusinessUser(connectionItem);
        if (!businessUser)
            return;
        try {
            this.isLoading = true;
            const value = {
                business_id: businessUser.business_id,
                customer_id: this.user.id.toString(),
            };
            if (this.customerCommentId) {
                if (this.customerReplyCommentId) {
                    await deleteCustomerCommentReply({ connectionId }, { customer_comment_id: this.customerCommentId, id: this.customerReplyCommentId, ...value });
                    this.customerReplyCommentId = '';
                }
                else {
                    await deleteCustomerComment({ connectionId }, { id: this.customerCommentId, ...value });
                }
                this.customerCommentId = '';
            }
            await this.loadCustomerComments(true);
            this.commentUpdated.emit();
        }
        catch (error) {
            handleError(error, 'Failed to Delete Customer Comment');
        }
        finally {
            this.isLoading = false;
        }
    }
    handleUploadMedia(files) {
        if (!files || files.length === 0)
            return;
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = e => {
                    const base64 = e.target ? e.target.result : '';
                    this.images = [...this.images, base64];
                };
                reader.readAsDataURL(file);
            }
        }
    }
    handleRemoveImage = (index) => {
        this.images = this.images.filter((_, i) => i !== index);
    };
    handlePaste = (event) => {
        if (!event.clipboardData)
            return;
        const clipboardItems = event.clipboardData.items;
        if (!clipboardItems)
            return;
        for (let i = 0; i < clipboardItems.length; i++) {
            const item = clipboardItems[i];
            if (item.type.indexOf('image') !== -1) {
                const file = item.getAsFile();
                const reader = new FileReader();
                reader.onload = e => {
                    const base64 = e.target ? e.target.result : '';
                    this.images = [...this.images, base64];
                };
                if (file)
                    reader.readAsDataURL(file);
                event.preventDefault();
            }
        }
    };
    async handleUploadImages(files, max = 1) {
        if (files && files.length > 0) {
            const fileList = Array.from(files).slice(0, max);
            try {
                this.isImageLoading = true;
                for (const file of Array.from(fileList)) {
                    const response = await uploadFileService({
                        file,
                        filename: file.name.replace(/\s+/g, '-'),
                    });
                    if (response && response.key) {
                        const url = handleGetMediaUrlFromSignKey(response.key);
                        return url;
                    }
                }
            }
            catch (error) {
                handleError(error, 'Failed to upload media');
            }
            finally {
                this.isImageLoading = false;
            }
        }
    }
    adjustHeight() {
        const textarea = this.inputEl;
        if (!textarea)
            return;
        textarea.style.height = 'auto';
        const lineHeight = parseInt(getComputedStyle(textarea).lineHeight || '20', 10);
        const minHeight = 2 * lineHeight;
        const maxHeight = 8 * lineHeight;
        const newHeight = this.commentText.length === 0 ? minHeight : Math.min(Math.max(textarea.scrollHeight, minHeight), maxHeight);
        textarea.style.height = `${newHeight}px`;
    }
    handleInput = (e) => {
        const target = e.target;
        this.commentText = target.value;
        this.adjustHeight();
    };
    handleKeydown = (e) => {
        if (e.key === 'Enter') {
            if (e.shiftKey) {
                return;
            }
            e.preventDefault();
            if (this.commentText || this.images.length > 0) {
                this.handleCustomerComment();
            }
        }
    };
    renderReplyPreview() {
        const previewId = this.customerReplyCommentId || this.customerCommentId;
        if (!previewId)
            return null;
        const comment = this.customerComments.find(c => c.id === previewId) ||
            this.customerComments.flatMap(c => c.customer_reply_comments || []).find(r => r.id === previewId);
        if (!comment)
            return null;
        const user = businessStore.get('users').find(item => item.id === comment.business_user_id);
        return (h("div", { class: "relative mb-2 p-2 text-sm" }, h("div", { class: "flex items-center justify-between mb-1" }, h("div", { class: "flex items-center gap-2 text-sm text-surface font-semibold" }, h(ZIconButton, { variant: "text", iconName: this.isEdit ? "Pencil" : "Reply", addClassIcon: "size-4", noPadding: true, noPaddingY: true, disabled: true }), h("span", null, this.isEdit ? 'Editing' : 'Replying to', ": ", user?.display_name || 'Unknown')), h(ZIconButton, { variant: "text", iconName: "X", addClassIcon: "size-4", onClick: () => {
                this.customerCommentId = '';
                this.customerReplyCommentId = '';
                this.isEdit = false;
                this.commentText = '';
                this.images = [];
                this.adjustHeight();
            }, noPadding: true, noPaddingY: true })), h("div", { class: "text-sm text-theme-gray truncate ml-6", innerHTML: comment.messages?.text || '' })));
    }
    renderCommentInput() {
        const t = useTranslation();
        return (h("div", { class: "bg-selected shadow-inner w-full flex flex-col py-2 px-4" }, this.renderReplyPreview(), this.images.length > 0 && (h("div", { class: "m-2 flex max-h-80 flex-wrap items-center space-x-1 overflow-y-auto scroll-container" }, this.images.map((img, idx) => (h("div", { class: "relative inline-block", key: `img-${idx}` }, h("div", { class: "absolute top-[-8px] right-[-8px]" }, h(ZIconButton, { variant: "text", iconName: "CircleX", onClick: () => this.handleRemoveImage(idx) })), h("img", { src: img, style: { maxWidth: '150px', margin: '5px', borderRadius: '5px' }, loading: "lazy" })))))), h("div", { class: "flex items-center gap-2" }, h(ZIconButton, { variant: "text", iconName: "Camera", addClassIcon: "size-5", onClick: () => {
                if (document.getElementById('cameraInputCustomerComment'))
                    document.getElementById('cameraInputCustomerComment').click();
            }, isLoading: this.isImageLoading }), h("input", { type: "file", id: "cameraInputCustomerComment", accept: "image/*", hidden: true, onChange: event => {
                this.handleUploadMedia(event.target.files);
                event.target.value = '';
            } }), h("div", { class: "relative flex-1" }, h("textarea", { class: "ring-primary text-surface bg-paper h-10 w-full flex-1 resize-none rounded-3xl border-none px-4 py-2 text-sm placeholder-[#707176] focus:outline-none scroll-container", placeholder: t('type_message_here') || 'Type message here...', value: this.commentText, ref: el => (this.inputEl = el), onPaste: this.handlePaste, onInput: this.handleInput, onKeyDown: this.handleKeydown })), h(ZIconButton, { variant: "text", iconName: "Send", addClassIcon: "size-5", disabled: this.isLoading || this.isImageLoading || (!this.commentText.trim() && this.images.length === 0), onClick: () => this.handleCustomerComment() }))));
    }
    renderCommentsList() {
        const connectionItem = getConnectionItem();
        const businessUser = getBusinessUser(connectionItem);
        const handleToolState = (action, comment, isEditReply = false) => {
            const commentId = comment.id;
            const t = useTranslation();
            switch (action) {
                case 'edit':
                    this.isEdit = true;
                    this.commentText = comment.messages?.text || '';
                    if (isEditReply) {
                        this.customerCommentId = comment.customer_comment_id;
                        this.customerReplyCommentId = commentId;
                    }
                    else {
                        this.customerCommentId = commentId;
                        this.customerReplyCommentId = '';
                    }
                    break;
                case 'reply':
                    this.isEdit = false;
                    this.commentText = '';
                    this.images = [];
                    this.adjustHeight();
                    this.customerCommentId = comment.id;
                    this.customerReplyCommentId = '';
                    break;
                case 'delete':
                    this.isEdit = false;
                    this.commentText = '';
                    this.images = [];
                    this.adjustHeight();
                    if (isEditReply) {
                        this.customerCommentId = comment.customer_comment_id;
                        this.customerReplyCommentId = commentId;
                    }
                    else {
                        this.customerCommentId = commentId;
                        this.customerReplyCommentId = '';
                    }
                    openDialog({
                        open: true,
                        type: "WARNING" /* DIALOG_TYPE.WARNING */,
                        title: 'ลบโน้ต',
                        contentCustom: 'คุณต้องการลบโน้ตนี้ใช่หรือไม่',
                        buttonName: t('confirm') || 'Confirm',
                        cancelButtonName: t('cancel') || 'Cancel',
                        onSubmitDialog: () => this.handleDeleteCustomerComment(),
                        onCloseDialog: closeDialog,
                    });
                    break;
            }
        };
        const renderCommentItem = (comment, isReply = false, isLastReply = false) => {
            const focusId = this.customerReplyCommentId || this.customerCommentId;
            return (h("comment-item", { key: comment.id, comment: comment, isReply: isReply, isLastReply: isLastReply, hasActionParams: true, businessUserId: businessUser?.id, focusId: focusId, onReplyComment: (e) => { e.stopPropagation(); handleToolState('reply', e.detail); }, onEditComment: (e) => { e.stopPropagation(); handleToolState('edit', e.detail, isReply); }, onDeleteComment: (e) => { e.stopPropagation(); handleToolState('delete', e.detail, isReply); }, 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: "flex flex-col gap-4 mt-4 px-4 pb-4" }, this.customerComments.map(comment => renderCommentItem(comment)), this.customerComments.length === 0 && !this.isLoading && (h("div", { class: "flex flex-col items-center justify-center p-8 text-theme-gray h-full" }, h("span", { class: "text-sm" }, "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E42\u0E19\u0E49\u0E15"))), this.isLoading && (h("div", { class: "flex justify-center p-2 text-theme-gray w-full" }, h(Icon, { name: "Loader2", addClass: "animate-spin size-6" })))));
    }
    handleScroll = debounce((e) => {
        const target = e.target;
        if (target.scrollTop + target.clientHeight >= target.scrollHeight - 50) {
            this.loadCustomerComments();
        }
    }, 200);
    handleClose = () => {
        this.close.emit();
    };
    handleBackdropClick = (e) => {
        e.stopPropagation();
        this.close.emit();
    };
    handleContainerClick = (e) => {
        e.stopPropagation();
    };
    render() {
        if (!this.isOpen)
            return null;
        const backdropStyle = this.containerRect ? {
            position: 'fixed',
            top: `${this.containerRect.top}px`,
            left: `${this.containerRect.left}px`,
            width: `${this.containerRect.width}px`,
            height: `${this.containerRect.height}px`,
        } : { position: 'absolute', inset: '0' };
        return (h(Host, null, h("div", { class: "z-100 flex items-end justify-center bg-black/40", style: backdropStyle, onClick: this.handleBackdropClick }, h("div", { class: "drawer-container z-animate-width", onClick: this.handleContainerClick }, h("div", { class: "drawer-header flex items-center justify-between py-3!" }, h("span", { class: "text-lg font-bold text-surface mx-auto" }, "\u0E42\u0E19\u0E49\u0E15"), h(ZIconButton, { iconName: "X", variant: "none", addClassIcon: "size-5", noPadding: true, noPaddingY: true, onClick: this.handleClose })), this.customerComments.length > 0 && (h("span", { class: "text-surface text-sm px-6" }, "\u0E42\u0E19\u0E49\u0E15 (", this.customerComments.length, ")")), h("div", { class: "drawer-content scroll-container pt-0 flex flex-col" }, h("div", { class: "flex-1 overflow-y-auto", onScroll: (e) => this.handleScroll(e) }, this.renderCommentsList()), this.renderCommentInput()))), 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-drawer"; }
    static get originalStyleUrls() {
        return {
            "$": ["../profile-ticket/profile-ticket-drawer.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["../profile-ticket/profile-ticket-drawer.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
            },
            "isOpen": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "is-open",
                "defaultValue": "false"
            }
        };
    }
    static get states() {
        return {
            "isLoading": {},
            "isImageLoading": {},
            "containerRect": {},
            "commentText": {},
            "images": {},
            "customerComments": {},
            "page": {},
            "totalPage": {},
            "hasNextPage": {},
            "customerCommentId": {},
            "customerReplyCommentId": {},
            "isEdit": {},
            "showDialog": {}
        };
    }
    static get events() {
        return [{
                "method": "close",
                "name": "close",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }, {
                "method": "commentUpdated",
                "name": "commentUpdated",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "isOpen",
                "methodName": "watchIsOpenHandler"
            }];
    }
}
