import SwiftUI
import SwiftData

/// Top-level tab container.
///
/// Tab 1: the existing search / connection / where-to-go home screen.
/// Tab 2: the live flight tracker (map + filters + tap-to-detail).
/// Tab 3: personal flight history (logbook + stats + map).
///
/// Also subscribes to WalletPassObserver so that adding a boarding
/// pass to Apple Wallet pops the add-flight sheet over whatever tab
/// the user is on.
struct RootView: View {
    let database: AirportDatabase
    let loadService: AirlineLoadService
    let routeExplorer: RouteExplorerClient
    let openSky: OpenSkyClient
    let fr24: FR24Client

    @State private var selectedTab: Tab = .search
    @StateObject private var wallet = WalletPassObserver.shared
    @State private var walletPrefill: AddFlightView.Prefill?
    /// URL-scheme prefill (from the Share Extension or any external
    /// invocation of `flights://import?...`).
    @State private var urlPrefill: AddFlightView.Prefill?
    @Environment(\.modelContext) private var modelContext

    enum Tab: Hashable { case search, live, history }

    var body: some View {
        TabView(selection: $selectedTab) {
            RoutePlannerView(
                database: database,
                client: routeExplorer,
                loadService: loadService
            )
            .tabItem {
                Label("Search", systemImage: "magnifyingglass")
            }
            .tag(Tab.search)

            NavigationStack {
                LiveFlightsView(
                    openSky: openSky,
                    fr24: fr24,
                    routeExplorer: routeExplorer,
                    database: database
                )
                .navigationTitle("Live Flights")
                .navigationBarTitleDisplayMode(.inline)
            }
            .tabItem {
                Label("Live", systemImage: "antenna.radiowaves.left.and.right")
            }
            .tag(Tab.live)

            NavigationStack {
                HistoryView(
                    database: database,
                    routeExplorer: routeExplorer,
                    openSky: openSky
                )
            }
            .tabItem {
                Label("History", systemImage: "book.closed")
            }
            .tag(Tab.history)
        }
        .tint(FlightTheme.accent)
        .task {
            // Defer PKPassLibrary initialization until the first task
            // run, so app launch isn't blocked by it.
            wallet.start()
        }
        .onChange(of: wallet.pendingPass) { _, pass in
            // A new boarding pass landed in Wallet — surface the
            // add-flight sheet pre-populated from it.
            guard let pass else { return }
            walletPrefill = AddFlightView.Prefill(
                flightDate: pass.flightDate,
                carrierICAO: nil,
                carrierIATA: pass.carrierIATA,
                flightNumber: pass.flightNumber,
                departureIATA: pass.departureIATA,
                arrivalIATA: pass.arrivalIATA,
                scheduledDeparture: pass.flightDate,
                scheduledArrival: nil,
                aircraftType: nil,
                registration: nil,
                icao24: nil,
                source: "wallet"
            )
        }
        .sheet(item: $walletPrefill) { prefill in
            let store = FlightHistoryStore(context: modelContext, airportDatabase: database)
            AddFlightView(
                routeExplorer: routeExplorer,
                database: database,
                store: store,
                prefill: prefill
            )
            .onDisappear { wallet.clearPending() }
        }
        .sheet(item: $urlPrefill) { prefill in
            let store = FlightHistoryStore(context: modelContext, airportDatabase: database)
            AddFlightView(
                routeExplorer: routeExplorer,
                database: database,
                store: store,
                prefill: prefill
            )
        }
        .onOpenURL { url in
            // Share Extension hands us a URL like:
            //   flights://import?carrier=WN&num=7&dep=DAL&arr=HOU&date=1779892800
            guard url.scheme == "flights", url.host == "import" else { return }
            let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
            let q = components?.queryItems ?? []
            func val(_ k: String) -> String? { q.first { $0.name == k }?.value }
            let dateInterval = val("date").flatMap(TimeInterval.init)
            let prefill = AddFlightView.Prefill(
                flightDate: dateInterval.map { Date(timeIntervalSince1970: $0) } ?? Date(),
                carrierICAO: nil,
                carrierIATA: val("carrier"),
                flightNumber: val("num"),
                departureIATA: val("dep"),
                arrivalIATA: val("arr"),
                scheduledDeparture: nil,
                scheduledArrival: nil,
                aircraftType: nil,
                registration: nil,
                icao24: nil,
                source: "mail-share"
            )
            selectedTab = .history
            urlPrefill = prefill
        }
    }
}

extension AddFlightView.Prefill: Identifiable {
    public var id: String {
        // Stable enough — pass-prompted prefills are one-at-a-time.
        "\(flightDate.timeIntervalSince1970)-\(carrierIATA ?? "")\(flightNumber ?? "")"
    }
}
