import SwiftUI

struct OLTListView: View {
    let connection: MCMSConnection
    @State private var vm: OLTListViewModel

    init(connection: MCMSConnection) {
        self.connection = connection
        _vm = State(initialValue: OLTListViewModel(connection: connection))
    }

    var body: some View {
        @Bindable var vm = vm
        Group {
            switch vm.phase {
            case .idle:
                LoadingView(label: "Loading OLTs…")
            case .loading where vm.olts.isEmpty:
                LoadingView(label: "Loading OLTs…")
            case .failed(let msg):
                ErrorStateView(message: msg) { Task { await vm.load() } }
            default:
                list
            }
        }
        .navigationTitle("OLTs")
        .searchable(text: $vm.search, prompt: "OLT name or MAC")
        .task { if vm.phase == .idle { await vm.load() } }
        .refreshable { await vm.load() }
    }

    private var list: some View {
        List(vm.filtered) { olt in
            NavigationLink {
                OLTDetailView(connection: connection, oltId: olt.id, title: olt.displayName)
            } label: {
                row(olt)
            }
        }
        .listStyle(.plain)
        .overlay {
            if vm.filtered.isEmpty {
                if vm.search.isEmpty {
                    ContentUnavailableView("No OLTs", systemImage: "antenna.radiowaves.left.and.right")
                } else {
                    ContentUnavailableView.search(text: vm.search)
                }
            }
        }
    }

    private func row(_ olt: OLTStateDoc) -> some View {
        HStack {
            VStack(alignment: .leading, spacing: 4) {
                Text(olt.displayName).font(.body.weight(.medium))
                Text(subtitle(olt)).font(.caption).foregroundStyle(.secondary)
            }
            Spacer()
            let down = olt.totalONUs - olt.onlineONUs
            if olt.totalONUs == 0 {
                StateBadge(text: "no ONUs", color: .secondary)
            } else if down > 0 {
                StateBadge(text: "\(down) down", color: .orange)
            } else {
                StateBadge(text: "all up", color: .green)
            }
        }
    }

    /// Secondary line: the MAC (only when a name is the title) and the ONU counts.
    private func subtitle(_ olt: OLTStateDoc) -> String {
        let prefix = olt.resolvedName != nil ? "\(olt.id) · " : ""
        return "\(prefix)\(olt.totalONUs) ONUs · \(olt.onlineONUs) online"
    }
}
