import Foundation
import AVFoundation
import SwiftUI

class AudioPlayerCoordinator: NSObject, AVAudioPlayerDelegate {
    var parent: ContentView
    
    init(_ parent: ContentView) {
        self.parent = parent
        super.init()
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(handleInterruption),
            name: AVAudioSession.interruptionNotification,
            object: nil
        )
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(handleRouteChange),
            name: AVAudioSession.routeChangeNotification,
            object: nil
        )
    }
    
    @objc func handleInterruption(_ notification: Notification) {
        guard let userInfo = notification.userInfo,
              let typeValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
              let type = AVAudioSession.InterruptionType(rawValue: typeValue) else {
            return
        }
        
        switch type {
        case .began:
            DispatchQueue.main.async {
                self.parent.isPlaying = false
                self.parent.updateNowPlaying()
            }
            
        case .ended:
            guard let optionsValue = userInfo[AVAudioSessionInterruptionOptionKey] as? UInt else { return }
            let options = AVAudioSession.InterruptionOptions(rawValue: optionsValue)
            
            if options.contains(.shouldResume) {
                DispatchQueue.main.async {
                    self.parent.audioPlayer?.play()
                    self.parent.isPlaying = true
                    self.parent.startTimer()
                    self.parent.updateNowPlaying()
                }
            }
            
        @unknown default:
            break
        }
    }
    
    @objc func handleRouteChange(_ notification: Notification) {
        guard let userInfo = notification.userInfo,
              let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
              let reason = AVAudioSession.RouteChangeReason(rawValue: reasonValue) else {
            return
        }
        
        switch reason {
        case .oldDeviceUnavailable:
            DispatchQueue.main.async {
                if self.parent.isPlaying {
                    self.parent.audioPlayer?.pause()
                    self.parent.isPlaying = false
                    self.parent.updateNowPlaying()
                }
            }
            
        case .newDeviceAvailable:
            print("Новое устройство подключено")
            self.parent.checkAudioRoute()
            
        default:
            break
        }
    }
    
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        print("🎵 ==================================")
        print("🎵 Трек ЗАВЕРШИЛСЯ успешно: \(flag)")
        print("🎵 Длительность трека: \(player.duration) секунд")
        print("🎵 Текущий индекс: \(parent.currentTrackIndex)")
        print("🎵 Всего треков: \(parent.tracks.count)")
        print("🎵 ==================================")
        
        DispatchQueue.main.async {
            self.parent.isPlaying = false
            self.parent.currentTime = 0
            self.parent.timer?.invalidate()
            self.parent.timer = nil
            self.parent.updateNowPlaying()
            
            // Проверяем, есть ли следующий трек
            if self.parent.tracks.count > 0 {
                let nextIndex = (self.parent.currentTrackIndex + 1) % self.parent.tracks.count
                print("🎵 Следующий индекс будет: \(nextIndex)")
                self.parent.playNextTrack()
            } else {
                print("🎵 Плейлист пуст, останавливаем воспроизведение")
            }
        }
    }
    
    func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
        print("🎵 ==================================")
        print("🎵 ОШИБКА декодирования: \(error?.localizedDescription ?? "неизвестна")")
        print("🎵 ==================================")
        
        DispatchQueue.main.async {
            self.parent.songTitle = "Ошибка декодирования файла"
            
            // Пробуем переключить на следующий трек при ошибке
            if self.parent.tracks.count > 0 {
                self.parent.playNextTrack()
            }
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
