import UIKit
import VMSDK_Core

/// Bottom-sheet picker that lists every floor across every building in the
/// loaded venue. Each section is a building; each row is "[ordinal] name".
/// Tapping a row invokes `onSelect` and dismisses.
final class FloorListController: UITableViewController {

    struct Group {
        let buildingId: String
        let buildingName: String
        let floors: [VMMSBaseFloor]
    }

    private let groups: [Group]
    private let currentFloor: VMMSBaseFloor?
    private let onSelect: (VMMSBaseFloor) -> Void

    init(groups: [Group], current: VMMSBaseFloor?, onSelect: @escaping (VMMSBaseFloor) -> Void) {
        self.groups = groups
        self.currentFloor = current
        self.onSelect = onSelect
        super.init(style: .insetGrouped)
    }

    @available(*, unavailable) required init?(coder: NSCoder) { fatalError() }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Floors"
        navigationItem.leftBarButtonItem = UIBarButtonItem(
            barButtonSystemItem: .cancel, target: self, action: #selector(dismissPicker))
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

    @objc private func dismissPicker() {
        dismiss(animated: true)
    }

    // MARK: - Data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        groups.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        groups[section].floors.count
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        let group = groups[section]
        return group.buildingName.isEmpty ? group.buildingId : group.buildingName
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let floor = groups[indexPath.section].floors[indexPath.row]
        let name = floor.name.isEmpty ? floor.uid : floor.name
        cell.textLabel?.text = "[\(floor.ordinal)] \(name)"
        cell.accessoryType = (floor.uid == currentFloor?.uid) ? .checkmark : .none
        return cell
    }

    // MARK: - Delegate

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let floor = groups[indexPath.section].floors[indexPath.row]
        onSelect(floor)
    }
}
