import { h, Fragment } from "@stencil/core";
import { configStore, selectedChatStore } from "../../store/store";
import { ZIconButton } from "../internal-component/z-icon-button";
import { displayDate } from "../../utils/dayjs";
import { CUSTOM_FIELD_CONFIG_TYPE } from "../../store/zdesk.type";
import { getCustomerCustomFieldConfigsCustomer, patchCustomerCustomField, postCustomerCustomField } from "../../api/zdesk/customer";
import { getConnectionId, getConnectionItem } from "../../utils/func";
import { getBusinessUser } from "../profile-ticket/utils";
import { handleError } from "../../store/dialog";
export class CustomerInfoSection {
    user;
    readOnly = false;
    customerInfoConfigList = [];
    customerInfoFieldList = [];
    isLoading = false;
    activeTab = 'info';
    isCollapsed = false;
    showDialog = { open: false };
    isUnpinnedCollapsed = true;
    showDialogDetails = false;
    editCustomerInfo;
    saveCustomerInfo;
    cancelEdit;
    editNotes;
    async watchUserHandler(newValue, oldValue) {
        if (newValue?.id !== oldValue?.id) {
            await this.loadCustomerCustomField();
        }
    }
    async componentWillLoad() {
        if (this.user) {
            const selectedChat = selectedChatStore.get('selectedChat');
            if (!selectedChat)
                return;
            await this.loadCustomerCustomField();
        }
    }
    async loadCustomerCustomField() {
        const user = this.user;
        if (!user)
            return;
        const connectionItem = getConnectionItem();
        const connectionId = getConnectionId(connectionItem);
        const businessUser = getBusinessUser(connectionItem);
        if (!businessUser)
            return;
        try {
            this.isLoading = true;
            const customerInfoConfigs = await getCustomerCustomFieldConfigsCustomer({ connectionId }, {
                customer_id: user.id.toString(),
                business_id: businessUser.business_id,
            });
            const filterFields = customerInfoConfigs.filter((item) => item.is_show) || [];
            this.customerInfoConfigList = filterFields.sort((a, b) => a.order_index - b.order_index);
            this.customerInfoFieldList = filterFields.reduce((acc, config) => {
                if (config.customer_custom_fields?.length) {
                    acc.push(...config.customer_custom_fields);
                }
                return acc;
            }, []);
        }
        catch (error) {
            handleError(error, 'Failed to load customer custom fields');
        }
        finally {
            this.isLoading = false;
        }
    }
    handleTabChange = (tab) => {
        if (this.activeTab !== tab) {
            this.activeTab = tab;
        }
    };
    handleToggleCollapse = () => {
        this.isCollapsed = !this.isCollapsed;
    };
    renderInfoTab() {
        const isAllowEmpty = (field) => {
            return field === 'name' || field === 'phone';
        };
        const handleOpenDialogEditor = async ({ label, field, value, type = 'input', required, options }) => {
            this.showDialog = { open: true, type, label, field, value, required, options };
        };
        const handleCloseDialogEditor = () => {
            this.showDialog = { open: false };
        };
        const { pinnedConfigs, unpinnedConfigs } = this.customerInfoConfigList.reduce((acc, item) => {
            if (item.is_pinned) {
                acc.pinnedConfigs.push(item);
            }
            else {
                acc.unpinnedConfigs.push(item);
            }
            return acc;
        }, { pinnedConfigs: [], unpinnedConfigs: [] });
        const renderConfigItem = (item) => {
            const itemField = this.customerInfoFieldList.find((field) => field.custom_field_config_id === item.id);
            let labelValue = '';
            let value = '';
            let customValue = null;
            const rawValue = itemField?.value?.value;
            switch (item.type) {
                case CUSTOM_FIELD_CONFIG_TYPE.FILE: {
                    const files = (Array.isArray(rawValue) ? rawValue : []);
                    value = files.map((f) => f.url);
                    if (files.length > 0) {
                        labelValue = files.map((f) => f.name).join(', ');
                        customValue = (h("div", { class: "flex flex-col gap-1" }, files.map((f) => (h("a", { href: f.url, target: "_blank", rel: "noopener noreferrer", class: "text-sm text-primary underline" }, f.name)))));
                    }
                    break;
                }
                case CUSTOM_FIELD_CONFIG_TYPE.MULTISELECT:
                case CUSTOM_FIELD_CONFIG_TYPE.CHECKBOX: {
                    const items = (Array.isArray(rawValue) ? rawValue : []);
                    value = items.map((f) => typeof f === 'object' && f !== null ? f.value : String(f));
                    labelValue = items.map((f) => typeof f === 'object' && f !== null ? f.label || f.value : String(f)).join(', ');
                    break;
                }
                case CUSTOM_FIELD_CONFIG_TYPE.DROPDOWN:
                case CUSTOM_FIELD_CONFIG_TYPE.RADIO: {
                    if (typeof rawValue === 'object' && rawValue !== null && !Array.isArray(rawValue)) {
                        const opt = rawValue;
                        value = opt.value || '';
                        labelValue = opt.label || opt.value || '';
                    }
                    else {
                        value = rawValue != null ? String(rawValue) : '';
                        labelValue = value;
                    }
                    break;
                }
                case CUSTOM_FIELD_CONFIG_TYPE.DATE: {
                    value = rawValue != null ? String(rawValue) : '';
                    labelValue = value ? displayDate(value) : '';
                    break;
                }
                case CUSTOM_FIELD_CONFIG_TYPE.URL: {
                    value = rawValue != null ? String(rawValue) : '';
                    labelValue = value;
                    if (value) {
                        customValue = (h("a", { href: value, target: "_blank", rel: "noopener noreferrer", class: "text-sm text-primary underline break-all" }, value));
                    }
                    break;
                }
                default: {
                    value = rawValue != null ? String(rawValue) : '';
                    labelValue = value;
                    break;
                }
            }
            return (h("div", { class: "customer-info-card-content", key: item.id }, h("div", { class: "flex flex-row items-start justify-between" }, h("div", { class: "flex flex-col" }, h("span", { class: "customer-info-key" }, item.name), customValue ? customValue : h("span", { class: "customer-info-value" }, labelValue || '-')), h(ZIconButton, { variant: "text", iconName: "Pencil", addClassIcon: "size-4", noPadding: true, noPaddingY: true, onClick: () => handleOpenDialogEditor({
                    label: item.name,
                    field: item.key,
                    value: value,
                    type: item.type,
                    required: item.is_required,
                    options: item.options,
                }) }))));
        };
        const handleSaveDialogEditor = async (field, value) => {
            try {
                const connectionItem = getConnectionItem();
                const connectionId = getConnectionId(connectionItem);
                const businessUser = getBusinessUser(connectionItem);
                if (!businessUser)
                    return;
                const customerInfoConfig = this.customerInfoConfigList.find((item) => item.key === field);
                if (!customerInfoConfig)
                    return;
                const customerInfoField = this.customerInfoFieldList.find((item) => item.custom_field_config_id === customerInfoConfig.id);
                const selectedOption = customerInfoConfig.options?.find((item) => item.value === value);
                const saveValue = { value: selectedOption || value };
                if (customerInfoField) {
                    await patchCustomerCustomField({ connectionId }, {
                        business_id: businessUser.business_id,
                        id: customerInfoField.id,
                        customer_id: this.user.id,
                        value: saveValue
                    });
                    this.customerInfoFieldList = this.customerInfoFieldList.map((item) => item.id === customerInfoField.id ? { ...item, value: saveValue } : item);
                }
                else {
                    const response = await postCustomerCustomField({ connectionId }, {
                        business_id: businessUser.business_id,
                        customer_id: this.user.id,
                        custom_field_config_id: customerInfoConfig.id,
                        value: saveValue
                    });
                    this.customerInfoFieldList = [...this.customerInfoFieldList, response];
                }
                handleCloseDialogEditor();
            }
            catch (error) {
                handleError(error, 'Failed to update customer custom field');
            }
        };
        return (h("div", { class: "customer-info-cards" }, pinnedConfigs.map(renderConfigItem), unpinnedConfigs.length > 0 && (h(Fragment, null, h("div", { class: "flex w-full items-center justify-center cursor-pointer mb-2", onClick: () => this.isUnpinnedCollapsed = !this.isUnpinnedCollapsed }, h("div", { class: "grow border-t border-divider" }), h("div", { class: "flex flex-row items-center gap-1 mx-4 text-primary" }, h("span", { class: "text-sm text-primary select-none" }, this.isUnpinnedCollapsed ? 'แสดง' : 'ซ่อน'), h(ZIconButton, { variant: "text", iconName: this.isUnpinnedCollapsed ? 'ChevronDown' : 'ChevronUp', addClassIcon: "size-4 text-primary", noPadding: true, noPaddingY: true })), h("div", { class: "grow border-t border-divider" })), !this.isUnpinnedCollapsed && unpinnedConfigs.map(renderConfigItem))), this.showDialog.open && (h("div", { class: "dialog-backdrop", onClick: (e) => e.stopPropagation() }, h("dialog-editor", { label: this.showDialog.label, dialogType: this.showDialog.type, field: this.showDialog.field, value: this.showDialog.value, options: this.showDialog.options, allowEmpty: isAllowEmpty(this.showDialog.field) && !this.showDialog.required, onCancel: handleCloseDialogEditor, onSave: (event) => handleSaveDialogEditor(this.showDialog.field, event ? event.detail : undefined) })))));
    }
    render() {
        const theme = configStore.get('theme');
        return (h("div", { key: 'b065a14da4b241b233e516d3a4e8023e7978a792', class: "customer-info-section-wrapper", "data-theme": theme }, h("div", { key: 'da261208b541127973385140b0338432b59666ff', class: "customer-info-header" }, h("div", { key: '8f6f4dc7fe1fb3c241575cbfc38052cc6ef9ce40', class: "customer-info-tabs" }, h("button", { key: '9c4dc599614058ad4e5a21e66fa0f97415aba78f', class: `customer-info-tab ${this.activeTab === 'info' ? 'active' : ''}`, onClick: () => this.handleTabChange('info') }, "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E25\u0E39\u0E01\u0E04\u0E49\u0E32"), h("button", { key: '46f995c89cfa1339c5213b4a8b5ef591e9ec5b84', class: `customer-info-tab ${this.activeTab === 'notes' ? 'active' : ''}`, onClick: () => this.handleTabChange('notes') }, "\u0E42\u0E19\u0E49\u0E15")), h(ZIconButton, { key: '45a26ab5121a503f26b23885d05f8256e7878d2f', iconName: this.isCollapsed ? 'ChevronDown' : 'ChevronUp', onClick: this.handleToggleCollapse, variant: 'none' })), !this.isCollapsed && (h(Fragment, { key: '6f091f5742608884372643de9d598a771227ca50' }, h("div", { key: '703289f74d4302cf025fd18e19d26670bdfe420e', class: "customer-info-body" }, this.activeTab === 'info' ? this.renderInfoTab() : (h("customer-info-comment", { user: this.user, readOnly: this.readOnly, onEditNotes: () => this.editNotes.emit() })))))));
    }
    static get is() { return "customer-info-section"; }
    static get originalStyleUrls() {
        return {
            "$": ["customer-info-section.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["customer-info-section.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 {
            "customerInfoConfigList": {},
            "customerInfoFieldList": {},
            "isLoading": {},
            "activeTab": {},
            "isCollapsed": {},
            "showDialog": {},
            "isUnpinnedCollapsed": {},
            "showDialogDetails": {}
        };
    }
    static get events() {
        return [{
                "method": "editCustomerInfo",
                "name": "editCustomerInfo",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }, {
                "method": "saveCustomerInfo",
                "name": "saveCustomerInfo",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }, {
                "method": "cancelEdit",
                "name": "cancelEdit",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }, {
                "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"
            }];
    }
}
