//
//  LNIMConversationListController.swift
//  Lanu
//
//  Created by OneeChan on 2025/11/13.
//

import Foundation
import UIKit
import SnapKit
import MJRefresh


class LNIMConversationListController: UIViewController {
    private let notifyView = LNIMNotificationPermissionView()
    private let tableView = UITableView()
    private let redDotView = UIView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupViews()
        LNEventDeliver.addObserver(self)
        reloadList()
    }
}

extension LNIMConversationListController {
    private func reloadList() {
        LNIMManager.shared.reloadConversationList { [weak self] success in
            guard let self else { return }
            tableView.mj_header?.endRefreshing()
        }
    }
}

extension LNIMConversationListController: LNIMManagerNotify {
    func onConversationListChanged() {
        tableView.reloadData()
        tableView.mj_header?.endRefreshing()
        
        let unreadCount = LNIMManager.shared.conversationList.reduce(0) { $0 + $1.unreadCount}
        redDotView.isHidden = unreadCount <= 0
    }
}

extension LNIMConversationListController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        LNIMManager.shared.conversationList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: LNIMConversationCell.className, for: indexPath) as! LNIMConversationCell
        
        let item = LNIMManager.shared.conversationList[indexPath.row]
        cell.update(item)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let data = LNIMManager.shared.conversationList[indexPath.row]
        guard let uid = data.userID else { return }
        
        if uid.isImOfficialId {
            view.pushToOfficialMessage(uid: uid)
        } else {
            view.pushToChat(uid: uid)
        }
    }
}

extension LNIMConversationListController {
    private func setupViews() {
        view.backgroundColor = .primary_1
        
        let bg = UIImageView()
        bg.image = .icHomeTopBg
        view.addSubview(bg)
        bg.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.top.equalToSuperview()
        }
        
        let topMenu = buildTopMenu()
        view.addSubview(topMenu)
        topMenu.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.top.equalToSuperview()
        }
        
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.spacing = 16
        view.addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.bottom.equalToSuperview()
            make.top.equalTo(topMenu.snp.bottom)
        }
        
        stackView.addArrangedSubview(notifyView)
        
        let tableView = buildTableView()
        stackView.addArrangedSubview(tableView)
        
        if let tabView = tabBarItem.value(forKey: "view") as? UIView,
           let icon = tabView.subviews.first(where: { $0 is UIImageView }) {
            redDotView.backgroundColor = .fill_6
            redDotView.layer.cornerRadius = 4
            redDotView.isHidden = true
            tabView.addSubview(redDotView)
            redDotView.snp.makeConstraints { make in
                make.top.trailing.equalTo(icon)
                make.width.height.equalTo(8)
            }
        }
    }
    
    private func buildTopMenu() -> UIView {
        let container = UIView()
        container.snp.makeConstraints { make in
            make.height.equalTo(44 + UIView.statusBarHeight)
        }
        
        let titleLabel = UILabel()
        titleLabel.text = .init(key: "A00093")
        titleLabel.font = .heading_h1
        titleLabel.textColor = .text_5
        container.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(16)
            make.bottom.equalToSuperview().offset(-16)
        }
        
        let tag = UIImageView()
        tag.image = .icHomeTabSelected
        container.insertSubview(tag, belowSubview: titleLabel)
        tag.snp.makeConstraints { make in
            make.center.equalTo(titleLabel)
        }
        
        let clear = UIButton()
        clear.setImage(.icImChatClear, for: .normal)
        clear.addAction(UIAction(handler: { _ in
            let alert = LNCommonAlertView()
            alert.messageLabel.text = .init(key: "A00094")
            alert.showConfirm {
                LNIMManager.shared.cleanConversationUnread(uid: "")
            }
            alert.showCancel()
            alert.popup()
        }), for: .touchUpInside)
        container.addSubview(clear)
        clear.snp.makeConstraints { make in
            make.centerY.equalTo(titleLabel)
            make.trailing.equalToSuperview().offset(-16)
        }
        
//        let search = UIButton()
//        search.setImage(.init(named: "ic_im_chat_search"), for: .normal)
//        search.addAction(UIAction(handler: { [weak self] _ in
//            guard let self else { return }
//            view.pushToUserSearch()
//        }), for: .touchUpInside)
//        container.addSubview(search)
//        search.snp.makeConstraints { make in
//            make.centerY.equalTo(titleLabel)
//            make.trailing.equalTo(clear.snp.leading).offset(-14)
//        }
        
        return container
    }
    
    private func buildTableView() -> UIView {
        let header = MJRefreshNormalHeader { [weak self] in
            guard let self else { return }
            reloadList()
        }
        header.lastUpdatedTimeLabel?.isHidden = true
        header.stateLabel?.isHidden = true
        tableView.mj_header = header
        
        tableView.backgroundColor = .clear
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.register(LNIMConversationCell.self, forCellReuseIdentifier: LNIMConversationCell.className)
        tableView.contentInset = .init(top: 0, left: 0, bottom: 96, right: 0)
        
        return tableView
    }
}
