import SwiftUI

struct RecentlyAiredDetailView: 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)

    /// Format subtitle showing current season and air date
    private func subtitle(for show: TVShow) -> String {
        var parts: [String] = []

        // Current season (highest season number)
        if let latestSeason = show.seasons.last {
            parts.append("Season \(latestSeason.number)")
        }

        // Format air date
        if let dateString = appState.tvShowAirDates[show.name] {
            let formatted = Self.formatAirDate(dateString)
            parts.append(formatted)
        }

        return parts.joined(separator: " • ")
    }

    /// Convert "YYYY-MM-DD" to "Jan 18, 2026" format
    private static func formatAirDate(_ dateString: String) -> String {
        let inputFormatter = DateFormatter()
        inputFormatter.dateFormat = "yyyy-MM-dd"

        let outputFormatter = DateFormatter()
        outputFormatter.dateFormat = "MMM d, yyyy"

        if let date = inputFormatter.date(from: dateString) {
            return outputFormatter.string(from: date)
        }
        return dateString
    }

    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,
                                        customSubtitle: subtitle(for: show)
                                    )
                                }
                                .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("Shows with Recently Aired Episodes")
                    .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 Recently Aired Shows")
                .font(.title)
                .foregroundColor(.white)

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