import SwiftUI

struct TVShowsLibraryView: View {
    @EnvironmentObject var appState: AppState
    @StateObject private var viewModel = VODLibraryViewModel()
    @State private var selectedTVShow: TVShow? = nil
    @State private var selectedEpisode: VODItem? = nil
    @State private var navigateToTrending: Bool = false
    @State private var navigateToRecentlyAired: Bool = false
    @State private var navigateToAllShows: Bool = false
    @FocusState private var focusedItem: String?

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

    private var isSearching: Bool {
        !viewModel.searchText.isEmpty
    }

    /// Filtered TV shows based on search text (uses AppState cached data)
    var tvShows: [TVShow] {
        if viewModel.searchText.isEmpty {
            return appState.cachedTVShows
        }
        return appState.cachedTVShows.filter { $0.name.localizedCaseInsensitiveContains(viewModel.searchText) }
    }

    var continueWatchingTVShows: [WatchHistoryEntry] {
        appState.watchHistory.filter { !$0.isMovie }
    }

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

                if appState.isLoading || appState.tvDataLoading {
                    LoadingView()
                } else if let error = appState.error {
                    ErrorView(error: error, onRetry: {
                        Task {
                            await appState.loadPlaylist(forceRefresh: true)
                        }
                    }, onDismiss: {
                        appState.clearError()
                    })
                } else if !appState.cachedTVShows.isEmpty {
                    ScrollView {
                        VStack(spacing: 40) {
                            headerView

                            if isSearching {
                                searchResultsGridView
                            } else {
                                browseView
                            }
                        }
                    }
                    .navigationDestination(item: $selectedTVShow) { show in
                        TVShowDetailView(tvShow: show)
                            .environmentObject(appState)
                    }
                    .navigationDestination(item: $selectedEpisode) { episode in
                        VODDetailView(vodItem: episode)
                            .environmentObject(appState)
                    }
                    .navigationDestination(isPresented: $navigateToTrending) {
                        TrendingTVShowsDetailView(shows: appState.trendingTVShows)
                            .environmentObject(appState)
                    }
                    .navigationDestination(isPresented: $navigateToRecentlyAired) {
                        RecentlyAiredDetailView(shows: appState.recentlyAiredShows)
                            .environmentObject(appState)
                    }
                    .navigationDestination(isPresented: $navigateToAllShows) {
                        AllTVShowsGridView(shows: appState.cachedTVShows)
                            .environmentObject(appState)
                    }
                } else {
                    emptyStateView
                }
            }
            .navigationTitle("")
            .toolbar(.hidden, for: .navigationBar)
            .onAppear {
                // Trigger TV data computation if not already done
                appState.computeTVShowCache()
            }
            .onChange(of: appState.playlist?.vodItems.count) { _, _ in
                appState.computeTVShowCache()
            }
        }
    }

    // MARK: - Browse View (Row-based layout)

    private var browseView: some View {
        VStack(spacing: 40) {
            // Row 1: Continue Watching
            if !continueWatchingTVShows.isEmpty {
                ContinueWatchingRow(entries: continueWatchingTVShows) { entry in
                    // Use O(1) lookup instead of linear search
                    if let episode = appState.episodeLookup[entry.id] {
                        selectedEpisode = episode
                    }
                }
            }

            // Row 2: Trending TV Shows
            if !appState.trendingTVShows.isEmpty {
                TrendingTVShowsRow(
                    shows: appState.trendingTVShows,
                    onSeeAll: { navigateToTrending = true },
                    onSelectShow: { selectedTVShow = $0 }
                )
            }

            // Row 3: Recently Aired Episodes
            if !appState.recentlyAiredShows.isEmpty {
                RecentlyAiredShowsRow(
                    shows: appState.recentlyAiredShows,
                    airDates: appState.tvShowAirDates,
                    onSeeAll: { navigateToRecentlyAired = true },
                    onSelectShow: { selectedTVShow = $0 }
                )
            }

            // Row 4: All Shows (first 10 + See All)
            AllTVShowsRow(
                shows: appState.cachedTVShows,
                onSeeAll: { navigateToAllShows = true },
                onSelectShow: { selectedTVShow = $0 }
            )
        }
        .padding(.bottom, 60)
    }

    // MARK: - Search Results Grid

    private var searchResultsGridView: some View {
        VStack(alignment: .leading, spacing: 20) {
            Text("Search Results")
                .font(.title2)
                .fontWeight(.bold)
                .foregroundColor(.white)
                .padding(.horizontal, 80)

            if tvShows.isEmpty {
                VStack(spacing: 20) {
                    Image(systemName: "magnifyingglass")
                        .font(.system(size: 60))
                        .foregroundColor(.gray)

                    Text("No shows found for \"\(viewModel.searchText)\"")
                        .font(.title3)
                        .foregroundColor(.gray)
                }
                .frame(maxWidth: .infinity)
                .padding(.top, 60)
            } else {
                LazyVGrid(columns: columns, spacing: Constants.UI.vodGridSpacing) {
                    ForEach(tvShows) { 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)
            }
        }
    }

    // MARK: - Header View

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

                Spacer()

                SearchBar(text: $viewModel.searchText, placeholder: "Search TV shows...")
                    .frame(width: 400)

                Button(action: {
                    Task {
                        await appState.loadPlaylist(forceRefresh: true)
                    }
                }) {
                    Image(systemName: "arrow.clockwise")
                        .font(.title3)
                        .foregroundColor(.white)
                        .padding()
                        .background(Color.white.opacity(0.1))
                        .cornerRadius(10)
                }

                if appState.isDevelopmentMode {
                    Button(action: {
                        Task {
                            await appState.clearWatchHistory()
                        }
                    }) {
                        Image(systemName: "trash")
                            .font(.title3)
                            .foregroundColor(.white)
                            .padding()
                            .background(Color.orange.opacity(0.3))
                            .cornerRadius(10)
                    }
                }

                Button(action: {
                    Task {
                        await appState.logout()
                    }
                }) {
                    HStack {
                        Image(systemName: "rectangle.portrait.and.arrow.right")
                        Text("Logout")
                    }
                    .font(.title3)
                    .foregroundColor(.white)
                    .padding()
                    .background(Color.red.opacity(0.3))
                    .cornerRadius(10)
                }
            }
            .padding(.horizontal, 80)
            .padding(.top, 60)

            if appState.playlist != nil {
                HStack {
                    Text("\(appState.cachedTVShows.count) shows")
                        .font(.title3)
                        .foregroundColor(.gray)

                    if appState.tvDataLoading {
                        ProgressView()
                            .scaleEffect(0.8)
                            .padding(.leading, 10)
                    }

                    Spacer()
                }
                .padding(.horizontal, 80)
            }
        }
    }

    // MARK: - Empty State View

    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("Pull down to refresh or check back later")
                .font(.title3)
                .foregroundColor(.gray)

            Button("Refresh") {
                Task {
                    await appState.loadPlaylist(forceRefresh: true)
                }
            }
            .buttonStyle(.plain)
            .padding()
            .background(Color.blue)
            .cornerRadius(10)
            .foregroundColor(.white)
        }
    }
}

#Preview {
    TVShowsLibraryView()
        .environmentObject(AppState(developmentMode: true))
}
