//
//  SoundSelectionView.swift
//  TheNoiseClock
//
//  Created by Matt Bruce on 9/8/25.
//

import SwiftUI
import AudioPlaybackKit

/// View for selecting alarm sounds with preview functionality
struct SoundSelectionView: View {
    @Binding var selectedSound: String
    @Environment(\.dismiss) private var dismiss
    
    // Use shared player instance to avoid audio conflicts
    private let soundPlayer = SoundPlayer.shared
    private let alarmSounds = AlarmSoundService.shared.getAlarmSounds().sorted { $0.name < $1.name }
    
    @State private var isPlaying = false
    @State private var currentlyPlayingSound: String? = nil
    
    var body: some View {
        List {
            Section("Alarm Sounds") {
                ForEach(alarmSounds, id: \.id) { sound in
                    HStack {
                        Text(sound.name)
                            .font(.body)
                        Spacer()
                        if selectedSound == sound.fileName {
                            Image(systemName: "checkmark")
                                .foregroundColor(AppAccent.primary)
                        }
                    }
                    .contentShape(Rectangle())
                    .onTapGesture {
                        // Stop any currently playing sound when selecting a new one
                        if isPlaying {
                            stopSound()
                        }
                        selectedSound = sound.fileName
                    }
                }
            }
        }
        .navigationTitle("Sound")
        .navigationBarTitleDisplayMode(.inline)
        .toolbar {
            ToolbarItem(placement: .navigationBarTrailing) {
                Button(action: {
                    if isPlaying && currentlyPlayingSound == selectedSound {
                        stopSound()
                    } else {
                        playSelectedSound()
                    }
                }) {
                    Image(systemName: isPlaying && currentlyPlayingSound == selectedSound ? "stop.fill" : "play.fill")
                        .foregroundColor(AppAccent.primary)
                }
            }
        }
        .onDisappear {
            // Stop any playing sound when leaving the view
            stopSound()
        }
    }
    
    private func playSelectedSound() {
        guard let sound = alarmSounds.first(where: { $0.fileName == selectedSound }) else { return }
        
        // Stop any currently playing sound first
        stopSound()
        
        // Start playing the new sound
        soundPlayer.playSound(sound)
        isPlaying = true
        currentlyPlayingSound = selectedSound
    }
    
    private func stopSound() {
        soundPlayer.stopSound()
        isPlaying = false
        currentlyPlayingSound = nil
    }
}
