//
//  LibraryPickerHostViewController.swift
//  DashSmash
//
//  Hosts an MPMediaPickerController so the player can pick a song from the
//  device's Apple Music library (anything added/downloaded via the Apple
//  Music app). Works without the MusicKit capability — see MUSICKIT_SETUP.md
//  for enabling the full catalog flow.
//

import UIKit
import MediaPlayer

final class LibraryPickerHostViewController: UIViewController, MPMediaPickerControllerDelegate {

    private let statusLabel = UILabel()
    private let backButton = UIButton(type: .system)
    private let titleLabel = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .black
        setupUI()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        requestAuthorizationAndPresentPicker()
    }

    override var prefersStatusBarHidden: Bool { true }

    private func setupUI() {
        titleLabel.text = "YOUR LIBRARY"
        titleLabel.textColor = .white
        titleLabel.font = UIFont(name: "AvenirNext-Heavy", size: 22) ?? .boldSystemFont(ofSize: 22)
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(titleLabel)

        backButton.setTitle("← Back", for: .normal)
        backButton.titleLabel?.font = UIFont(name: "AvenirNext-Medium", size: 17) ?? .systemFont(ofSize: 17)
        backButton.setTitleColor(.white, for: .normal)
        backButton.addTarget(self, action: #selector(backTapped), for: .touchUpInside)
        backButton.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(backButton)

        statusLabel.numberOfLines = 0
        statusLabel.textColor = UIColor.white.withAlphaComponent(0.6)
        statusLabel.font = UIFont(name: "AvenirNext-Medium", size: 16) ?? .systemFont(ofSize: 16)
        statusLabel.textAlignment = .center
        statusLabel.translatesAutoresizingMaskIntoConstraints = false
        statusLabel.text = "Loading your library…"
        view.addSubview(statusLabel)

        NSLayoutConstraint.activate([
            backButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
            backButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 12),

            titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            titleLabel.centerYAnchor.constraint(equalTo: backButton.centerYAnchor),

            statusLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            statusLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            statusLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 32),
            statusLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -32)
        ])
    }

    private var pickerPresented = false

    private func requestAuthorizationAndPresentPicker() {
        guard !pickerPresented else { return }
        MPMediaLibrary.requestAuthorization { [weak self] status in
            DispatchQueue.main.async {
                guard let self else { return }
                switch status {
                case .authorized:
                    self.statusLabel.text = nil
                    self.presentPicker()
                case .denied:
                    self.statusLabel.text = "Library access denied.\nEnable it in Settings → Privacy & Security → Media & Apple Music."
                case .restricted:
                    self.statusLabel.text = "Library access is restricted on this device."
                case .notDetermined:
                    self.statusLabel.text = "Library access was not granted."
                @unknown default:
                    self.statusLabel.text = "Library access is unavailable."
                }
            }
        }
    }

    private func presentPicker() {
        let picker = MPMediaPickerController(mediaTypes: .music)
        picker.allowsPickingMultipleItems = false
        picker.showsCloudItems = true
        picker.prompt = "Pick a song"
        picker.delegate = self
        pickerPresented = true
        present(picker, animated: true)
    }

    @objc private func backTapped() {
        navigationController?.popViewController(animated: true)
    }

    // MARK: - MPMediaPickerControllerDelegate

    func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {
        mediaPicker.dismiss(animated: true) { [weak self] in
            guard let self else { return }
            guard let item = mediaItemCollection.items.first else {
                self.statusLabel.text = "No song selected."
                self.navigationController?.popViewController(animated: true)
                return
            }
            let track = PlayableTrack.library(item)
            self.statusLabel.text = "Detecting tempo…"
            Task { [weak self] in
                guard let self else { return }
                let detection = await BPMDetector.shared.detect(for: track)
                if let detection {
                    self.startGameDirectly(track: track, bpm: detection.bpm)
                } else {
                    // No automatic detection — fall back to tap-tempo. The
                    // preview seeks 30% into the song so the player taps over
                    // a stable groove rather than a sparse intro.
                    let tap = TapTempoViewController(track: track, previewStartFraction: 0.3)
                    self.navigationController?.pushViewController(tap, animated: true)
                }
            }
        }
    }

    private func startGameDirectly(track: PlayableTrack, bpm: Double) {
        // Build the same level we'd get out of the tap-tempo flow, then
        // restart playback from beat 0 and push the game scene.
        let level = LevelGenerator.generate(
            songName: track.title,
            bandName: track.artistName,
            fixedBPM: bpm,
            fixedDurationSeconds: track.duration,
            trackSourceID: track.sourceID
        )
        Task { [weak self] in
            guard let self else { return }
            switch track {
            case .library(let item):
                let player = MPMusicPlayerController.applicationMusicPlayer
                player.setQueue(with: MPMediaItemCollection(items: [item]))
                try? await player.prepareToPlay()
                player.skipToBeginning()
                player.play()
            case .appleMusicCatalog, .midi:
                break
            }
            let game = GameViewController(level: level, track: track)
            self.navigationController?.pushViewController(game, animated: true)
        }
    }

    func mediaPickerDidCancel(_ mediaPicker: MPMediaPickerController) {
        mediaPicker.dismiss(animated: true) { [weak self] in
            self?.navigationController?.popViewController(animated: true)
        }
    }
}
