//
//  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 topFadeView: YHFadeView = {
        let view = YHFadeView()
        view.isHidden = true
        view.backgroundColor = .clear.withAlphaComponent(0.1)
        return view
    }()

    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)
        addSubview(topFadeView)
        bringSubviewToFront(topFadeView)
        topFadeView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(26)
        }

        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 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
    }
}
