import DOMPurify from 'dompurify';
import { marked } from 'marked';
import {
    isCustomerServiceMessage,
    MESSAGE_TYPES,
    CUSTOM_MESSAGE_SRC,
    type IMessageModel,
    JSONToObject,
} from '@tencentcloud/ai-desk-core';
import { getLocale, translate } from '../locales';

export interface customerServicePayloadType {
    customerServicePlugin: number;
    src: string;
    content: any;
    text?: string;
    isFinished?: number;
    chunks?: string[];
    subtype?: string;
    nodeStatus?: number;
    isCustomerClick?: boolean;
    sendFrom?: string;
}

export interface PreviewImageItem {
    messageId: string;
    src: string;
}

const PREVIEW_IMAGE_CHILD_ID_REGEXP = /__rich_text_image_\d+$/;

const getCurrentIntlLocale = () => {
    return getLocale() || (typeof navigator !== 'undefined' ? navigator.language : 'zh-CN');
};

export const getLocalizedTimezone = (timeZone: string) => {
    try {
        const formatter = new Intl.DateTimeFormat(getCurrentIntlLocale(), {
            timeZone,
            timeZoneName: 'long',
        });
        const parts = formatter.formatToParts(new Date());
        const timeZonePart = parts.find((part) => part.type === 'timeZoneName');
        return timeZonePart ? timeZonePart.value : timeZone;
    } catch (error) {
        console.error(error);
        return timeZone;
    }
};

export const getLocalizedUserLanguage = (language: string) => {
    const normalizedLanguage = String(language || '').trim();

    const languageMap: Record<string, string> = {
        zh: translate('简体中文'),
        'zh-CN': translate('简体中文'),
        'zh-Hans': translate('简体中文'),
        'zh-TW': translate('繁体中文'),
        'zh-Hant': translate('繁体中文'),
        en: translate('英文'),
        'en-US': translate('英文'),
        vi: translate('越南语'),
        id: translate('印度尼西亚语'),
        ja: translate('日语'),
        fil: translate('菲律宾语'),
        ms: translate('马来语'),
        th: translate('泰语'),
        ru: translate('俄语'),
        ko: translate('韩语'),
        es: translate('西班牙语'),
    };

    return languageMap[normalizedLanguage] || normalizedLanguage;
};

export const getLocalizedCountry = (country: string) => {
    try {
        const displayNames = new Intl.DisplayNames([getCurrentIntlLocale()], {
            type: 'region',
        });
        return displayNames.of(String(country || '').toUpperCase()) || country;
    } catch (error) {
        console.error(error);
        return country;
    }
};

const extractImageSourcesFromHtml = (htmlContent: string) => {
    if (!htmlContent || typeof DOMParser === 'undefined') {
        return [];
    }

    try {
        const sanitizedHtml = DOMPurify.sanitize(htmlContent, {
            ADD_ATTR: ['target'],
        });
        const parser = new DOMParser();
        const doc = parser.parseFromString(sanitizedHtml, 'text/html');

        return Array.from(doc.querySelectorAll('.richText-image-container img, .rich-text img, img'))
            .map((img) => img.getAttribute('src') ?? '')
            .filter(Boolean);
    } catch (error) {
        console.error(error);
        return [];
    }
};

export const getPreviewSourceMessageId = (previewImageId: string) => {
    return previewImageId.replace(PREVIEW_IMAGE_CHILD_ID_REGEXP, '');
};

