//
//  HorizontalPlayerPager.swift
//  vibes
//
//  Created by Claude Code on 1/6/25.
//

import SwiftUI

struct HorizontalPlayerPager: View {
    let mainItem: HooksTabView.FeedItem
    let remixes: [HooksTabView.FeedItem]
    @Binding var currentHorizontalPage: Int
    let verticalIndex: Int
    let getGlobalPlaylistIndex: (Int, Int) -> Int
    let bottomSafeArea: CGFloat

    @Environment(AudioManager.self) private var audioManager
    @EnvironmentObject private var appState: AppState
    @EnvironmentObject private var tabBarState: TabBarState

    var body: some View {
        GeometryReader { geometry in
            ZStack {
                TabView(selection: $currentHorizontalPage) {
                    // Main song/video (page 0)
                    ZStack {
                        switch mainItem {
                        case .video(let title, let videoUrl):
                            VideoPlayerView(
                                trackTitle: title,
                                videoUrl: videoUrl
                            )
                        case .song(let title, let artwork):
                            SongPlayerView(
                                song: UploadedSong(id: "123", name: title, artistName: "Unknown", artistId: "123", createdAt: .now),
                                bottomSafeArea: bottomSafeArea
                            )
                        case .uploadedSong(let song):
                            SongPlayerView(
                                song: song,
                                bottomSafeArea: bottomSafeArea
                            )
                            .id(song.id)
                        }
                    }
                    .tag(0)

                    // Remix songs (pages 1+)
                    ForEach(Array(remixes.enumerated()), id: \.element.id) { index, remix in
                        switch remix {
                        case .video(let title, let videoUrl):
                            VideoPlayerView(
                                trackTitle: title,
                                videoUrl: videoUrl
                            )
                            .tag(index + 1)
                        case .song(let title, let artwork):
                            SongPlayerView(
                                song: UploadedSong(id: "123", name: title, artistName: "Unknown", artistId: "123", createdAt: .now),
                                bottomSafeArea: bottomSafeArea
                            )
                            .tag(index + 1)
                        case .uploadedSong(let song):
                            SongPlayerView(
                                song: song,
                                bottomSafeArea: bottomSafeArea
                            )
                            .tag(index + 1)
                            .id(song.id)
                        }
                    }
                }
                .tabViewStyle(.page(indexDisplayMode: .never))
                .frame(width: geometry.size.width, height: geometry.size.height)
                .onChange(of: currentHorizontalPage) { oldPage, newPage in
                    // Only control AudioManager when we're in hooks playback context
                    guard audioManager.playbackContext == .hooks else { return }

                    // Convert local horizontal page to global playlist index
                    let globalIndex = getGlobalPlaylistIndex(verticalIndex, newPage)

                    // When user swipes horizontally, switch to the corresponding song in the global playlist
                    if globalIndex >= 0 && globalIndex < audioManager.currentPlaylist.count {
                        // Only switch if we're not already playing this song
                        if audioManager.currentPlaylistIndex != globalIndex {
                            audioManager.playFromPlaylist(at: globalIndex)
                            print("🎵 Switched to global playlist index \(globalIndex) (vertical: \(verticalIndex), horizontal: \(newPage))")
                        }
                    }
                }
                .onChange(of: audioManager.currentPlaylistIndex) { oldIndex, newIndex in
                    // Only sync page when hooks playback is active
                    guard audioManager.playbackContext == .hooks else { return }

                    // Quick check: if the new index is far from this vertical item's range, skip processing
                    let firstIndex = getGlobalPlaylistIndex(verticalIndex, 0)
                    let totalPages = 1 + remixes.count
                    let lastIndex = getGlobalPlaylistIndex(verticalIndex, totalPages - 1)

                    // If the new index is outside our range, this change doesn't concern us
                    guard newIndex >= firstIndex && newIndex <= lastIndex else { return }

                    // Determine which horizontal page corresponds to this playlist index
                    for page in 0..<totalPages {
                        if getGlobalPlaylistIndex(verticalIndex, page) == newIndex {
                            // This playlist index belongs to our vertical item
                            if currentHorizontalPage != page {
                                currentHorizontalPage = page
                                print("🎵 Synced horizontal page to \(page) for global index \(newIndex)")
                            }
                            return
                        }
                    }
                }

                VStack {
                    Spacer()

                    let totalPages = 1 + remixes.count
                    if totalPages > 1 {
                        PaginationDots(totalDots: totalPages, currentIndex: currentHorizontalPage)
                            // Keep dots above the home indicator by accounting for bottom safe area.
                            .padding(.bottom, 8 + bottomSafeArea)
                            .animation(.easeInOut(duration: 0.2), value: bottomSafeArea)
                    }
                }
            }
            .frame(width: geometry.size.width, height: geometry.size.height)
        }
    }

}

#Preview {
    struct PreviewWrapper: View {
        var body: some View {
            HorizontalPlayerPager(
                mainItem: .song(title: "Main Song", artwork: "Artwork/2"),
                remixes: [
                    .song(title: "Remix 1", artwork: "Artwork/3"),
                    .song(title: "Remix 2", artwork: "Artwork/4"),
                    .song(title: "Remix 3", artwork: "Artwork/6")
                ],
                currentHorizontalPage: .constant(0),
                verticalIndex: 0,
                getGlobalPlaylistIndex: { vertical, horizontal in
                    return horizontal  // Simple passthrough for preview
                },
                bottomSafeArea: 0
            )
        }
    }

    return PreviewWrapper()
}
