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 { getConnectionId, getConnectionItem } from "../../utils/func";
import { debounce } from "../../utils/helpers";
import { getBusinessUser } from "./utils";
import { selectedChatStore, businessStore } from "../../store/store";
import { deleteTicketComment, deleteTicketCommentReply, getTicketComment, patchTicketComment, patchTicketCommentReply, postTicketComment, postTicketCommentReply } from "../../api/zdesk/ticket";
import { closeDialog, handleError, openDialog } from "../../store/dialog";
import { handleGetMediaUrlFromSignKey, uploadFileService } from "../../utils/upload";
export class ProfileTicketComments {
    ticketId;
    businessUserId;
    isLoading = false;
    isImageLoading = false;
    commentText = '';
    images = [];
    ticketComments = [];
    page = 1;
    totalPage = 1;
    hasNextPage = true;
    ticketCommentId = '';
    ticketReplyCommentId = '';
    isEdit = false;
    showDialog = { open: false };
    inputEl;
    componentDidLoad() {
        this.adjustHeight();
    }
    handleOpenDialog = ({ url, type }) => {
        this.showDialog = { open: true, url, type };
    };
    handleCloseDialog = () => {
        this.showDialog = { open: false };
    };
    async componentWillLoad() {
        const selectedChat = selectedChatStore.get('selectedChat');
        if (!selectedChat)
            return;
        await this.loadTicketComments();
    }
    async loadTicketComments(reset = false) {
        if (this.isLoading && !reset)
            return; // Prevent concurrent loading unless reset
        if (reset) {
            this.ticketComments = [];
            this.page = 1;
            this.hasNextPage = true;
        }
        if (!this.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.isLoading = true;
            const { data, meta } = await getTicketComment({ connectionId }, {
                ticket_id: this.ticketId,
                business_id: businessUser.business_id,
                order: PaginationOrder.DESC,
                order_by: 'created_at',
                page: this.page,
                limit: 5
            });
            this.ticketComments = [...this.ticketComments, ...data];
            this.totalPage = meta.page_count;
            this.hasNextPage = meta.has_next_page;
            this.page++;
        }
        catch (error) {
            handleError(error, 'Failed to load Ticket Comments');
        }
        finally {
            this.isLoading = false;
        }
    }
    async handleTicketComment() {
        const selectedChat = selectedChatStore.get('selectedChat');
        if (!selectedChat)
            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,
                    type: MESSAGE_TYPE.IMAGE
                };
            }
            const value = {
                business_id: businessUser.business_id,
                business_user_id: this.businessUserId,
                messages
            };
            if (this.ticketCommentId) {
                if (this.isEdit) {
                    if (this.ticketReplyCommentId) {
                        await patchTicketCommentReply({ connectionId }, { ticket_comment_id: this.ticketCommentId, id: this.ticketReplyCommentId, ...value });
                        this.ticketReplyCommentId = '';
                    }
                    else {
                        await patchTicketComment({ connectionId }, { ticket_id: this.ticketId, id: this.ticketCommentId, ...value });
                    }
                    this.isEdit = false;
                }
                else {
                    await postTicketCommentReply({ connectionId }, { ticket_comment_id: this.ticketCommentId, ...value });
                }
                this.ticketCommentId = '';
            }
            else {
                await postTicketComment({ connectionId }, { ticket_id: this.ticketId, ...value });
            }
            if (this.commentText)
                this.commentText = '';
            if (this.images.length)
                this.images = [];
            this.adjustHeight();
            await this.loadTicketComments(true);
        }
        catch (error) {
            handleError(error, 'Failed to Ticket Comment');
        }
        finally {
            this.isLoading = false;
        }
    }
    async handleDeleteTicketComment() {
        const selectedChat = selectedChatStore.get('selectedChat');
        if (!selectedChat)
            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,
                business_user_id: this.businessUserId,
            };
            if (this.ticketCommentId) {
                if (this.ticketReplyCommentId) {
                    await deleteTicketCommentReply({ connectionId }, { ticket_comment_id: this.ticketCommentId, id: this.ticketReplyCommentId, ...value });
                    this.ticketReplyCommentId = '';
                }
                else {
                    await deleteTicketComment({ connectionId }, { ticket_id: this.ticketId, id: this.ticketCommentId, ...value });
                }
                this.ticketCommentId = '';
            }
            await this.loadTicketComments(true);
        }
        catch (error) {
            handleError(error, 'Failed to Delete Ticket 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.handleTicketComment();
            }
        }
    };
    renderReplyPreview() {
        const previewId = this.ticketReplyCommentId || this.ticketCommentId;
        if (!previewId)
            return null;
        const comment = this.ticketComments.find(c => c.id === previewId) ||
            this.ticketComments.flatMap(c => c.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: "reply-preview" }, 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.ticketCommentId = '', 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: "comments-footer flex flex-col pt-2 pb-6 px-4" }, this.renderReplyPreview(), this.images.length > 0 && (h("div", { class: "chat-input-image-wrapper scroll-container" }, this.images.map((img, idx) => (h("div", { class: "relative" }, h("div", { class: "chat-input-image-button" }, h(ZIconButton, { variant: "text", iconName: "CircleX", onClick: () => this.handleRemoveImage(idx) })), h("img", { key: idx, 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('cameraInputTicketComment'))
                    document.getElementById('cameraInputTicketComment').click();
            }, isLoading: this.isImageLoading }), h("input", { type: "file", id: "cameraInputTicketComment", accept: "image/*", hidden: true, onChange: event => {
                this.handleUploadMedia(event.target.files);
                event.target.value = ''; // Reset input value to allow re-upload same file
            } }), h("div", { class: "chat-input-textarea-wrapper flex-1 relative" }, h("textarea", { class: "chat-input-textarea-input scroll-container", placeholder: t('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.handleTicketComment() }))));
    }
    renderCommentsList() {
        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.ticketCommentId = comment.ticket_comment_id;
                        this.ticketReplyCommentId = commentId;
                    }
                    else {
                        this.ticketCommentId = commentId;
                        this.ticketReplyCommentId = '';
                    }
                    break;
                case 'reply':
                    this.isEdit = false;
                    this.commentText = '';
                    this.images = [];
                    this.adjustHeight();
                    this.ticketCommentId = comment.id;
                    this.ticketReplyCommentId = '';
                    break;
                case 'delete':
                    this.isEdit = false;
                    this.commentText = '';
                    this.images = [];
                    this.adjustHeight();
                    if (isEditReply) {
                        this.ticketCommentId = comment.ticket_comment_id;
                        this.ticketReplyCommentId = commentId;
                    }
                    else {
                        this.ticketCommentId = commentId;
                        this.ticketReplyCommentId = '';
                    }
                    openDialog({
                        open: true,
                        type: "WARNING" /* DIALOG_TYPE.WARNING */,
                        title: 'ลบความคิดเห็น',
                        contentCustom: 'คุณต้องการลบความคิดเห็นนี้ใช่หรือไม่',
                        buttonName: t('confirm'),
                        cancelButtonName: t('cancel'),
                        onSubmitDialog: () => this.handleDeleteTicketComment(),
                        onCloseDialog: closeDialog,
                    });
                    break;
            }
        };
        const renderCommentItem = (comment, isReply = false, isLastReply = false) => {
            const focusId = this.ticketReplyCommentId || this.ticketCommentId;
            return (h("comment-item", { key: comment.id, comment: comment, isReply: isReply, isLastReply: isLastReply, hasActionParams: true, businessUserId: this.businessUserId, 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?.reply_comments && comment.reply_comments.length > 0 && (h("div", { class: "replies-container" }, comment.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.ticketComments.map(comment => renderCommentItem(comment)), 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.loadTicketComments();
        }
    }, 200);
    render() {
        return (h(Host, { key: 'd200c721d1cfe4fccbeab7c939ade97d4926ab26', class: "flex flex-col h-full overflow-hidden" }, h("div", { key: '3abda8100e910b94f1ab6c7aa69e77e11745602a', class: "flex-1 overflow-y-auto", onScroll: (e) => this.handleScroll(e) }, this.renderCommentsList()), this.renderCommentInput(), this.showDialog.open && (h("div", { key: '56de086afa1b3fdd7365806c280c936a50c76faa', class: "dialog-backdrop", onClick: (e) => e.stopPropagation() }, h("dialog-preview-media", { key: 'f3fcb969cd8370094243a429939aee0f78ba352e', dialogType: this.showDialog.type, url: this.showDialog.url || '', onClose: this.handleCloseDialog })))));
    }
    static get is() { return "profile-ticket-comments"; }
    static get originalStyleUrls() {
        return {
            "$": ["profile-ticket-comments.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["profile-ticket-comments.css"]
        };
    }
    static get properties() {
        return {
            "ticketId": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "ticket-id"
            },
            "businessUserId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "business-user-id"
            }
        };
    }
    static get states() {
        return {
            "isLoading": {},
            "isImageLoading": {},
            "commentText": {},
            "images": {},
            "ticketComments": {},
            "page": {},
            "totalPage": {},
            "hasNextPage": {},
            "ticketCommentId": {},
            "ticketReplyCommentId": {},
            "isEdit": {},
            "showDialog": {}
        };
    }
}
