import SwiftUI

/// The Passport screen. Replaces the old "Lifetime Stats" sheet —
/// stacked colored hero cards, each one feature-sized for a single
/// stat, year tabs at the top to re-scope, OCR-passport flex footer
/// at the bottom. Pure read-only.
struct PassportView: View {
    let stats: StatsEngine
    let allFlights: [LoggedFlight]
    let database: AirportDatabase
    let store: FlightHistoryStore
    @Binding var selectedYear: Int?

    @Environment(\.dismiss) private var dismiss
    @Environment(\.colorScheme) private var scheme

    var body: some View {
        ScrollView {
            VStack(spacing: 14) {
                header
                YearTabStrip(years: yearsList, selection: $selectedYear)
                    .padding(.vertical, 4)
                cards
                OCRPassportFooter(owner: "TARTT GARY", issued: stats.flights.first?.flightDate ?? Date())
                    .padding(.horizontal, 16)
                    .padding(.top, 12)
                Spacer(minLength: 60)
            }
            .padding(.vertical, 4)
        }
        .background(HistoryStyle.background(scheme).ignoresSafeArea())
        .navigationTitle("")
        .toolbar {
            ToolbarItem(placement: .cancellationAction) {
                Button { dismiss() } label: { Image(systemName: "xmark") }
            }
        }
    }

    private var header: some View {
        VStack(spacing: 4) {
            Text(selectedYear == nil ? "ALL TIME" : String(selectedYear!))
                .font(.system(size: 12, weight: .heavy))
                .tracking(2.5)
                .foregroundStyle(HistoryStyle.inkTertiary(scheme))
            Text("PASSPORT")
                .font(.system(size: 40, weight: .black))
                .tracking(-0.5)
                .foregroundStyle(HistoryStyle.ink(scheme))
            Rectangle()
                .fill(HistoryStyle.runwayOrange)
                .frame(width: 38, height: 3)
                .padding(.top, 4)
        }
        .frame(maxWidth: .infinity)
        .padding(.top, 8)
        .padding(.bottom, 12)
    }

    private var yearsList: [Int] {
        let cal = Calendar.current
        return Array(Set(allFlights.map { cal.component(.year, from: $0.flightDate) })).sorted(by: >)
    }

    /// Stats for the current scope — either lifetime or one year.
    private var scopedStats: StatsEngine {
        guard let y = selectedYear else { return stats }
        let filtered = allFlights.filter { Calendar.current.component(.year, from: $0.flightDate) == y }
        return StatsEngine(store: store, database: database, flights: filtered)
    }

    @ViewBuilder
    private var cards: some View {
        let s = scopedStats
        VStack(spacing: 12) {
            HeroStatCard(
                label: "FLIGHTS",
                value: numberString(s.totalFlights),
                subtitle: "across \(s.uniqueAirports) airports",
                variant: .orange
            ) {
                HStack(spacing: 16) {
                    StatColumn(label: "Airlines", value: "\(s.uniqueAirlines)")
                    StatColumn(label: "Aircraft", value: "\(s.uniqueAircraftTypes)")
                    StatColumn(label: "Countries", value: "\(s.uniqueCountries)")
                }
                .padding(.top, 4)
            }

            HeroStatCard(
                label: "DISTANCE",
                value: s.shortDistance + " mi",
                subtitle: equatorComparison(miles: s.totalMiles),
                variant: .navy
            ) { EmptyView() }

            HeroStatCard(
                label: "TIME ALOFT",
                value: hoursAloftDisplay(s.totalMinutes),
                subtitle: timeAloftSubtitle(s.totalMinutes),
                variant: .gold,
                onForeground: .white
            ) { EmptyView() }

            if let top = s.topRoute {
                HeroStatCard(
                    label: "TOP ROUTE",
                    value: top.label.replacingOccurrences(of: "↔", with: " ↔ "),
                    subtitle: "\(top.count) trips",
                    variant: .green
                ) { EmptyView() }
            }

            if let topAirline = s.topAirline {
                let name = AircraftRegistry.shared.lookup(icao: topAirline.icao)?.name ?? topAirline.icao
                HeroStatCard(
                    label: "TOP AIRLINE",
                    value: name,
                    subtitle: "\(topAirline.count) flights",
                    variant: .orange
                ) { EmptyView() }
            }

            if let longest = s.longestFlight,
               let miles = store.distanceMiles(for: longest) {
                HeroStatCard(
                    label: "LONGEST FLIGHT",
                    value: "\(longest.departureIATA) → \(longest.arrivalIATA)",
                    subtitle: "\(numberString(miles)) mi · \(shortDate(longest.flightDate))",
                    variant: .navy
                ) { EmptyView() }
            }

            repeatedTailsCard(s)
        }
        .padding(.horizontal, 16)
    }

    @ViewBuilder
    private func repeatedTailsCard(_ s: StatsEngine) -> some View {
        let tails = s.repeatedTails.prefix(5)
        if !tails.isEmpty {
            VStack(alignment: .leading, spacing: 12) {
                HistorySectionLabel("Airframes you've repeated")
                    .foregroundStyle(HistoryStyle.inkSecondary(scheme))
                VStack(spacing: 0) {
                    ForEach(Array(tails.enumerated()), id: \.offset) { index, item in
                        HStack {
                            Text(item.reg)
                                .font(.system(size: 14, weight: .bold).monospaced())
                                .foregroundStyle(HistoryStyle.ink(scheme))
                            Spacer()
                            Text("\(item.count)×")
                                .font(.system(size: 14, weight: .black).monospacedDigit())
                                .foregroundStyle(HistoryStyle.runwayOrange)
                        }
                        .padding(.horizontal, 16)
                        .padding(.vertical, 12)
                        if index < tails.count - 1 {
                            Rectangle()
                                .fill(HistoryStyle.hairline(scheme))
                                .frame(height: 0.5)
                                .padding(.horizontal, 16)
                        }
                    }
                }
            }
            .padding(.vertical, 14)
            .background(HistoryStyle.card(scheme), in: RoundedRectangle(cornerRadius: 22))
        }
    }

    // MARK: - Helpers

    private func numberString(_ n: Int) -> String {
        let f = NumberFormatter()
        f.numberStyle = .decimal
        return f.string(from: NSNumber(value: n)) ?? "\(n)"
    }

    private func equatorComparison(miles: Int) -> String {
        let equator = 24_901
        let ratio = Double(miles) / Double(equator)
        if miles == 0 { return "—" }
        if ratio < 0.05 { return "miles flown" }
        if ratio < 1 { return String(format: "%.0f%% of the way around earth", ratio * 100) }
        return String(format: "%.1f× around the equator", ratio)
    }

    private func hoursAloftDisplay(_ minutes: Int) -> String {
        let days = minutes / (60 * 24)
        let hours = (minutes % (60 * 24)) / 60
        if days > 0 {
            return "\(days)d \(hours)h"
        }
        return "\(hours)h"
    }

    private func timeAloftSubtitle(_ minutes: Int) -> String {
        if minutes <= 0 { return "—" }
        return "≈ \(numberString(minutes / 60)) total hours airborne"
    }

    private func shortDate(_ d: Date) -> String {
        let f = DateFormatter()
        f.dateFormat = "MMM d, yyyy"
        return f.string(from: d)
    }
}
