//
//  LNOrderRoomManageSeatListView.swift
//  Gami
//
//  Created by OneeChan on 2026/3/18.
//

import Foundation
import UIKit
import SnapKit
import MJRefresh


class LNOrderRoomManageSeatListView: UIView {
    private let emptyView = LNNoMoreDataView()
    private let tabType: LNRoomApplySeatType
    
    private let countLabel = UILabel()
    private let filterButton = UIButton()
    private let tableView = UITableView(frame: .zero, style: .plain)
    private let clearButton = UIButton()
    
    private weak var roomSession: LNOrderRoomViewModel?
    private var nextTag: String? = nil
    private var items: [LNRoomMicApplyPageVO] = []
    
    private var categories: [LNGameCategoryItemVO] = []
    
    private var curCode: String = ""
    private var curTitle: String = .init(key: "A00361")
    
    init(tabType: LNRoomApplySeatType) {
        self.tabType = tabType
        super.init(frame: .zero)
        
        setupViews()
    }
    
    func update(room: LNOrderRoomViewModel?) {
        roomSession = room
        loadList()
        if tabType == .playmate {
            loadCategory()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNOrderRoomManageSeatListView {
    private func loadList() {
        guard let roomSession else { return }
        let currentNextTag = nextTag
        roomSession.getApplyList(type: tabType == .guest ? .guest : .playmate,
                                 next: currentNextTag,
                                 filter: curCode)
        { [weak self] res in
            guard let self else { return }
            if let list = res?.list {
                if currentNextTag == nil {
                    items.removeAll()
                }
                items.append(contentsOf: list)
                nextTag = res?.next
                tableView.reloadData()
                updateCountView()
                
                if items.isEmpty {
                    emptyView.showNoData(tips: .init(key: "A00005"))
                } else {
                    emptyView.hide()
                }
            } else {
                if items.isEmpty {
                    emptyView.showNetworkError()
                }
            }
            
            tableView.mj_header?.endRefreshing()
            if currentNextTag?.isEmpty != false {
                tableView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                tableView.mj_footer?.endRefreshing()
            }
        }
    }
    
    private func loadCategory() {
        roomSession?.getApplyListCategory { [weak self] res in
            guard let self else { return }
            guard let res else { return }
            categories = res.list
        }
    }
}

extension LNOrderRoomManageSeatListView: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(
            withIdentifier: LNOrderRoomManageSeatCell.className,
            for: indexPath
        ) as! LNOrderRoomManageSeatCell
        let item = items[indexPath.row]
        cell.update(room: roomSession, item: item, index: indexPath.row + 1)
        return cell
    }
}

extension LNOrderRoomManageSeatListView {
    private func updateCountView() {
        let text = String(key: "A00333", items.count)
        let range = (text as NSString).range(of: .init(key: "A00334", items.count))
        let attrString = NSMutableAttributedString(string: text)
        attrString.addAttributes([
            .foregroundColor: UIColor.text_6
        ], range: range)
        countLabel.attributedText = attrString
    }
    
    private func updateFilterView() {
        filterButton.setTitle(curTitle, for: .normal)
    }
    
    private func setupViews() {
        backgroundColor = .clear
        
        let countView = buildCountView()
        addSubview(countView)
        countView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.horizontalEdges.equalToSuperview().inset(16)
            make.height.equalTo(30)
        }
        
        clearButton.layer.cornerRadius = 23.5
        clearButton.layer.borderColor = UIColor.fill.withAlphaComponent(0.2).cgColor
        clearButton.layer.borderWidth = 1
        clearButton.setTitle(.init(key: "A00335"), for: .normal)
        clearButton.setTitleColor(.text_2, for: .normal)
        clearButton.titleLabel?.font = .heading_h3
        clearButton.addAction(UIAction(handler: { [weak self] _ in
            guard let self else { return }
            roomSession?.clearApplyList(type: tabType) { [weak self] success in
                guard let self else { return }
                guard success else { return }
                
                nextTag = nil
                loadList()
            }
        }), for: .touchUpInside)
        addSubview(clearButton)
        clearButton.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().offset(commonBottomInset)
            make.height.equalTo(47)
        }
        
