//
//  LNOrderListViewController.swift
//  Lanu
//
//  Created by OneeChan on 2025/11/18.
//

import Foundation
import UIKit
import SnapKit
import MJRefresh


extension UIView {
    func pushToOrderList() {
        let vc = LNOrderListViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
}


class LNOrderListViewController: LNViewController {
    private var isLoading = false
    private let emptyView = LNNoMoreDataView()
    private let tableView = UITableView()
    
    private var orders: [LNOrderListItemVO] = []
    private var nextTag: String? = nil
    private let pageSize = 30
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupViews()
        
        tableView.mj_header?.beginRefreshing()
        
        LNEventDeliver.addObserver(self)
    }
}

extension LNOrderListViewController {
    private func loadOrderList() {
        guard !isLoading else { return }
        
        isLoading = true
        
        LNOrderManager.shared.getList(size: pageSize, next: nextTag) { [weak self] list, next in
            guard let self else { return }
            isLoading = false
            if let list, let next {
                if nextTag?.isEmpty == false {
                    orders.append(contentsOf: list)
                } else {
                    orders = list
                }
                nextTag = next
                tableView.reloadData()
                
                if orders.isEmpty {
                    emptyView.showNoData(icon: .icNoDataOrderEmpty, tips: .init(key: "A00153"))
                } else {
                    emptyView.hide()
                }
            } else {
                if orders.isEmpty {
                    emptyView.showNetworkError()
                }
            }
            tableView.mj_header?.endRefreshing()
            if next?.isEmpty != false {
                tableView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                tableView.mj_footer?.endRefreshing()
            }
        }
    }
}

extension LNOrderListViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        orders.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: LNOrderListItemCell.className, for: indexPath) as! LNOrderListItemCell
        let item = orders[indexPath.row]
        cell.update(item)
        
        return cell
    }
}

extension LNOrderListViewController: LNOrderManagerNotify {
    func onOrderInfoChanged(orderId: String) {
        tableView.reloadData()
    }
}

extension LNOrderListViewController {
    private func setupViews() {
        title = .init(key: "A00154")
        view.backgroundColor = .primary_1
        
        let header = MJRefreshNormalHeader { [weak self] in
            guard let self else { return }
            self.nextTag = nil
            self.loadOrderList()
        }
        header.lastUpdatedTimeLabel?.isHidden = true
        header.stateLabel?.isHidden = true
        tableView.mj_header = header
        
        let footer = MJRefreshAutoNormalFooter { [weak self] in
            guard let self else { return }
            if self.nextTag == nil { return }
            self.loadOrderList()
        }
        footer.setTitle("", for: .noMoreData)
        footer.setTitle(.init(key: "A00046"), for: .idle)
        tableView.mj_footer = footer
        tableView.backgroundColor = .clear
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.register(LNOrderListItemCell.self, forCellReuseIdentifier: LNOrderListItemCell.className)
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.top.equalToSuperview().offset(6)
            make.bottom.equalToSuperview()
        }
        
        tableView.addSubview(emptyView)
        emptyView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().multipliedBy(0.6)
        }
    }
}

#if DEBUG

import SwiftUI

struct LNOrderListViewControllerPreview: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> some UIViewController {
        LNOrderListViewController()
    }
    
    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) { }
}

#Preview(body: {
    LNOrderListViewControllerPreview()
})
#endif
