import SwiftUI
import VoiceCatCore

struct PerUserTuningView: View {
    let user: User
    @Bindable var session: SessionState
    @Environment(\.dismiss) private var dismiss

    @State private var gain: Float = 1.0
    @State private var muted = false
    @State private var noiseReduction = false

    private var streamsForUser: [StreamSummary] {
        session.client.listUserStreams(user.id)
    }

    var body: some View {
        NavigationStack {
            Form {
                Section("Volume") {
                    HStack {
                        Text("Gain")
                        Slider(value: $gain, in: 0...4, step: 0.05) { _ in
                            applyToAllStreams()
                        }
                        .accessibilityLabel("Volume gain for \(user.nickname)")
                        Text(String(format: "%.0f%%", gain * 100))
                            .monospacedDigit()
                            .frame(width: 44, alignment: .trailing)
                    }
                    Toggle("Mute", isOn: $muted)
                        .onChange(of: muted) { _, _ in applyToAllStreams() }
                        .accessibilityLabel("Mute \(user.nickname)")
                }

                Section("Audio Processing") {
                    Toggle("Noise Reduction", isOn: $noiseReduction)
                        .onChange(of: noiseReduction) { _, _ in applyToAllStreams() }
                        .accessibilityLabel("Noise reduction for \(user.nickname)")
                }
            }
            .navigationTitle(user.nickname)
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .confirmationAction) {
                    Button("Done") { dismiss() }
                }
            }
        }
        .onAppear {
            // Load from first stream if available
            let streams = streamsForUser
            if let first = streams.first {
                let (_, state) = session.client.getRemoteStream(userId: user.id, streamId: first.id)
                if let s = state {
                    gain = s.gain
                    muted = s.muted
                    noiseReduction = s.noiseReduction
                }
            }
        }
    }

    private func applyToAllStreams() {
        for stream in streamsForUser {
            session.client.setRemoteStream(
                userId: user.id, streamId: stream.id,
                gain: gain, muted: muted, noiseReduction: noiseReduction)
        }
    }
}
