import SwiftUI
import CoreBluetooth

struct ScannerView: View {
    @EnvironmentObject var ble: BluetoothManager
    @State private var showTerminal = false

    var body: some View {
        NavigationView {
            Group {
                if ble.bluetoothState != .poweredOn {
                    bluetoothOffView
                } else {
                    deviceList
                }
            }
            .navigationTitle("BLE Terminal")
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    scanButton
                }
            }
            .background(
                NavigationLink(isActive: $showTerminal) {
                    TerminalView()
                        .environmentObject(ble)
                } label: { EmptyView() }
            )
            .onChange(of: ble.connectedPeripheral) { peripheral in
                showTerminal = peripheral != nil
            }
        }
        .navigationViewStyle(.stack)
    }

    // MARK: Sub-views

    private var bluetoothOffView: some View {
        VStack(spacing: 16) {
            Image(systemName: "bluetooth.slash")
                .font(.system(size: 56))
                .foregroundColor(.secondary)
            Text(stateMessage)
                .foregroundColor(.secondary)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
    }

    private var stateMessage: String {
        switch ble.bluetoothState {
        case .poweredOff:    return "Bluetooth is off"
        case .unauthorized:  return "Bluetooth permission denied"
        case .unsupported:   return "BLE not supported"
        default:             return "Waiting for Bluetooth…"
        }
    }

    private var deviceList: some View {
        List {
            if ble.discoveredPeripherals.isEmpty && !ble.isScanning {
                Text("Tap scan to discover devices")
                    .foregroundColor(.secondary)
                    .listRowBackground(Color.clear)
            }
            ForEach(ble.discoveredPeripherals) { info in
                DeviceRow(info: info)
                    .contentShape(Rectangle())
                    .onTapGesture { ble.connect(info) }
            }
        }
        .listStyle(.insetGrouped)
        .overlay {
            if ble.isScanning && ble.discoveredPeripherals.isEmpty {
                VStack(spacing: 12) {
                    ProgressView()
                    Text("Scanning…").foregroundColor(.secondary)
                }
            }
        }
    }

    private var scanButton: some View {
        Button {
            ble.isScanning ? ble.stopScanning() : ble.startScanning()
        } label: {
            Label(ble.isScanning ? "Stop" : "Scan",
                  systemImage: ble.isScanning ? "stop.fill" : "arrow.clockwise")
        }
        .accentColor(ble.isScanning ? .red : .accentColor)
    }
}

// MARK: - Device Row

struct DeviceRow: View {
    let info: PeripheralInfo

    var body: some View {
        HStack(spacing: 12) {
            Image(systemName: info.signalStrength.icon)
                .foregroundColor(info.signalStrength.color)
                .frame(width: 28)

            VStack(alignment: .leading, spacing: 2) {
                Text(info.name)
                    .font(.headline)
                Text(info.peripheral.identifier.uuidString)
                    .font(.caption2)
                    .foregroundColor(.secondary)
                    .lineLimit(1)
            }

            Spacer()

            VStack(alignment: .trailing, spacing: 2) {
                Text(info.rssiText)
                    .font(.caption)
                    .foregroundColor(.secondary)
                if info.isConnected {
                    Text("Connected")
                        .font(.caption2)
                        .foregroundColor(.green)
                }
            }
        }
        .padding(.vertical, 4)
    }
}
