import SwiftUI

struct TVShowDetailView: View {
    let tvShow: TVShow
    @EnvironmentObject var appState: AppState
    @State private var selectedSeason: Season? = nil
    @State private var selectedEpisode: VODItem? = nil
    @FocusState private var focusedSeason: String?

    let columns = Array(repeating: GridItem(.flexible(), spacing: 40), count: 3)

    /// Seasons sorted from most recent to least recent
    private var sortedSeasons: [Season] {
        tvShow.seasons.sorted { $0.number > $1.number }
    }

    /// The most recent episode (last episode of the latest season)
    private var latestEpisode: VODItem? {
        guard let latestSeason = tvShow.seasons.max(by: { $0.number < $1.number }) else {
            return nil
        }
        return latestSeason.episodes.last
    }

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

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

                        seasonsGrid
                    }
                    .padding(.horizontal, 80)
                    .padding(.top, 60)
                    .padding(.bottom, 60)
                }
                .navigationDestination(item: $selectedSeason) { season in
                    SeasonDetailView(tvShow: tvShow, season: season)
                        .environmentObject(appState)
                }
                .navigationDestination(item: $selectedEpisode) { episode in
                    VODDetailView(vodItem: episode)
                        .environmentObject(appState)
                }
            }
            .navigationTitle("")
            .toolbar(.hidden, for: .navigationBar)
        }
    }

    private var headerView: some View {
        HStack(alignment: .top, spacing: 40) {
            if let iconURL = tvShow.iconURL, let url = URL(string: iconURL) {
                AsyncImage(url: url) { phase in
                    switch phase {
                    case .empty:
                        ZStack {
                            Color.gray.opacity(0.3)
                            ProgressView()
                        }
                    case .success(let image):
                        image
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                    case .failure:
                        ZStack {
                            Color.gray.opacity(0.3)
                            Image(systemName: "tv")
                                .font(.system(size: 80))
                                .foregroundColor(.white.opacity(0.5))
                        }
                    @unknown default:
                        EmptyView()
                    }
                }
                .frame(width: 400, height: 600)
                .cornerRadius(20)
                .clipped()
            }

            VStack(alignment: .leading, spacing: 20) {
                Text(tvShow.name)
                    .font(.system(size: 60, weight: .bold))
                    .foregroundColor(.white)

                Text("\(tvShow.seasons.count) season\(tvShow.seasons.count == 1 ? "" : "s")")
                    .font(.title2)
                    .foregroundColor(.gray)

                if let latest = latestEpisode {
                    Button {
                        selectedEpisode = latest
                    } label: {
                        HStack(spacing: 15) {
                            Image(systemName: "play.fill")
                                .font(.title2)
                            Text("Play Latest Episode")
                                .font(.title2)
                                .fontWeight(.semibold)
                        }
                        .foregroundColor(.white)
                        .padding(.horizontal, 40)
                        .padding(.vertical, 20)
                        .background(Color.blue)
                        .cornerRadius(15)
                    }
                    .buttonStyle(.plain)
                    .padding(.top, 20)

                    if let latestSeason = tvShow.seasons.max(by: { $0.number < $1.number }) {
                        Text("S\(latestSeason.number) E\(latestSeason.episodes.count)")
                            .font(.callout)
                            .foregroundColor(.gray)
                    }
                }

                Text("Select a season to view episodes")
                    .font(.title3)
                    .foregroundColor(.white.opacity(0.7))
                    .padding(.top, 10)
            }

            Spacer()
        }
    }

    private var seasonsGrid: some View {
        VStack(alignment: .leading, spacing: 30) {
            Text("Seasons")
                .font(.system(size: 40, weight: .semibold))
                .foregroundColor(.white)

            LazyVGrid(columns: columns, spacing: 40) {
                ForEach(sortedSeasons) { season in
                    Button {
                        selectedSeason = season
                    } label: {
                        SeasonCardView(
                            season: season,
                            isFocused: focusedSeason == season.id
                        )
                    }
                    .buttonStyle(.plain)
                    .focused($focusedSeason, equals: season.id)
                }
            }
        }
    }
}

struct SeasonCardView: View {
    let season: Season
    let isFocused: Bool

    var body: some View {
        VStack(spacing: 15) {
            ZStack {
                RoundedRectangle(cornerRadius: 20)
                    .fill(isFocused ? Color.blue : Color.white.opacity(0.1))

                VStack(spacing: 10) {
                    Text("Season \(season.number)")
                        .font(.system(size: 35, weight: .semibold))
                        .foregroundColor(.white)

                    Text("\(season.episodes.count) episode\(season.episodes.count == 1 ? "" : "s")")
                        .font(.title3)
                        .foregroundColor(.gray)
                }
            }
            .frame(height: 200)
        }
        .scaleEffect(isFocused ? 1.05 : 1.0)
        .shadow(color: isFocused ? .white.opacity(0.3) : .clear, radius: 10)
        .animation(.easeInOut(duration: 0.2), value: isFocused)
    }
}
