//
//  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()
        }
    }

    // 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()
    }
}

// MARK: - UITableViewDelegate & UITableViewDataSource

extension YHLiveMessageListView: UITableViewDelegate, UITableViewDataSource {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        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 - scrollView.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
            }
        }
    }
    
    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 = ""
        if let ext = message.ext {
            nickName = ext["fromNickName"] as? String ?? "YinHe"
        }
        if let body = message.body as? EMTextMessageBody, body.type == .text {
            printLog(body.text)
            printLog("\(nickName) : \(body.text)")
            content = body.text
            let isAnchor = nickName == anchorName
            cell.configureNormalMessage(nickName, content, 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)
        }
        
        return cell
    }
}
