import { Host, h } from "@stencil/core";
import { Icon } from "../internal-component/icon";
import { useTranslation } from "../../utils/utils";
import { ZIconButton } from "../internal-component/z-icon-button";
import { ZInput } from "../internal-component/z-input";
import { ZButton } from "../internal-component/z-button";
import { getChargeLogo, getChargeName, getPaymentName } from "../../utils/order";
import dayjs from "dayjs";
import { ZInputArea } from "../internal-component/z-input-area";
import { updateUserOrder } from "../../api";
import { handleError } from "../../store/dialog";
import { selectedChatStore } from "../../store/store";
import { getConnectionId } from "../../utils/func";
export class ProfileOrderCard {
    el;
    order;
    isExpanded = false;
    isTrackingModalOpen = false;
    isCancelReasonModalOpen = false;
    editingTrackingNo = '';
    editingCancelReason = '';
    isUpdating = false;
    isAddressModalOpen = false;
    editingAddress = {
        name: '',
        phone_number: '',
        address: '',
        district: '',
        sub_district: '',
        province: '',
        zip_code: '',
    };
    orderUpdated;
    handleOrderStatusChange = (value) => {
        if (value === this.order.status)
            return;
        if (value === "shipped") {
            this.openTrackingModal();
        }
        else if (value === "canceled") {
            this.openCancelReasonModal();
        }
        else {
            this.updateUserOrder({
                status: value
            });
        }
    };
    updateUserOrder = async ({ status, trackingNo, sendTrackingStatus, reason, sendReason, shipping_address, }) => {
        const selectedChat = selectedChatStore.get('selectedChat');
        if (!selectedChat)
            return;
        const { channel } = selectedChat;
        const type = selectedChat.type === 'group' ? 'group' : 'user';
        const selectedChatType = selectedChat[type];
        const id = selectedChatType ? selectedChatType.id : '';
        const connectionId = getConnectionId();
        try {
            this.isUpdating = true;
            await updateUserOrder({
                connectionId: connectionId,
                channel: channel,
                userId: id,
                orderId: this.order.id.toString(),
                status: status,
                trackingNo: trackingNo,
                sendTrackingStatus: sendTrackingStatus,
                reason: reason,
                sendReason: sendReason,
                shipping_address: shipping_address,
            });
            this.orderUpdated.emit();
        }
        catch (error) {
            handleError(error, 'Failed to update order');
        }
        finally {
            this.isUpdating = false;
        }
    };
    toggleExpand = () => {
        this.isExpanded = !this.isExpanded;
    };
    formatPrice(price) {
        if (Number.isNaN(price))
            return '฿0.00';
        return new Intl.NumberFormat('th-TH', {
            style: 'currency',
            currency: 'THB',
            minimumFractionDigits: 2,
        }).format(price);
    }
    get orderStatusOptions() {
        return [
            { id: 'pending', name: 'pending' },
            { id: 'ordered', name: 'ordered' },
            { id: 'paid', name: 'paid' },
            { id: 'shipped', name: 'shipped' },
            { id: 'unpaid', name: 'unpaid' },
            { id: 'canceled', name: 'canceled' },
        ];
    }
    handleCopyTracking = () => {
        if (this.order.tracking_no) {
            navigator.clipboard.writeText(this.order.tracking_no);
        }
    };
    openTrackingModal() {
        this.editingTrackingNo = this.order.tracking_no || '';
        this.isTrackingModalOpen = true;
    }
    closeTrackingModal() {
        this.isTrackingModalOpen = false;
        if (this.order.status === 'shipped')
            return;
        this.updateUserOrder({
            status: 'shipped',
        });
    }
    saveTrackingNo = async (isSend = false) => {
        this.isTrackingModalOpen = false;
        this.updateUserOrder({
            status: 'shipped',
            trackingNo: this.editingTrackingNo,
            sendTrackingStatus: isSend,
        });
    };
    openCancelReasonModal() {
        this.editingCancelReason = this.order.reason || '';
        this.isCancelReasonModalOpen = true;
    }
    closeCancelReasonModal() {
        this.isCancelReasonModalOpen = false;
    }
    saveCancelReason = async (isSend = false) => {
        this.isCancelReasonModalOpen = false;
        this.updateUserOrder({
            status: 'canceled',
            reason: this.editingCancelReason,
            sendReason: isSend,
        });
    };
    isValidTrackingNo(value, regexOnly = false) {
        if (!regexOnly) {
            if (value == null || value.length === 0)
                return false;
            if (value === this.order.tracking_no)
                return false;
        }
        const regex = /^[a-zA-Z0-9]+$/;
        return regex.test(value);
    }
    isValidCancelReason(value) {
        if (value === this.order.reason)
            return false;
        return true;
    }
    renderTrackingNoModal() {
        if (!this.isTrackingModalOpen)
            return null;
        const t = useTranslation();
        const isEdit = this.order.status === 'shipped';
        return (h("div", { class: "modal-overlay" }, h("div", { class: "modal-content" }, h("h3", { class: "modal-title" }, t('chat_profile_view.tracking_no')), h("div", { class: "modal-input-container" }, h("div", { class: "flex-1" }, h(ZInput, { value: this.editingTrackingNo, onChange: (value) => this.editingTrackingNo = value, error: this.isValidTrackingNo(this.editingTrackingNo, true) || this.editingTrackingNo.length === 0 ? '' : t('chat_profile_view.tracking_no_error') })), h("button", { onClick: () => this.saveTrackingNo(true) }, h(Icon, { name: "Send", addClass: `h-4 w-4  ${this.isValidTrackingNo(this.editingTrackingNo, true) && this.editingTrackingNo.length > 0 ? 'text-primary cursor-pointer' : 'text-gray-400 cursor-not-allowed'}` }))), h("div", { class: "modal-actions" }, h(ZButton, { variant: "outlined", label: isEdit ? t('cancel') : t('later'), onClick: () => this.closeTrackingModal(), fullWidth: true, disabled: this.isUpdating }), h(ZButton, { variant: "primary", label: this.isUpdating ? h(Icon, { name: "LoaderCircle", addClass: "job-icon animate-spin" }) : t('save'), onClick: () => this.saveTrackingNo(), fullWidth: true, disabled: !this.isValidTrackingNo(this.editingTrackingNo) || this.isUpdating })))));
    }
    renderCancelReasonModal() {
        if (!this.isCancelReasonModalOpen)
            return null;
        const t = useTranslation();
        const isEdit = this.order.status === 'canceled';
        return (h("div", { class: "modal-overlay" }, h("div", { class: "modal-content" }, !isEdit && (h("div", { class: "flex flex-col items-center gap-1 mb-4" }, h(Icon, { name: "AlertCircle", addClass: "h-[60px] w-[60px] text-primary" }), h("p", { class: "text-[18px] font-bold text-surface text-center" }, t('chat_profile_view.order.cancel_confirm_title')), h("p", { class: "text-[14px] text-surface text-center" }, t('chat_profile_view.order.cancel_confirm_message')))), h("h3", { class: "modal-title" }, t('chat_profile_view.cancel_reason_placeholder')), h("div", { class: "modal-input-container" }, h("div", { class: "flex-1" }, h(ZInputArea, { value: this.editingCancelReason, onChange: (value) => this.editingCancelReason = value })), h("button", { onClick: () => this.saveCancelReason(true) }, h(Icon, { name: "Send", addClass: `h-4 w-4  ${this.editingCancelReason.length > 0 ? 'text-primary cursor-pointer' : 'text-gray-400 cursor-not-allowed'}` }))), h("div", { class: "modal-actions" }, h(ZButton, { variant: "outlined", label: isEdit ? t('cancel') : t('later'), onClick: () => this.closeCancelReasonModal(), fullWidth: true, disabled: this.isUpdating }), h(ZButton, { variant: "primary", label: isEdit ? t('save') : t('confirm'), onClick: () => this.saveCancelReason(), fullWidth: true, disabled: (!this.isValidCancelReason(this.editingCancelReason) && isEdit) || this.isUpdating })))));
    }
    handleOpenAddressModal = () => {
        this.editingAddress = {
            name: this.order.shipping_address.name,
            phone_number: this.order.shipping_address.tel,
            address: this.order.shipping_address.address,
            province: this.order.shipping_address.province,
            district: this.order.shipping_address.district,
            sub_district: this.order.shipping_address.sub_district,
            zip_code: this.order.shipping_address.zipcode,
        };
        this.isAddressModalOpen = true;
    };
    handleCloseDialogEditor = () => {
        this.isAddressModalOpen = false;
    };
    handleSaveDialogEditor = (address) => {
        this.isAddressModalOpen = false;
        this.updateUserOrder({
            shipping_address: address,
        });
    };
    renderAddressModal() {
        if (!this.isAddressModalOpen)
            return null;
        const t = useTranslation();
        return (h("div", { class: "modal-overlay" }, h("dialog-editor", { label: t('address'), dialogType: "order_address", value: this.editingAddress, allowEmpty: false, onCancel: this.handleCloseDialogEditor, onSave: (event) => this.handleSaveDialogEditor(event.detail) })));
    }
    render() {
        if (!this.order)
            return null;
        const t = useTranslation();
        const { order } = this;
        const address = order.shipping_address;
        return (h(Host, null, h("div", { class: `profile-order-card ${this.isUpdating ? 'updating' : ''}` }, this.isUpdating && (h("div", { class: "loading-overlay" }, h(Icon, { name: "LoaderCircle", addClass: "w-8 h-8 text-primary animate-spin" }))), this.renderTrackingNoModal(), this.renderCancelReasonModal(), this.renderAddressModal(), h("div", { class: "order-header" }, h("div", { class: "order-no" }, t('chat_profile_view.order_no'), ": ", order.id || '-'), h("div", { class: "order-status" }, h("z-dropdown-input", { placeholder: t('chat_profile_view.order_status_label'), options: this.orderStatusOptions.map(opt => ({
                value: opt.id,
                label: t(`chat_profile_view.order_status.${opt.name}`)
            })), value: order.status, disabled: order.status === 'canceled' || this.isUpdating, disabledOptions: order.status === 'unpaid' ? ['pending', 'ordered', 'paid', 'shipped', 'unpaid'] : [], hideOptions: ['unpaid'], enableSearch: false, onValueChange: (e) => this.handleOrderStatusChange(e.detail) }))), order.status === 'shipped' && (h("div", { class: "tracking-row" }, h("div", { class: "tracking-label" }, t('chat_profile_view.tracking_no'), ": ", order.tracking_no || '-'), h("div", { class: "tracking-actions" }, h("button", { class: "tracking-icon-btn", onClick: () => this.openTrackingModal() }, h(Icon, { name: "Pencil", addClass: "h-4 w-4" })), order.tracking_no && [
            h("button", { class: "tracking-icon-btn", onClick: this.handleCopyTracking }, h(Icon, { name: "Copy", addClass: "h-4 w-4" })),
            h("button", { class: "tracking-icon-btn", onClick: () => {
                    this.updateUserOrder({
                        status: this.order.status,
                        trackingNo: this.order.tracking_no,
                        sendTrackingStatus: true,
                    });
                } }, h(Icon, { name: "Send", addClass: "h-4 w-4" }))
        ]))), order.status === 'canceled' && (h("div", { class: "tracking-row" }, h("div", { class: "tracking-label" }, t('chat_profile_view.cancel_reason'), ": ", order.reason || '-'), h("div", { class: "tracking-actions" }, h("button", { class: "tracking-icon-btn", onClick: () => this.openCancelReasonModal() }, h(Icon, { name: "Pencil", addClass: "h-4 w-4" })), order.reason && [
            h("button", { class: "tracking-icon-btn", onClick: () => {
                    this.updateUserOrder({
                        status: this.order.status,
                        reason: this.order.reason,
                        sendReason: true,
                    });
                } }, h(Icon, { name: "Send", addClass: "h-4 w-4" }))
        ]))), h("div", { class: "shipping-info" }, h("div", { class: "shipping-info-title" }, t('chat_profile_view.shipping_info')), h("div", { class: "shipping-address-container" }, h("div", { class: "shipping-address-text" }, h("div", null, address?.name || '-', " (", address?.tel || '-', ")"), h("div", null, address?.address || '-', ", ", address?.sub_district || '-', ", ", address?.district || '-', ", ", address?.province || '-', ", ", address?.zipcode || '-')), h("div", { class: "address-action-btn" }, h(ZIconButton, { variant: "text", iconName: "Pencil", addClassIcon: 'h-4 w-4', onClick: () => this.handleOpenAddressModal() })))), h("div", { class: "card-divider" }), this.isExpanded && (h("div", { class: "order-items-container" }, order.product_details?.map(item => (h("div", { class: "order-item" }, h("img", { src: item.photourl, class: "item-image", alt: item.name }), h("div", { class: "item-details" }, h("div", { class: "item-name" }, item.name), item.option && h("div", { class: "item-option" }, item.option)), h("div", { class: "item-pricing" }, h("div", { class: "item-qty" }, "x", item.quantity), h("div", { class: "item-price" }, this.formatPrice(item.price)))))))), h("div", { class: "summary-section" }, h("div", { class: "summary-row" }, h("span", { class: "summary-label" }, t('chat_profile_view.subtotal_items', { count: order.product_details?.reduce((acc, item) => acc + item.quantity, 0) || 0 })), h("span", { class: "summary-value" }, this.formatPrice(order.product_details?.reduce((acc, item) => acc + (item.quantity * item.price_per_unit), 0)))), h("div", { class: "summary-row" }, h("span", { class: "summary-label" }, t('chat_profile_view.shipping_fee')), h("span", { class: "summary-value" }, this.formatPrice(order.shipping_charge || 0))), h("div", { class: "summary-row" }, h("span", { class: "summary-label" }, t('chat_profile_view.discount')), h("span", { class: "summary-value" }, this.formatPrice(order.discount || 0))), h("div", { class: "card-divider hidden-divider" }), h("div", { class: "total-payment-row", onClick: this.toggleExpand }, h("span", { class: "total-label" }, t('chat_profile_view.total_payment')), h("span", { class: "total-value" }, this.formatPrice(order.amount || 0)), h(Icon, { name: this.isExpanded ? 'ChevronUp' : 'ChevronDown', addClass: `expand-icon w-4 h-4 text-surface` })), h("div", { class: "payment-method-row" }, h("span", { class: "summary-label" }, t('chat_profile_view.payment_method')), h("span", { class: "summary-value" }, getPaymentName(order.payment) || '-')), order.shipping_type && (h("div", { class: "shipping-type-row" }, h("div", { class: "shipping-type-content" }, h("img", { src: getChargeLogo(order.shipping_type), alt: getChargeName(order.shipping_type), class: "shipping-type-logo", onError: (e) => {
                // Fallback to other_charge.png if logo not found
                e.target.src = getChargeLogo('other_charge');
            } }), h("span", { class: "shipping-type-name" }, getChargeName(order.shipping_type))))), h("div", { class: "last-update" }, t('chat_profile_view.last_update'), " ", dayjs(order.timestamp).format('DD/MM/YYYY HH:mm'))))));
    }
    static get is() { return "profile-order-card"; }
    static get originalStyleUrls() {
        return {
            "$": ["profile-order-card.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["profile-order-card.css"]
        };
    }
    static get properties() {
        return {
            "order": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "UserOrder",
                    "resolved": "{ id: number; amount: number; name_address: string; product_details: UserOrderProductDetail[]; status: string; reason: string; remark: string; payment: string; tracking_no: string; timestamp: string; shipping_type: string; shipping_charge: number; shipping_address: UserOrderShippingAddress; cost: number; discount: number; total: number; invoice_no: string; }",
                    "references": {
                        "UserOrder": {
                            "location": "import",
                            "path": "../../api/type",
                            "id": "src/api/type.ts::UserOrder",
                            "referenceLocation": "UserOrder"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            }
        };
    }
    static get states() {
        return {
            "isExpanded": {},
            "isTrackingModalOpen": {},
            "isCancelReasonModalOpen": {},
            "editingTrackingNo": {},
            "editingCancelReason": {},
            "isUpdating": {},
            "isAddressModalOpen": {},
            "editingAddress": {}
        };
    }
    static get events() {
        return [{
                "method": "orderUpdated",
                "name": "orderUpdated",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }];
    }
    static get elementRef() { return "el"; }
}
