import SwiftUI

struct RouteDetailView: View {
    let departure: Airport
    let arrival: Airport
    let date: Date
    let service: FlightService
    let loadService: AirlineLoadService
    let favoritesManager: FavoritesManager

    @State private var viewModel: RouteDetailViewModel
    @State private var selectedFlight: FlightSchedule?

    init(departure: Airport, arrival: Airport, date: Date, service: FlightService, loadService: AirlineLoadService, favoritesManager: FavoritesManager) {
        self.departure = departure
        self.arrival = arrival
        self.date = date
        self.service = service
        self.loadService = loadService
        self.favoritesManager = favoritesManager
        self._viewModel = State(initialValue: RouteDetailViewModel(service: service, date: date))
    }

    var body: some View {
        ZStack {
            FlightTheme.background
                .ignoresSafeArea()

            Group {
                if viewModel.isLoading {
                    loadingView
                } else if let error = viewModel.error {
                    errorView(error)
                } else if viewModel.flightsForDate.isEmpty {
                    emptyView
                } else {
                    scheduleList
                }
            }
        }
        .navigationTitle("\(departure.iata) \u{2192} \(arrival.iata)")
        .toolbar {
            ToolbarItem(placement: .topBarTrailing) {
                Button {
                    favoritesManager.toggle(departure: departure, arrival: arrival)
                } label: {
                    Image(systemName: favoritesManager.isFavorite(departure: departure, arrival: arrival) ? "heart.fill" : "heart")
                        .foregroundStyle(favoritesManager.isFavorite(departure: departure, arrival: arrival) ? .red : FlightTheme.textSecondary)
                }
            }
            ToolbarItem(placement: .topBarTrailing) {
                DatePicker(
                    "Date",
                    selection: $viewModel.selectedDate,
                    displayedComponents: .date
                )
                .labelsHidden()
                .datePickerStyle(.compact)
                .tint(FlightTheme.accent)
            }
        }
        .task {
            let depId = await resolveId(for: departure)
            let desId = await resolveId(for: arrival)
            await viewModel.loadSchedules(dep: depId, des: desId)
        }
        .sheet(item: $selectedFlight) { flight in
            FlightLoadDetailView(
                schedule: flight,
                departureCode: departure.iata,
                arrivalCode: arrival.iata,
                date: viewModel.selectedDate,
                loadService: loadService
            )
        }
    }

    // MARK: - Loading

    private var loadingView: some View {
        VStack(spacing: 12) {
            ProgressView()
                .tint(FlightTheme.accent)

            if let progress = viewModel.loadingProgress {
                Text("Loading airline \(progress.completed)/\(progress.total)...")
                    .font(.caption)
                    .foregroundStyle(FlightTheme.textSecondary)
            }
        }
    }

    // MARK: - Error

    private func errorView(_ message: String) -> some View {
        ContentUnavailableView {
            Label("Error", systemImage: "exclamationmark.triangle")
        } description: {
            Text(message)
        } actions: {
            Button("Retry") {
                Task {
                    let depId = await resolveId(for: departure)
                    let desId = await resolveId(for: arrival)
                    await viewModel.loadSchedules(dep: depId, des: desId)
                }
            }
            .buttonStyle(.borderedProminent)
            .tint(FlightTheme.accent)
        }
    }

    // MARK: - Empty

    private var emptyView: some View {
        ContentUnavailableView {
            Label("No Flights", systemImage: "airplane")
        } description: {
            Text("No flights operate on this date.")
        }
    }

    // MARK: - Schedule List

    private var scheduleList: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: FlightTheme.sectionSpacing) {
                ForEach(viewModel.airlineGroups, id: \.airline.id) { group in
                    VStack(alignment: .leading, spacing: 12) {
                        // Section header: small logo + airline name
                        HStack(spacing: 8) {
                            AsyncImage(url: group.airline.logoURL) { phase in
                                switch phase {
                                case .success(let image):
                                    image
                                        .resizable()
                                        .scaledToFit()
                                default:
                                    RoundedRectangle(cornerRadius: 6)
                                        .fill(FlightTheme.accent)
                                        .overlay {
                                            Text(String(group.airline.name.prefix(1)))
                                                .font(.system(size: 12, weight: .bold, design: .rounded))
                                                .foregroundStyle(.white)
                                        }
                                }
                            }
                            .frame(width: 24, height: 24)
                            .clipShape(RoundedRectangle(cornerRadius: 6))

                            Text(group.airline.name)
                                .font(.headline)
                                .foregroundStyle(FlightTheme.textPrimary)
                        }
                        .padding(.top, 4)

                        // Flight cards
                        ForEach(group.flights) { schedule in
                            Button {
                                selectedFlight = schedule
                            } label: {
                                FlightScheduleRow(
                                    schedule: schedule,
                                    departureCode: departure.iata,
                                    arrivalCode: arrival.iata
                                )
                            }
                            .buttonStyle(.plain)
                        }
                    }
                }
            }
            .padding(.horizontal, 16)
            .padding(.vertical, 12)
        }
    }

    // MARK: - ID Resolution

    /// If an airport was selected from browse/map with no FlightConnections ID, look it up.
    private func resolveId(for airport: Airport) async -> String {
        guard airport.id.isEmpty else { return airport.id }
        do {
            let results = try await service.searchAirports(term: airport.iata)
            if let match = results.first(where: { $0.iata == airport.iata }) {
                return match.id
            }
        } catch {}
        return airport.id
    }
}