export const getPreviewableImageItems = (
    message: IMessageModel,
    options?: { includeRevoked?: boolean },
) => {
    if ((!options?.includeRevoked && message.isRevoked) || !message.ID) {
        return [] as PreviewImageItem[];
    }

    if (message.type === MESSAGE_TYPES.MSG_IMAGE) {
        const src = message?.payload?.imageInfoArray?.[0]?.url ?? '';
        return src ? [{ messageId: message.ID, src }] : [];
    }

    if (message.type === MESSAGE_TYPES.MSG_FILE) {
        const src = message?.payload?.fileUrl ?? message?.payload?.url ?? '';
        const isImageFile = /\.(png|jpe?g|gif|bmp|webp|svg)(\?.*)?$/i.test(src);
        return src && isImageFile ? [{ messageId: message.ID, src }] : [];
    }

    if (message.type === MESSAGE_TYPES.MSG_CUSTOM && isCustomerServiceMessage(message)) {
        const customerServicePayload = JSONToObject(message?.payload?.data) ?? {};

        if (String(customerServicePayload?.src ?? '') === CUSTOM_MESSAGE_SRC.RICH_TEXT) {
            if (typeof customerServicePayload?.content !== 'string') {
                return [];
            }

            const htmlContent = marked.parse(customerServicePayload.content, {
                async: false,
            }) as string;

            return extractImageSourcesFromHtml(htmlContent).map((src, index) => ({
                messageId: `${message.ID}__rich_text_image_${index}`,
                src,
            }));
        }

        if (String(customerServicePayload?.src ?? '') === CUSTOM_MESSAGE_SRC.STREAM_TEXT) {
            const markdownContent = Array.isArray(customerServicePayload?.chunks)
                ? customerServicePayload.chunks
                    .map((item: any) => {
                        if (typeof item === 'string') {
                            return item;
                        }
                        if (typeof item === 'number' || typeof item === 'boolean') {
                            return String(item);
                        }
                        return '';
                    })
                    .join('')
                : '';
            const htmlContent = marked.parse(markdownContent, {
                async: false,
            }) as string;

            return extractImageSourcesFromHtml(htmlContent).map((src, index) => ({
                messageId: `${message.ID}__rich_text_image_${index}`,
                src,
            }));
        }
    }

    return [] as PreviewImageItem[];
};

export const isSeatSideMessage = (message: IMessageModel) => {
    try {
        if (message.conversationID?.startsWith('C2C') && message.flow === 'in') {
            return false;
        }
        if (message.flow === 'out') {
            return true;
        }
        if (message.from === 'administrator') {
            return true;
        }
        if (message.cloudCustomData !== '') {
            const customerData = JSON.parse(message.cloudCustomData);
            if (customerData?.role === 'seat') {
                return true;
            }
        }
        return false;
    } catch (e) {
        console.error(e);
        return false;
    }
};

const targetProperties = [
    'clientUserID',
    'clientUserNickName',
    'fromMemberUserID',
    'fromMemberNickName',
    'peerMemberUserID',
    'peerMemberNickName',
];
export const isInterveneMergeMessage = (message: IMessageModel): boolean => {
    try {
        if (message.type === MESSAGE_TYPES.MSG_MERGER) {
            const cloudCustomData = message?.cloudCustomData;
            const customerServicePayload = JSON.parse(cloudCustomData);
            const targetObject = customerServicePayload?.relayUserInfo;
            if (typeof targetObject === 'object' && targetObject !== null) {
                return targetProperties.every((prop) => prop in targetObject);
            }
            return false;
        }
        return false;
    } catch (e) {
        console.log(e);
        return false;
    }
};

