import SwiftUI

struct RecentReleasesDetailView: View {
    let movies: [VODItem]
    @EnvironmentObject var appState: AppState
    @State private var selectedVODItem: VODItem? = nil
    @FocusState private var focusedItem: String?

    // Cached data to avoid expensive recomputation
    @State private var cachedMovieGroupLookup: [String: MovieGroup] = [:]
    @State private var lastPlaylistUpdate: Date?

    let columns = Array(repeating: GridItem(.flexible(), spacing: Constants.UI.vodGridSpacing), count: Constants.UI.vodGridColumns)

    /// All movies in playlist for finding versions
    private var allPlaylistMovies: [VODItem] {
        appState.playlist?.vodItems.filter { $0.isMovie } ?? []
    }

    /// Get all versions for a movie (uses cache)
    private func allVersions(for item: VODItem) -> [VODItem] {
        cachedMovieGroupLookup[item.id]?.versions ?? [item]
    }

    /// Rebuild cache when playlist changes
    private func rebuildCacheIfNeeded() {
        guard let playlist = appState.playlist else { return }
        guard lastPlaylistUpdate != playlist.lastUpdated else { return }

        let movies = playlist.vodItems.filter { $0.isMovie }
        let groups = movies.groupedByTitle()

        var lookup: [String: MovieGroup] = [:]
        for group in groups {
            for version in group.versions {
                lookup[version.id] = group
            }
        }
        cachedMovieGroupLookup = lookup
        lastPlaylistUpdate = playlist.lastUpdated
    }

    var body: some View {
        ZStack {
            Color.black.ignoresSafeArea()

            ScrollView {
                VStack(spacing: 40) {
                    headerView

                    if movies.isEmpty {
                        emptyStateView
                    } else {
                        LazyVGrid(columns: columns, spacing: Constants.UI.vodGridSpacing) {
                            ForEach(movies) { item in
                                Button {
                                    selectedVODItem = item
                                } label: {
                                    VODCardView(
                                        vodItem: item,
                                        isFocused: focusedItem == item.id,
                                        releaseDate: appState.tmdbReleaseDates[item.id]
                                    )
                                }
                                .buttonStyle(.plain)
                                .focused($focusedItem, equals: item.id)
                            }
                        }
                        .padding(.horizontal, 80)
                        .padding(.bottom, 60)
                    }
                }
            }
        }
        .navigationDestination(item: $selectedVODItem) { item in
            VODDetailView(vodItem: item, allVersions: allVersions(for: item))
                .environmentObject(appState)
        }
        .onAppear {
            rebuildCacheIfNeeded()
        }
    }

    private var headerView: some View {
        VStack(spacing: 25) {
            HStack {
                Text("Recently Released")
                    .font(.system(size: 60, weight: .bold))
                    .foregroundColor(.white)

                Spacer()

                Text("\(movies.count) movies")
                    .font(.title3)
                    .foregroundColor(.gray)
            }
            .padding(.horizontal, 80)
            .padding(.top, 60)
        }
    }

    private var emptyStateView: some View {
        VStack(spacing: 30) {
            Image(systemName: "film")
                .font(.system(size: 100))
                .foregroundColor(.gray)

            Text("No Recent Releases Found")
                .font(.title)
                .foregroundColor(.white)

            Text("No movies in your library match recent theatrical releases")
                .font(.title3)
                .foregroundColor(.gray)
                .multilineTextAlignment(.center)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .padding(.top, 100)
    }
}
