//
//  OrderSourcePickerViewController.swift
//  suixinkan
//

import SnapKit
import UIKit

/// 订单来源获客员选择 Bottom Sheet 首页，点击获客员后 push 带客单页。
final class OrderSourcePickerViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    private let orderNumber: String
    private let viewModel: OrderListViewModel
    private let referralOrder: BoundReferralOrderEntity?
    private let loadLeads: (OrderSourcePerson) async -> Void
    private let onLeadBound: (OrderSourceSelection) -> Void
    private let onCallPhone: (String) -> Void

    private let subtitleLabel = UILabel()
    private let tableView = UITableView(frame: .zero, style: .plain)
    private let loadingIndicator = UIActivityIndicatorView(style: .medium)
    private let emptyLabel = UILabel()

    init(
        orderNumber: String,
        viewModel: OrderListViewModel,
        referralOrder: BoundReferralOrderEntity?,
        loadLeads: @escaping (OrderSourcePerson) async -> Void,
        onLeadBound: @escaping (OrderSourceSelection) -> Void,
        onCallPhone: @escaping (String) -> Void
    ) {
        self.orderNumber = orderNumber
        self.viewModel = viewModel
        self.referralOrder = referralOrder
        self.loadLeads = loadLeads
        self.onLeadBound = onLeadBound
        self.onCallPhone = onCallPhone
        super.init(nibName: nil, bundle: nil)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "选择获客员"
        navigationItem.largeTitleDisplayMode = .never
        view.backgroundColor = .white
        setupUI()
        applyViewModel()
    }

    func reloadFromViewModel() {
        applyViewModel()
        (navigationController?.topViewController as? OrderSourceLeadListViewController)?
            .reloadFromViewModel()
    }

    private func setupUI() {
        subtitleLabel.font = .systemFont(ofSize: 13)
        subtitleLabel.textColor = AppColor.text666
        subtitleLabel.text = "选择人员后，再选择该人员创建的带客单"
        subtitleLabel.numberOfLines = 0

        tableView.separatorStyle = .none
        tableView.backgroundColor = .white
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(OrderSourcePersonCell.self, forCellReuseIdentifier: OrderSourcePersonCell.reuseIdentifier)

        loadingIndicator.hidesWhenStopped = true
        loadingIndicator.color = AppColor.primary

        emptyLabel.font = .systemFont(ofSize: 14)
        emptyLabel.textColor = AppColor.text666
        emptyLabel.textAlignment = .center
        emptyLabel.numberOfLines = 0
        emptyLabel.text = "暂无合作获客员"

        view.addSubview(subtitleLabel)
        view.addSubview(tableView)
        view.addSubview(loadingIndicator)
        view.addSubview(emptyLabel)

        subtitleLabel.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide).offset(AppSpacing.md)
            make.leading.trailing.equalToSuperview().inset(AppSpacing.md)
        }
        tableView.snp.makeConstraints { make in
            make.top.equalTo(subtitleLabel.snp.bottom).offset(14)
            make.leading.trailing.bottom.equalToSuperview()
        }
        loadingIndicator.snp.makeConstraints { make in
            make.center.equalTo(tableView)
        }
        emptyLabel.snp.makeConstraints { make in
            make.center.equalTo(tableView)
            make.leading.trailing.equalTo(tableView).inset(AppSpacing.lg)
        }
    }

    private func applyViewModel() {
        if viewModel.isLoadingOrderSourcePeople {
            loadingIndicator.startAnimating()
            tableView.isHidden = true
            emptyLabel.isHidden = true
        } else {
            loadingIndicator.stopAnimating()
            tableView.isHidden = false
            let isEmpty = viewModel.orderSourcePeople.isEmpty
            emptyLabel.isHidden = !isEmpty
            tableView.reloadData()
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        viewModel.orderSourcePeople.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(
            withIdentifier: OrderSourcePersonCell.reuseIdentifier,
            for: indexPath
        ) as! OrderSourcePersonCell
        let person = viewModel.orderSourcePeople[indexPath.row]
        let currentSelection = viewModel.orderSourceSelection(
            orderNumber: orderNumber,
            referralOrder: referralOrder
        )
        cell.configure(
            person: person,
            selected: currentSelection?.person.key == person.key
        )
        cell.onCallPhone = onCallPhone
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let person = viewModel.orderSourcePeople[indexPath.row]
        let leadController = OrderSourceLeadListViewController(
            person: person,
            orderNumber: orderNumber,
            viewModel: viewModel,
            referralOrder: referralOrder,
            loadLeads: loadLeads,
            onLeadBound: onLeadBound,
            onCallPhone: onCallPhone
        )
        navigationController?.setNavigationBarHidden(false, animated: true)
        navigationController?.pushViewController(leadController, animated: true)
    }
}
