import SwiftUI

/// Drilldown showing every flight you've flown through one airport
/// (as departure OR arrival), plus a "Top destinations from here"
/// rollup. Available from the lifetime route map (tap an airport
/// dot).
struct AirportFlightsView: View {
    let iata: String
    let allFlights: [LoggedFlight]
    let database: AirportDatabase
    let store: FlightHistoryStore
    let openSky: OpenSkyClient
    @Binding var filters: HistoryFilters

    @Environment(\.dismiss) private var dismiss

    var body: some View {
        let through = allFlights
            .filter { $0.departureIATA == iata || $0.arrivalIATA == iata }
            .sorted { $0.flightDate > $1.flightDate }

        return List {
            Section {
                summary(for: through)
                    .listRowInsets(EdgeInsets())
                    .listRowBackground(Color.clear)
            }
            if !destinations(from: through).isEmpty {
                Section("Top destinations") {
                    ForEach(destinations(from: through), id: \.iata) { d in
                        HStack {
                            Text(d.iata)
                                .font(.subheadline.weight(.semibold).monospaced())
                            if let m = database.airport(byIATA: d.iata) {
                                Text(m.name)
                                    .font(.caption)
                                    .foregroundStyle(FlightTheme.textSecondary)
                                    .lineLimit(1)
                            }
                            Spacer()
                            Text("\(d.count)×")
                                .font(.subheadline.weight(.bold).monospacedDigit())
                                .foregroundStyle(FlightTheme.accent)
                        }
                    }
                }
            }
            Section("All flights") {
                ForEach(through) { flight in
                    NavigationLink {
                        HistoryDetailView(
                            flight: flight,
                            store: store,
                            database: database,
                            openSky: openSky
                        )
                    } label: {
                        HistoryRowView(flight: flight, database: database)
                    }
                }
            }
        }
        .navigationTitle(iata)
        .navigationBarTitleDisplayMode(.inline)
        .toolbar {
            ToolbarItem(placement: .primaryAction) {
                Button {
                    filters.airports = [iata]
                    dismiss()
                } label: {
                    Label("Filter list", systemImage: "line.3.horizontal.decrease.circle")
                }
            }
        }
    }

    private func summary(for through: [LoggedFlight]) -> some View {
        VStack(alignment: .leading, spacing: 8) {
            if let airport = database.airport(byIATA: iata) {
                Text(airport.name)
                    .font(.subheadline.weight(.semibold))
                    .foregroundStyle(FlightTheme.textPrimary)
                if !airport.country.isEmpty {
                    Text(airport.country)
                        .font(.caption)
                        .foregroundStyle(FlightTheme.textSecondary)
                }
            }
            HStack(spacing: 12) {
                tile(label: "Total", value: "\(through.count)")
                tile(label: "Departed", value: "\(through.filter { $0.departureIATA == iata }.count)")
                tile(label: "Arrived", value: "\(through.filter { $0.arrivalIATA == iata }.count)")
            }
            .padding(.top, 6)
        }
        .padding(16)
    }

    private func tile(label: String, value: String) -> some View {
        VStack(spacing: 2) {
            Text(value)
                .font(.title3.weight(.bold).monospacedDigit())
                .foregroundStyle(FlightTheme.textPrimary)
            Text(label.uppercased())
                .font(.caption2.weight(.semibold))
                .tracking(0.6)
                .foregroundStyle(FlightTheme.textTertiary)
        }
        .frame(maxWidth: .infinity)
        .padding(.vertical, 8)
        .background(FlightTheme.cardBackground, in: RoundedRectangle(cornerRadius: 10))
    }

    private struct DestCount {
        let iata: String
        let count: Int
    }

    /// "Where did I go FROM this airport?" — counts of the OTHER
    /// endpoint for each flight through here, with this airport
    /// itself filtered out.
    private func destinations(from through: [LoggedFlight]) -> [DestCount] {
        let others = through.map { f -> String in
            f.departureIATA == iata ? f.arrivalIATA : f.departureIATA
        }.filter { $0 != iata && !$0.isEmpty }
        return Dictionary(grouping: others) { $0 }
            .map { DestCount(iata: $0.key, count: $0.value.count) }
            .sorted { $0.count > $1.count }
            .prefix(10)
            .map { $0 }
    }
}
