//
//  YHTUIMessageListManager.swift
//  galaxy
//
//  Created by alexzzw on 2025/5/22.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import Foundation
import ImSDK_Plus
import TUIConversation

// 消息列表代理
public protocol YHMessageListDelegate: AnyObject {
    func onMessageListDataSourceChanged()
    func onMessageSelected(message: TUIConversationCellData)
    func onUnreadCountChanged(unreadCount: Int, hideUnreadCount: Int)
    // 可选实现的自定义消息显示
    func getCustomMessageDisplay(conversation: V2TIMConversation) -> String?
}

// 扩展协议默认实现
public extension YHMessageListDelegate {
    func getCustomMessageDisplay(conversation: V2TIMConversation) -> String? {
        return nil
    }
}

public class YHTUIMessageListManager: NSObject {
    public static let shared = YHTUIMessageListManager()

    private var dataProvider: TUIConversationListDataProvider = TUIConversationListDataProvider()
    private var messageList: [TUIConversationCellData] = []
    public weak var delegate: YHMessageListDelegate?
    private var unreadCount: UInt64 = 0

    override private init() {
        super.init()
    }

    public func setupDataProvider() {
        dataProvider = TUIConversationListDataProvider()
        dataProvider.delegate = self
        V2TIMManager.sharedInstance().addConversationListener(listener: self)
        getTotalUnreadCount(unreadMessageCountEvent: { [weak self] count, msg in
            if msg != nil {
                self?.unreadCount = count
            }
        })
    }

    func getTotalUnreadCount(unreadMessageCountEvent: @escaping (UInt64, String?) -> Void) {
        V2TIMManager.sharedInstance().getTotalUnreadMessageCount { count in
            unreadMessageCountEvent(count, nil)
        } fail: { _, msg in
            unreadMessageCountEvent(0, msg)
        }
    }
    
    func getTotalUnreadCount() -> UInt64 {
        return unreadCount
    }

    // MARK: - Public Methods

    public func logoutIM() {
        messageList.removeAll()
        dataProvider.delegate = nil
    }
    
    /// 获取消息列表
    public func getMessageList() -> [TUIConversationCellData] {
        return messageList
    }

    /// 刷新消息列表
    public func refreshMessageList() {
        dataProvider.loadNexPageConversations()
    }

    /// 删除会话
    public func deleteConversation(_ item: TUIConversationCellData) {
        guard let conversation = findConversationData(for: item.conversationID) else {
            return
        }
        dataProvider.removeConversation(conversation)
    }

    /// 标记会话已读
    public func markAsRead(_ item: TUIConversationCellData) {
        guard let conversation = findConversationData(for: item.conversationID) else {
            return
        }
        dataProvider.markConversation(asRead: conversation)
    }

    /// 标记会话未读
    public func markAsUnread(_ item: TUIConversationCellData) {
        guard let conversation = findConversationData(for: item.conversationID) else {
            return
        }
        dataProvider.markConversation(asUnRead: conversation)
    }

    /// 置顶会话
    public func pinConversation(_ item: TUIConversationCellData, isPinned: Bool) {
        guard let conversation = findConversationData(for: item.conversationID) else {
            return
        }
        dataProvider.pinConversation(conversation, pin: isPinned)
    }

    /// 清空会话历史消息
    public func clearHistoryMessage(_ item: TUIConversationCellData) {
        guard let conversation = findConversationData(for: item.conversationID) else {
            return
        }
        dataProvider.clearHistoryMessage(conversation)
    }

    // MARK: - Private Methods

    private func findConversationData(for conversationID: String) -> TUIConversationCellData? {
        let conversationList = dataProvider.conversationList as? [TUIConversationCellData] ?? []
        return conversationList.first { $0.conversationID == conversationID }
    }

    private func updateMessageList() {
        let conversationList = dataProvider.conversationList as? [TUIConversationCellData] ?? []
        messageList = conversationList
        // 通知UI更新
        DispatchQueue.main.async { [weak self] in
            self?.delegate?.onMessageListDataSourceChanged()
        }
    }
}

// MARK: - TUIConversationListDataProviderDelegate

extension YHTUIMessageListManager: TUIConversationListDataProviderDelegate {
    public func getConversationDisplayString(_ conversation: V2TIMConversation) -> String {
        return delegate?.getCustomMessageDisplay(conversation: conversation) ?? ""
    }

    public func insertConversations(atIndexPaths indexPaths: [Any]) { // IndexPath
        updateMessageList()
    }

    public func deleteConversation(atIndexPaths indexPaths: [Any]) {
        updateMessageList()
    }

    public func reloadConversations(atIndexPaths indexPaths: [Any]) {
        updateMessageList()
    }

    public func reloadAllConversations() {
        updateMessageList()
    }

    public func updateMarkUnreadCount(_ markUnreadCount: Int, markHideUnreadCount: Int) {
        DispatchQueue.main.async { [weak self] in
            self?.delegate?.onUnreadCountChanged(unreadCount: markUnreadCount,
                                                 hideUnreadCount: markHideUnreadCount)
        }
    }
}

extension YHTUIMessageListManager: V2TIMConversationListener {
    public func onTotalUnreadMessageCountChanged(totalUnreadCount: UInt64) {
        printLog("totalUnreadCount: \(totalUnreadCount)")
        unreadCount = totalUnreadCount
        NotificationCenter.default.post(name: YhConstant.YhNotification.didTxIMUnReadMsgCountChangeNotification, object: nil)
    }
    
}
