//
//  LNUserRelationListView.swift
//  Lanu
//
//  Created by OneeChan on 2025/12/22.
//

import Foundation
import UIKit
import SnapKit
import MJRefresh


protocol LNUserRelationListViewDelegate: AnyObject {
    func onUserRelationListViewTotalChanged(view: LNUserRelationListView, total: Int)
}


class LNUserRelationListView: UIView {
    private let emptyView = LNNoMoreDataView()
    private let tableView = UITableView()
    let curType: LNUserRelationTabType
    
    private var curList: [LNRelationUserVO] = []
    private var nextTag: String = ""
    
    weak var delegate: LNUserRelationListViewDelegate?
    
    init(curType: LNUserRelationTabType) {
        self.curType = curType
        super.init(frame: .zero)
        
        setupViews()
        
        tableView.mj_header?.beginRefreshing()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNUserRelationListView {
    private func loadList() {
        let completion: ([LNRelationUserVO]?, String?, Int?) -> Void = { [weak self] list, next, total in
            guard let self else { return }
            if let list, let next, let total {
                if nextTag.isEmpty {
                    curList = list
                } else {
                    curList.append(contentsOf: list)
                }
                tableView.reloadData()
                
                nextTag = next
                delegate?.onUserRelationListViewTotalChanged(view: self, total: total)
                
                if curList.isEmpty {
                    let text: String = switch curType {
                    case .follow: .init(key: "A00236")
                    case .fans: .init(key: "A00237")
                    }
                    emptyView.showNoData(icon: .icNoDataRelationEmpty, tips: text)
                } else {
                    emptyView.hide()
                }
            } else {
                if curList.isEmpty {
                    emptyView.showNetworkError()
                }
            }
            
            self.tableView.mj_header?.endRefreshing()
            if next?.isEmpty != false {
                tableView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                tableView.mj_footer?.endRefreshing()
            }
        }
        
        switch curType {
        case .follow:
            LNRelationManager.shared.getUserFollowList(next: nextTag, handler: completion)
        case .fans:
            LNRelationManager.shared.getUserFansList(next: nextTag, handler: completion)
        }
    }
}

extension LNUserRelationListView: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        curList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: LNUserRelationItemCell.className, for: indexPath) as! LNUserRelationItemCell
        
        let item = curList[indexPath.row]
        cell.update(item)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
        
        let item = curList[indexPath.row]
        pushToProfile(uid: item.userNo)
    }
}

extension LNUserRelationListView {
    private func setupViews() {
        let header = MJRefreshNormalHeader { [weak self] in
            guard let self else { return }
            self.nextTag = ""
            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.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.register(LNUserRelationItemCell.self, forCellReuseIdentifier: LNUserRelationItemCell.className)
        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        tableView.addSubview(emptyView)
        emptyView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().multipliedBy(0.6)
        }
    }
}
