import SwiftUI

struct AllTVShowsGridView: View {
    let shows: [TVShow]
    @EnvironmentObject var appState: AppState
    @State private var selectedTVShow: TVShow? = nil
    @FocusState private var focusedItem: 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(spacing: 40) {
                    headerView

                    if shows.isEmpty {
                        emptyStateView
                    } else {
                        LazyVGrid(columns: columns, spacing: Constants.UI.vodGridSpacing) {
                            ForEach(shows) { show in
                                Button {
                                    selectedTVShow = show
                                } label: {
                                    TVShowCardView(
                                        tvShow: show,
                                        isFocused: focusedItem == show.id
                                    )
                                }
                                .buttonStyle(.plain)
                                .focused($focusedItem, equals: show.id)
                            }
                        }
                        .padding(.horizontal, 80)
                        .padding(.bottom, 60)
                    }
                }
            }
        }
        .navigationDestination(item: $selectedTVShow) { show in
            TVShowDetailView(tvShow: show)
                .environmentObject(appState)
        }
    }

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

                Spacer()

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

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

            Text("No TV Shows Available")
                .font(.title)
                .foregroundColor(.white)

            Text("Check back later for new content")
                .font(.title3)
                .foregroundColor(.gray)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .padding(.top, 100)
    }
}
