//
//  LNRoomListViewController.swift
//  Gami
//
//  Created by OneeChan on 2026/3/26.
//

import Foundation
import UIKit
import MJRefresh
import SnapKit


class LNRoomListViewController: UIViewController {
    private let emptyView = LNNoMoreDataView()
    private var items: [LNRoomItemVO] = []
    private var nextTag: String? = nil
    private let collectionView: UICollectionView
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        let width = (UIScreen.main.bounds.width - 16 * 2 - 13) * 0.5
        
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 16
        layout.minimumInteritemSpacing = 13
        layout.itemSize = .init(width: width, height: width * 204 / 165)
        self.collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupViews()
        
        nextTag = nil
        items.removeAll()
        collectionView.reloadData()
        emptyView.hide()
        collectionView.mj_footer?.resetNoMoreData()
        collectionView.mj_header?.beginRefreshing()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNRoomListViewController {
    private func loadList() {
        LNRoomManager.shared.getRoomList(next: nextTag) { [weak self] res in
            guard let self else { return }
            guard let list = res?.list else {
                collectionView.mj_header?.endRefreshing()
                collectionView.mj_footer?.endRefreshingWithNoMoreData()
                
                if items.isEmpty {
                    emptyView.showNetworkError()
                }
                return
            }
            
            if nextTag?.isEmpty != false {
                items = list
            } else {
                items.append(contentsOf: list)
            }
            nextTag = res?.next
            
            collectionView.reloadData()
            if items.isEmpty {
                emptyView.showNoData(tips: .init(key: "A00244"))
            } else {
                emptyView.hide()
            }
            
            collectionView.mj_header?.endRefreshing()
            if res?.next.isEmpty != false {
                collectionView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                collectionView.mj_footer?.endRefreshing()
            }
        }
    }
}

extension LNRoomListViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        items.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(
            withReuseIdentifier: LNRoomListCardCell.className,
            for: indexPath
        ) as! LNRoomListCardCell
        cell.update(items[indexPath.item])
        return cell
    }
}

extension LNRoomListViewController {
    private func setupViews() {
        view.backgroundColor = .primary_1
        
        let fakeNavBar = LNFakeNaviBar()
        fakeNavBar.isUserInteractionEnabled = false // 因为是空白
        view.addSubview(fakeNavBar)
        fakeNavBar.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.top.equalToSuperview()
        }
        
        let titleLabel = UILabel()
        titleLabel.text = .init(key: "A00370")
        titleLabel.font = .heading_h3
        titleLabel.textColor = .text_5
        fakeNavBar.actionView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        
        let header = MJRefreshNormalHeader { [weak self] in
            guard let self else { return }
            nextTag = nil
            loadList()
        }
        header.lastUpdatedTimeLabel?.isHidden = true
        header.stateLabel?.isHidden = true
        collectionView.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)
        collectionView.mj_footer = footer
        
        collectionView.backgroundColor = .clear
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.allowsSelection = false
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(LNRoomListCardCell.self, forCellWithReuseIdentifier: LNRoomListCardCell.className)
        collectionView.contentInset = .init(top: 6, left: 0, bottom: -view.commonBottomInset, right: 0)
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.top.equalTo(fakeNavBar.snp.bottom)
            make.bottom.equalToSuperview()
        }
        
        collectionView.addSubview(emptyView)
        emptyView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().multipliedBy(0.6)
        }
    }
}

private final class LNRoomListCardCell: UICollectionViewCell {
    private let cardView = LNUserSearchRoomCardView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(cardView)
        cardView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func update(_ item: LNRoomItemVO) {
        cardView.update(item)
    }
}