const formatRichMessageWithTag = (content: string) => {
    try {
        // 1. 转换图片为[图片]
        let text = content.replace(/!\[.*?\]\(.*?\)/g, translate('[图片]'));
        text = text.replace(/<video[^>]*?(?:\/>|>.*?<\/video>)/gis, translate('[视频]'));
        // 2. 转换链接为[超链接]
        text = text.replace(/\[.*?\]\(.*?\)/g, translate('[超链接]'));
        // 3. 移除所有HTML标签（安全过滤）
        text = text.replace(/<[^>]*>/g, '');
        // 4. 处理其他Markdown语法（可选）
        text = text
            .replace(/#+\s*/g, '') // 移除标题标记
            .replace(/\*\*([^*]+)\*\*/g, '$1') // 移除加粗
            .replace(/\*([^*]+)\*/g, '$1'); // 移除斜体
        // 5. 合并所有空白字符为单个空格并去除首尾空格
        text = text.replace(/\s+/g, ' ').trim();
        return text;
    } catch (e) {
        console.log(e);
        return translate('[自定义消息]');
    }
};

export const formateMessageAbstract = (
    message: IMessageModel,
    currentUserId?: string,
) => {
    if (message.isRevoked) {
        if (message.flow === 'in') {
            return translate('对方撤回了一条消息');
        }
        if (message.flow === 'out') {
            return translate('你撤回了一条消息');
        }
    }
    if (message?.revokerInfo && message?.revokerInfo?.userID !== '') {
        if (message?.revokerInfo?.userID !== currentUserId) {
            return translate('对方撤回了一条消息');
        }
        return translate('你撤回了一条消息');
    }
    if (message.type === MESSAGE_TYPES.MSG_TEXT) {
        return message.payload.text;
    }
    if (message.type === MESSAGE_TYPES.MSG_IMAGE) {
        return translate('[图片消息]');
    }
    if (message.type === MESSAGE_TYPES.MSG_VIDEO) {
        return translate('[视频消息]');
    }
    if (message.type === MESSAGE_TYPES.MSG_AUDIO) {
        return translate('[音频消息]');
    }
    if (message.type === MESSAGE_TYPES.MSG_FILE) {
        return translate('[文件消息]');
    }
    if (message.type === MESSAGE_TYPES.MSG_LOCATION) {
        return translate('[位置消息]');
    }
    if (message.type === MESSAGE_TYPES.MSG_MERGER) {
        return translate('[聊天记录]');
    }
    if (message.type === MESSAGE_TYPES.MSG_STREAM) {
        if (!message.payload.markdown) {
            return translate('[流式消息]');
        }
        return formatRichMessageWithTag(message.payload.markdown);
    }
    if (message.type === MESSAGE_TYPES.MSG_CUSTOM) {
        if (isCustomerServiceMessage(message)) {
            const customerServicePayload = JSONToObject(message?.payload?.data);
            if (
                customerServicePayload?.src === CUSTOM_MESSAGE_SRC.RICH_TEXT &&
                typeof customerServicePayload?.content === 'string'
            ) {
                return formatRichMessageWithTag(customerServicePayload.content);
            }
            if (customerServicePayload?.src === CUSTOM_MESSAGE_SRC.STREAM_TEXT) {
                if (typeof customerServicePayload?.chunks?.join('') === 'string') {
                    return formatRichMessageWithTag(
                        customerServicePayload?.chunks?.join(''),
                    );
                }
            }
            if (
                customerServicePayload?.src === CUSTOM_MESSAGE_SRC.WELCOME_CARD &&
                typeof customerServicePayload?.content?.title === 'string'
            ) {
                return customerServicePayload?.content?.title;
            }
            if (
                customerServicePayload?.src === CUSTOM_MESSAGE_SRC.BRANCH &&
                typeof customerServicePayload?.content?.header === 'string'
            ) {
                return customerServicePayload?.content?.header;
            }
            if (
                customerServicePayload?.src === CUSTOM_MESSAGE_SRC.NEW_BRANCH &&
                typeof customerServicePayload?.content?.header === 'string'
            ) {
                return customerServicePayload?.content?.header;
            }
            if (
                customerServicePayload?.src === CUSTOM_MESSAGE_SRC.NEW_INFO_COLLECT &&
                typeof customerServicePayload?.content?.tip === 'string'
            ) {
                return customerServicePayload?.content?.tip;
            }
            if (customerServicePayload?.src === CUSTOM_MESSAGE_SRC.SESSION_TAKEOVER) {
                if (currentUserId === customerServicePayload?.content?.seat) {
                    return translate('会话已介入');
                } else {
                    return translate('当前会话已被 {name} 介入', {
                        name: customerServicePayload?.content?.seat ?? '',
                    });
                }
            }
            if (
                customerServicePayload?.src === CUSTOM_MESSAGE_SRC.USER_TIMEOUT_REMIND
            ) {
                return customerServicePayload?.content;
            }
            if (customerServicePayload?.src === CUSTOM_MESSAGE_SRC.MENU) {
                if (customerServicePayload?.sendFrom === 'agent') {
                    return translate('您已成功向用户发送了评价邀请');
                }
                if (customerServicePayload?.sendFrom === 'user') {
                    return translate('用户主动发起评价邀请');
                }
                if (customerServicePayload?.sendFrom === 'system') {
                    return translate('系统发送了评价邀请');
                }
                return translate('您已成功向用户发送了评价邀请');
            }
            if (customerServicePayload?.src === CUSTOM_MESSAGE_SRC.MENU_SELECTED) {
                return translate('用户已对您的服务作出评价');
            }
            if (customerServicePayload?.src === CUSTOM_MESSAGE_SRC.NO_SEAT_ONLINE) {
                return translate('暂无客服在线');
            }
            if (customerServicePayload?.src === CUSTOM_MESSAGE_SRC.END) {
                return translate('会话已结束');
            }
            if (customerServicePayload?.src === CUSTOM_MESSAGE_SRC.TIMEOUT) {
                return translate('会话超时结束');
            }
        }
        return translate('[自定义消息]');
    }
    if (message.type === MESSAGE_TYPES.MSG_FACE) {
        return translate('[表情]');
    }
};

const normalizeTimestamp = (timestamp: number) =>
    timestamp > 946684800000 ? timestamp : timestamp * 1000;

const padNumber = (value: number) => String(value).padStart(2, '0');

const getStartOfDay = (date: Date) =>
    new Date(date.getFullYear(), date.getMonth(), date.getDate());

const getStartOfYear = (date: Date) => new Date(date.getFullYear(), 0, 1);

const getStartOfISOWeek = (date: Date) => {
    const startOfDay = getStartOfDay(date);
    const day = startOfDay.getDay();
    const diff = day === 0 ? 6 : day - 1;

    startOfDay.setDate(startOfDay.getDate() - diff);
    return startOfDay;
};

const subtractDays = (date: Date, days: number) => {
    const result = new Date(date);
    result.setDate(result.getDate() - days);
    return result;
};

const formatDate = (date: Date, format: 'HH:mm' | 'MM-DD' | 'YY-MM-DD') => {
    const year = date.getFullYear();
    const month = padNumber(date.getMonth() + 1);
    const day = padNumber(date.getDate());
    const hours = padNumber(date.getHours());
    const minutes = padNumber(date.getMinutes());

    switch (format) {
        case 'HH:mm':
            return `${hours}:${minutes}`;
        case 'MM-DD':
            return `${month}-${day}`;
        case 'YY-MM-DD':
            return `${String(year).slice(-2)}-${month}-${day}`;
        default:
            return '';
    }
};


export function getSessionShowTime(timestamp: number) {
    const weekDays = [
        translate('星期日'),
        translate('星期一'),
        translate('星期二'),
        translate('星期三'),
        translate('星期四'),
        translate('星期五'),
        translate('星期六'),
    ];
    const time = new Date(normalizeTimestamp(timestamp));
    const now = new Date();
    const today = getStartOfDay(now);
    const yesterday = getStartOfDay(subtractDays(now, 1));
    const thisYear = getStartOfYear(now);
    const thisWeek = getStartOfISOWeek(now);
    const diffMs = now.getTime() - time.getTime();
    const hourDiff = Math.floor(diffMs / (60 * 60 * 1000));
    const minuteDiff = Math.floor(diffMs / (60 * 1000));

    if (hourDiff === 0) {
        if (minuteDiff <= 5) {
            return translate('刚刚');
        }
        return translate('{minutes}分钟前', { minutes: minuteDiff });
    }
    if (time.getTime() >= today.getTime()) {
        return formatDate(time, 'HH:mm');
    }
    if (time.getTime() >= yesterday.getTime()) {
        return translate('昨天');
    }
    if (time.getTime() >= thisWeek.getTime()) {
        return weekDays[time.getDay()];
    }
    if (time.getTime() >= thisYear.getTime()) {
        return formatDate(time, 'MM-DD');
    }
    return formatDate(time, 'YY-MM-DD');
}

function handleGroupProfileUpdated(message: IMessageModel) {
    const { nick, payload } = message;
    const { newGroupProfile, memberList, operatorID } = payload;
    let text: string = '';
    // 优先取 nick，nick 不存在时取 userID
    const showName: string = nick || operatorID;
    const key = Object.keys(newGroupProfile)[0];
    if (!key) {
        return text;
    }
    switch (key) {
        case 'muteAllMembers':
            if (newGroupProfile[key]) {
                text = `${translate('管理员')} ${showName} ${translate('开启全员禁言')}`;
            } else {
                text = `${translate('管理员')} ${showName} ${translate('取消全员禁言')}`;
            }
            break;
        case 'ownerID':
            text = `${memberList[0].nick || memberList[0].userID} ${translate('成为新的群主')}`;
            break;
        case 'groupName':
            text = `${showName} ${translate('修改群名为')} ${newGroupProfile[key]}`;
            break;
        case 'notification':
            text = `${showName} ${translate('发布新公告')}`;
            break;
        default:
            break;
    }
    return text;
}

export function formatGroupTipsMessage(message: IMessageModel) {
    let text = '';
    // 优先取 nick，nick 不存在时取 userID，以下逻辑是为兼容不同群提示消息的处理
    let showName: string = message?.nick || message?.payload?.userIDList?.join(',');
    if (message?.payload?.memberList?.length > 0) {
        showName = '';
        message?.payload?.memberList?.map((user: { nick?: string; userID: string }) => {
            showName += `${user?.nick || user?.userID},`;
        });
        showName = showName?.slice(0, -1);
    }

    switch (message.payload.operationType) {
        case 1:
            text = `${showName} ${translate('加入群组')}`;
            break;
        case 2:
            text = `${translate('群成员')}：${showName} ${translate('退出群组')}`;
            break;
        case 3:
            text = `${translate('群成员')}：${showName} ${translate('被踢出群组')}`;
            break;
        case 4:
            text = `${translate('群成员')}：${showName} ${translate('成为管理员')}`;
            break;
        case 5:
            text = `${translate('群成员')}：${showName} ${translate('被撤销管理员')}`;
            break;
        case 6:
            text = handleGroupProfileUpdated(message);
            break;
        case 7:
            for (const member of message.payload.memberList) {
                if (member.muteTime > 0) {
                    text = `${translate('群成员')}：${showName} ${translate('被禁言')}`;
                } else {
                    text = `${translate('群成员')}：${showName} ${translate('被取消禁言')}`;
                }
            }
            break;
        default:
            text = translate('群提示消息');
            break;
    }
    return text;
}

export const PEER_SOURCE =
{
    '0': '电话', // pstn user
    '1': '内线', // 座席账号
    '2': '微信小程序', // 微信小程序(自定义)
    '3': '微信公众号', // 公众号
    '4': '网页', // 网站用户
    '5': '微信公众号', // 订阅号
    '6': '微信小程序', // 服务号小程序(标准)
    '7': '微信客服', // 微信客服
    '8': '安卓', // 安卓
    '10': '即时通信IM渠道', // 即时通信IM渠道
    '11': 'WhatsApp',
    '12': 'Facebook Messenger',
    '13': 'Viber',
    '14': 'Telegram',
};

export function getSessionShowSource
    (peerSource: string, clientData?: string) {
    if (clientData && typeof clientData === 'object') {
        try {
            const clientDataObj = JSON.parse(JSON.stringify(clientData));
            if (clientDataObj?.peerSource && clientDataObj?.peerSource !== '') {
                return clientDataObj?.peerSource;
            }
        } catch (e) {
            console.log(e);
        }
    }
    if (typeof clientData === 'string' && clientData !== '') {
        try {
            return JSON.parse(clientData)?.peerSource || '';
        } catch (e) {
            console.log(e);
        }
    }
    const sourceKey = peerSource
        ? PEER_SOURCE[peerSource as keyof typeof PEER_SOURCE]
        : '';
    if (!sourceKey) {
        return translate('未知来源');
    }
    // WhatsApp / Facebook Messenger / Viber / Telegram 等品牌名不做翻译
    return translate(sourceKey);
}

export function getReplyMessageOriginType(message: IMessageModel) {
    switch (message.type) {
        case MESSAGE_TYPES.MSG_TEXT:
            return 1;
        case MESSAGE_TYPES.MSG_IMAGE:
            return 3;
        case MESSAGE_TYPES.MSG_VIDEO:
            return 5;
        case MESSAGE_TYPES.MSG_AUDIO:
            return 4;
        case MESSAGE_TYPES.MSG_CUSTOM:
            return 2;
        case MESSAGE_TYPES.MSG_FILE:
            return 6;
        default:
            return 0;
    }
}