import SwiftUI

struct ConnectionView: View {
    var state: AppState
    @State private var addressField: String = ""

    var body: some View {
        VStack(spacing: 0) {
            header
            Divider()
            connectionForm
            Spacer()
        }
        .navigationTitle("Connection")
        .onAppear { addressField = state.transport.address }
    }

    // MARK: - Header

    private var header: some View {
        HStack {
            Circle()
                .fill(statusColor)
                .frame(width: 10, height: 10)
            Text(state.transport.state.rawValue)
                .font(.headline)
            Spacer()
            if state.transport.state == .connected {
                Button("Disconnect") { state.transport.disconnect() }
                    .buttonStyle(.bordered)
                    .tint(.red)
            } else if state.transport.state == .connecting {
                ProgressView()
                    .controlSize(.small)
            } else {
                Button("Connect") { connectToDevice() }
                    .buttonStyle(.borderedProminent)
            }
        }
        .padding()
    }

    private var statusColor: Color {
        switch state.transport.state {
        case .connected: .green
        case .connecting: .yellow
        case .disconnected: .red
        }
    }

    // MARK: - Connection form

    private var connectionForm: some View {
        VStack(alignment: .leading, spacing: 16) {
            VStack(alignment: .leading, spacing: 4) {
                Text("Firmware Address")
                    .font(.subheadline.weight(.medium))
                    .foregroundStyle(.secondary)
                HStack {
                    TextField("192.168.4.1", text: $addressField)
                        .textFieldStyle(.roundedBorder)
                        .autocorrectionDisabled()
                        .textInputAutocapitalization(.never)
                        .keyboardType(.numbersAndPunctuation)
                    Text(":\(state.transport.port)")
                        .font(.subheadline.monospacedDigit())
                        .foregroundStyle(.secondary)
                }
            }

            Button("Connect") { connectToDevice() }
                .buttonStyle(.borderedProminent)
                .disabled(state.transport.state == .connecting)

            Text("Connect to the EIS4 WiFi network, then tap Connect.")
                .font(.caption)
                .foregroundStyle(Color(white: 0.4))
        }
        .padding()
    }

    private func connectToDevice() {
        let addr = addressField.trimmingCharacters(in: .whitespaces)
        if !addr.isEmpty {
            state.transport.address = addr
        }
        state.transport.connect()
    }
}
