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

import Foundation
import UIKit
import SnapKit
import MJRefresh


class LNOrderRoomApplySeatListPanel: LNPopupView {
    private let emptyView = LNNoMoreDataView()
    private let countLabel = UILabel()
    private let countDescLabel = UILabel()
    private let tableView = UITableView(frame: .zero, style: .plain)
    
    private weak var roomSession: LNOrderRoomViewModel?
    private var nextTag: String? = nil
    private var items: [LNRoomMicApplyPageVO] = []
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        containerHeight = .percent(0.62)
        
        setupViews()
    }
    
    func update(_ room: LNOrderRoomViewModel?) {
        roomSession = room
        
        loadList()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

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

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

private extension LNOrderRoomApplySeatListPanel {
    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
    }
    
    func setupViews() {
        container.backgroundColor = .fill_7
        
        let countView = buildCountView()
        container.addSubview(countView)
        countView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(16)
            make.horizontalEdges.equalToSuperview().inset(16)
            make.height.equalTo(20)
        }
        
        let clearButton = UIButton()
        clearButton.layer.cornerRadius = 23.5
        clearButton.layer.borderColor = UIColor.fill.withAlphaComponent(0.2).cgColor
        clearButton.layer.borderWidth = 1
        clearButton.setTitle(.init(key: "A00372"), 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?.cancelSeatApply { [weak self] success in
                guard let self else { return }
                guard success else { return }
                
                dismiss()
            }
        }), for: .touchUpInside)
        container.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 }
            self.nextTag = nil
            self.loadList()
        }
        header.lastUpdatedTimeLabel?.isHidden = true
        header.stateLabel?.isHidden = true
        tableView.mj_header = header
        
        let footer = MJRefreshAutoNormalFooter { [weak self] in
            guard let self else { return }
            self.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.register(LNOrderRoomApplySeatCell.self, forCellReuseIdentifier: LNOrderRoomApplySeatCell.className)
        container.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(countView.snp.bottom).offset(12)
            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)
        }
    }
    
    func buildCountView() -> UIView {
        let container = UIView()
        
        countLabel.font = .body_m
        countLabel.textColor = .text_1
        container.addSubview(countLabel)
        countLabel.snp.makeConstraints { make in
            make.leading.centerY.equalToSuperview()
        }
        
        return container
    }
}
