import SwiftUI

struct SeasonDetailView: View {
    let tvShow: TVShow
    let season: Season
    @State private var selectedEpisode: VODItem? = nil
    @FocusState private var focusedEpisode: String?

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

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

            ScrollView {
                VStack(alignment: .leading, spacing: 40) {
                    headerView

                    episodesGrid
                }
                .padding(.horizontal, 80)
                .padding(.top, 60)
                .padding(.bottom, 60)
            }
            .navigationDestination(item: $selectedEpisode) { episode in
                VODDetailView(vodItem: episode)
            }
        }
        .navigationTitle("")
        .toolbar(.hidden, for: .navigationBar)
    }

    private var headerView: some View {
        VStack(alignment: .leading, spacing: 20) {
            Text(tvShow.name)
                .font(.system(size: 50, weight: .bold))
                .foregroundColor(.white)

            Text("Season \(season.number)")
                .font(.system(size: 40, weight: .semibold))
                .foregroundColor(.gray)

            Text("\(season.episodes.count) episode\(season.episodes.count == 1 ? "" : "s")")
                .font(.title2)
                .foregroundColor(.white.opacity(0.7))
        }
    }

    private var episodesGrid: some View {
        LazyVGrid(columns: columns, spacing: Constants.UI.vodGridSpacing) {
            ForEach(season.episodes) { episode in
                Button {
                    selectedEpisode = episode
                } label: {
                    VODCardView(
                        vodItem: episode,
                        isFocused: focusedEpisode == episode.id
                    )
                }
                .buttonStyle(.plain)
                .focused($focusedEpisode, equals: episode.id)
            }
        }
    }
}
