//
//  YHLiveMessageListView.swift
//  galaxy
//
//  Created by alexzzw on 2024/11/25.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import HyphenateChat
import UIKit

class YHLiveMessageListView: UIView {
    private var messages: [EMChatMessage] = []
    var anchorName: String?

    // MARK: - UI Components

    private lazy var tableView: UITableView = {
        let view = UITableView()
        view.backgroundColor = .clear
        view.separatorStyle = .none
        view.showsVerticalScrollIndicator = false
        view.allowsSelection = false
        view.delegate = self
        view.dataSource = self
        view.transform = CGAffineTransform(rotationAngle: .pi)
        view.register(YHLiveMessageCell.self, forCellReuseIdentifier: YHLiveMessageCell.reuseIdentifier)
        return view
    }()

    // MARK: - Initialization

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        backgroundColor = .clear
        addSubview(tableView)

        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.bottom.right.equalToSuperview()
        }
        
        // 添加 KVO
        tableView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)
    }

    // MARK: - Public Methods

    func addMessages(_ msgs: [EMChatMessage]) {
        messages.insert(contentsOf: msgs, at: 0)
        let indexPaths = (0 ..< msgs.count).map {
            IndexPath(row: $0, section: 0)
        }
        tableView.insertRows(at: indexPaths, with: .bottom)
    }

    func clearMessages() {
        messages.removeAll()
        tableView.reloadData()
    }
    
    deinit {
        // 移除 KVO
        tableView.removeObserver(self, forKeyPath: "contentSize")
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "contentSize" {
            fadeCells()
        }
    }
    
    private func fadeCells() {
        // 内容大小变化
        let fadeRange: CGFloat = 50

        tableView.visibleCells.forEach { cell in
            guard let indexPath = tableView.indexPath(for: cell) else { return }
            let cellRect = tableView.rectForRow(at: indexPath)

            // 因为视图是倒置的，所以我们需要用 tableView 的高度来计算正确的位置
            let cellPositionFromBottom = tableView.bounds.height - (cellRect.origin.y - tableView.contentOffset.y) - cellRect.height

            if cellPositionFromBottom >= 0 && cellPositionFromBottom <= fadeRange {
                let progress = cellPositionFromBottom / fadeRange
                cell.alpha = progress
            } else if cellPositionFromBottom > fadeRange {
                cell.alpha = 1.0
            } else {
                cell.alpha = 0.0
            }
        }
    }
}

// MARK: - UITableViewDelegate & UITableViewDataSource

extension YHLiveMessageListView: UITableViewDelegate, UITableViewDataSource {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        fadeCells()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return messages.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard messages.count > indexPath.row else {
            return UITableViewCell()
        }
        guard let cell = tableView.dequeueReusableCell(
            withIdentifier: YHLiveMessageCell.reuseIdentifier) as? YHLiveMessageCell else {
            return UITableViewCell()
        }
        let message = messages[indexPath.row]
        // cell 也需要旋转
        cell.contentView.transform = CGAffineTransform(rotationAngle: .pi)
        var nickName: String = ""
        var content: String = ""
        var highlight: String = ""
        if let ext = message.ext {
            nickName = ext["fromNickName"] as? String ?? "YinHe"
            highlight = ext["replyTo"] as? String ?? ""
        }
        if let body = message.body as? EMTextMessageBody, body.type == .text {
            // IM 文本消息
            printLog(body.text)
            printLog("\(nickName) : \(body.text)")
            content = body.text
            let isAnchor = nickName == anchorName
            cell.configureNormalMessage(nickName, content, highlightTxt: highlight, isAnchor: isAnchor)
        } else if let body = message.body as? EMCustomMessageBody, body.event == YHChatRoomCustomLocal.tipsEvent, let customExt = body.customExt, let tips = customExt[YHChatRoomCustomLocal.tipsKey] {
            // 直播间提示消息
            cell.configureTipsMessage(tips)
        } else if let body = message.body as? EMCustomMessageBody, body.event == YHChatRoomCustomLocal.userEnterRoomEvent, let customExt = body.customExt, let userName = customExt[YHChatRoomCustomLocal.userEnterRoomEvent] {
            // 用户加入直播间消息
            cell.configureUserEnterRoomMessage(userName)
        }
        
        return cell
    }
}
