//
//  LNRoomPublicBoardView.swift
//  Gami
//
//  Created by OneeChan on 2026/3/9.
//

import Foundation
import UIKit
import SnapKit
import Combine


class LNRoomMessageView: UIView {
    private let tableView = UITableView()
    private let maxMessageCount = 300
    private weak var roomSession: LNRoomSession?
    
    private var items: [LNRoomMessageItem] = []
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupViews()
        LNEventDeliver.addObserver(self)
    }
    
    func update(_ room: LNRoomSession?) {
        roomSession = room
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNRoomMessageView: LNRoomViewModelNotify {
    func onRoomMessageChanged(session: LNRoomSession, messages: [any LNRoomMessageItem]) {
        guard roomSession == session else { return }
        items.append(contentsOf: messages)
        if items.count > maxMessageCount {
            items.removeFirst(Int(Double(maxMessageCount) * 0.3))
        }
        tableView.reloadData()
        tableView.scrollToBottom()
    }
}

extension LNRoomMessageView: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let message = items[indexPath.row]
        
        if let userMessage = message as? LNRoomChatMessageItem {
            let cell = tableView.dequeueReusableCell(withIdentifier: LNRoomChatMessageCell.className, for: indexPath) as! LNRoomChatMessageCell
            cell.update(userMessage)
            return cell
        } else if let welcomeMessage = message as? LNRoomWelcomeMessageItem {
            let cell = tableView.dequeueReusableCell(withIdentifier: LNRoomWelcomeMessageCell.className, for: indexPath) as! LNRoomWelcomeMessageCell
            cell.update(welcomeMessage)
            return cell
        } else if let giftMessage = message as? LNRoomGiftMessageItem {
            let cell = tableView.dequeueReusableCell(withIdentifier: LNRoomGiftMessageCell.className, for: indexPath) as! LNRoomGiftMessageCell
            cell.update(giftMessage)
            return cell
        }
        
        return tableView.dequeueReusableCell(withIdentifier: LNRoomUnknownMessageCell.className, for: indexPath)
    }
}

extension LNRoomMessageView {
    private func setupViews() {
        tableView.dataSource = self
        tableView.allowsSelection = false
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        tableView.alwaysBounceVertical = true
        tableView.showsVerticalScrollIndicator = false
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.contentInset = .init(top: 0, left: 0, bottom: 16, right: 0)
        tableView.register(LNRoomChatMessageCell.self, forCellReuseIdentifier: LNRoomChatMessageCell.className)
        tableView.register(LNRoomGiftMessageCell.self, forCellReuseIdentifier: LNRoomGiftMessageCell.className)
        tableView.register(LNRoomSystemMessageCell.self, forCellReuseIdentifier: LNRoomSystemMessageCell.className)
        tableView.register(LNRoomWelcomeMessageCell.self, forCellReuseIdentifier: LNRoomWelcomeMessageCell.className)
        tableView.register(LNRoomUnknownMessageCell.self, forCellReuseIdentifier: LNRoomUnknownMessageCell.className)
        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        let bottomGradientView = UIView.gradientView([
            .init(hex: "#010B2300"), .init(hex: "#010B23")
        ], .verticalUTD)
        addSubview(bottomGradientView)
        bottomGradientView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(44)
        }
    }
}