        let header = MJRefreshNormalHeader { [weak self] in
            guard let self else { return }
            nextTag = nil
            loadList()
        }
        header.lastUpdatedTimeLabel?.isHidden = true
        header.stateLabel?.isHidden = true
        tableView.mj_header = header
        
        let footer = MJRefreshAutoNormalFooter { [weak self] in
            guard let self else { return }
            loadList()
        }
        footer.setTitle("", for: .noMoreData)
        footer.setTitle(.init(key: "A00046"), for: .idle)
        tableView.mj_footer = footer
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.allowsSelection = false
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(LNOrderRoomManageSeatCell.self, forCellReuseIdentifier: LNOrderRoomManageSeatCell.className)
        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(countView.snp.bottom).offset(8)
            make.horizontalEdges.equalToSuperview()
            make.bottom.equalTo(clearButton.snp.top)
        }
        
        tableView.addSubview(emptyView)
        emptyView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().multipliedBy(0.6)
        }
        
        updateCountView()
        updateFilterView()
    }
    
    private func buildCountView() -> UIView {
        let container = UIView()
        
        countLabel.font = .body_m
        countLabel.textColor = .text_1
        countLabel.numberOfLines = 0
        container.addSubview(countLabel)
        countLabel.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.leading.equalToSuperview()
            make.trailing.lessThanOrEqualToSuperview().priority(.medium)
        }
        
        if tabType == .playmate {
            let config = UIImage.SymbolConfiguration(pointSize: 12)
            filterButton.backgroundColor = .fill.withAlphaComponent(0.15)
            filterButton.layer.cornerRadius = 15
            filterButton.clipsToBounds = true
            filterButton.titleLabel?.font = .body_s
            filterButton.setTitleColor(.text_1, for: .normal)
            filterButton.setImage(.init(systemName: "chevron.backward", withConfiguration: config), for: .normal)
            filterButton.tintColor = .text_1
            filterButton.semanticContentAttribute = .forceRightToLeft
            filterButton.imageEdgeInsets = .init(top: 0, left: 4, bottom: 0, right: -4)
            filterButton.contentEdgeInsets = .init(top: 0, left: 12, bottom: 0, right: 12)
            filterButton.addAction(UIAction(handler: { [weak self] _ in
                guard let self, tabType == .playmate else { return }
                
                let panel = LNOrderRoomGameCategoryFilterPanel()
                let options = buildPlaymateFilterOptions()
                panel.update(options: options, curSelectedCode: curCode)
                panel.handler = { [weak self] option in
                    guard let self else { return }
                    curCode = option.code
                    curTitle = option.code.isEmpty ? .init(key: "A00361") : option.name
                    updateFilterView()
                    
                    nextTag = nil
                    tableView.mj_header?.beginRefreshing()
                }
                panel.popup(self)
            }), for: .touchUpInside)
            container.addSubview(filterButton)
            filterButton.snp.makeConstraints { make in
                make.centerY.trailing.equalToSuperview()
                make.height.equalTo(30)
                make.leading.greaterThanOrEqualTo(countLabel.snp.trailing).offset(16)
                make.width.lessThanOrEqualTo(131)
            }
            filterButton.setContentHuggingPriority(.required, for: .horizontal)
            filterButton.setContentCompressionResistancePriority(.required, for: .horizontal)
        }
        
        return container
    }
    
    private func buildPlaymateFilterOptions() -> [LNGameCategoryItemVO] {
        var options: [LNGameCategoryItemVO] = []
        options.append(.init(code: "", name: .init(key: "A00360"), icon: "", categoryType: .normal))
        options.append(contentsOf: categories)
        
        return options
    }
}
