import SwiftUI

/// Year in Review — horizontal-paged deck of share-ready hero cards
/// for the chosen year. Each card is a full-screen composition: huge
/// stat number, small subtitle, footer brand mark.
struct YearInReviewView: View {
    let stats: StatsEngine
    let year: Int

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

    var body: some View {
        let yearFlights = stats.flights(for: year)
        let yearStats = StatsEngine(store: stats.store, database: stats.database, flights: yearFlights)

        NavigationStack {
            TabView {
                coverCard(year: year, flights: yearFlights.count)
                if yearStats.totalMiles > 0 {
                    distanceCard(yearStats)
                }
                airportsCard(yearStats)
                hoursCard(yearStats)
                if let top = yearStats.topAirline {
                    topAirlineCard(top)
                }
                if let route = yearStats.topRoute {
                    topRouteCard(route)
                }
                if let longest = yearStats.longestFlight {
                    longestCard(longest, yearStats: yearStats)
                }
            }
            .tabViewStyle(.page(indexDisplayMode: .always))
            .background(HistoryStyle.midnightNavy.ignoresSafeArea())
            .navigationTitle("\(year) Year in Flight")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button { dismiss() } label: { Image(systemName: "xmark") }
                }
            }
        }
    }

    // MARK: - Card variants

    private func coverCard(year: Int, flights: Int) -> some View {
        HeroComposition(background: HistoryStyle.heroOrangeGradient) {
            VStack(spacing: 12) {
                Spacer()
                Text("\(year)")
                    .font(.system(size: 140, weight: .black).monospacedDigit())
                    .foregroundStyle(.white)
                Text("YEAR IN FLIGHT")
                    .font(.system(size: 18, weight: .heavy))
                    .tracking(2.5)
                    .foregroundStyle(.white.opacity(0.85))
                Spacer()
                Text("\(flights) flights logged")
                    .font(.system(size: 14, weight: .semibold))
                    .foregroundStyle(.white.opacity(0.7))
            }
        }
    }

    private func distanceCard(_ s: StatsEngine) -> some View {
        HeroComposition(background: HistoryStyle.heroNavyGradient) {
            cardBody(
                eyebrow: "DISTANCE",
                hero: s.shortDistance,
                heroAccent: "mi",
                subtitle: equatorBlurb(miles: s.totalMiles)
            )
        }
    }

    private func airportsCard(_ s: StatsEngine) -> some View {
        HeroComposition(background: HistoryStyle.heroGreenGradient) {
            cardBody(
                eyebrow: "PASSPORT STAMPS",
                hero: "\(s.uniqueAirports)",
                heroAccent: "airports",
                subtitle: "\(s.uniqueCountries) countries"
            )
        }
    }

    private func hoursCard(_ s: StatsEngine) -> some View {
        HeroComposition(background: HistoryStyle.heroGoldGradient) {
            cardBody(
                eyebrow: "TIME ALOFT",
                hero: hoursDisplay(s.totalMinutes),
                heroAccent: "",
                subtitle: "≈ \(s.totalMinutes / 60) hours airborne"
            )
        }
    }

    private func topAirlineCard(_ top: (icao: String, count: Int)) -> some View {
        let name = AircraftRegistry.shared.lookup(icao: top.icao)?.name ?? top.icao
        return HeroComposition(background: HistoryStyle.heroOrangeGradient) {
            cardBody(
                eyebrow: "TOP AIRLINE",
                hero: name,
                heroAccent: "",
                subtitle: "\(top.count) flights"
            )
        }
    }

    private func topRouteCard(_ route: (label: String, count: Int)) -> some View {
        HeroComposition(background: HistoryStyle.heroNavyGradient) {
            cardBody(
                eyebrow: "TOP ROUTE",
                hero: route.label.replacingOccurrences(of: "↔", with: " ↔ "),
                heroAccent: "",
                subtitle: "\(route.count) trips"
            )
        }
    }

    private func longestCard(_ longest: LoggedFlight, yearStats: StatsEngine) -> some View {
        let miles = yearStats.store.distanceMiles(for: longest) ?? 0
        return HeroComposition(background: HistoryStyle.heroGreenGradient) {
            cardBody(
                eyebrow: "ENDURANCE RECORD",
                hero: "\(longest.departureIATA) → \(longest.arrivalIATA)",
                heroAccent: "",
                subtitle: "\(numberString(miles)) miles"
            )
        }
    }

    // MARK: - Card body template

    private func cardBody(eyebrow: String, hero: String, heroAccent: String, subtitle: String) -> some View {
        VStack(spacing: 16) {
            Spacer()
            Text(eyebrow)
                .font(.system(size: 14, weight: .heavy))
                .tracking(3)
                .foregroundStyle(.white.opacity(0.8))
            HStack(alignment: .firstTextBaseline, spacing: 8) {
                Text(hero)
                    .font(.system(size: 64, weight: .black).monospacedDigit())
                    .foregroundStyle(.white)
                    .lineLimit(2)
                    .minimumScaleFactor(0.4)
                    .multilineTextAlignment(.center)
                if !heroAccent.isEmpty {
                    Text(heroAccent)
                        .font(.system(size: 22, weight: .heavy))
                        .foregroundStyle(.white.opacity(0.7))
                }
            }
            Text(subtitle)
                .font(.system(size: 16, weight: .semibold))
                .foregroundStyle(.white.opacity(0.85))
                .multilineTextAlignment(.center)
            Spacer()
            Text("FLIGHTS · \(year)")
                .font(.system(size: 10, weight: .heavy))
                .tracking(2)
                .foregroundStyle(.white.opacity(0.55))
        }
        .padding(20)
        .multilineTextAlignment(.center)
    }

    // MARK: - Helpers

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

    private func hoursDisplay(_ 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 numberString(_ n: Int) -> String {
        let f = NumberFormatter(); f.numberStyle = .decimal
        return f.string(from: NSNumber(value: n)) ?? "\(n)"
    }
}

/// Card frame for the Year in Review deck — generic background +
/// foreground content. Used to keep page-to-page motion + sizing
/// consistent.
private struct HeroComposition<Content: View>: View {
    let background: LinearGradient
    @ViewBuilder var content: () -> Content

    var body: some View {
        ZStack {
            background
            content()
        }
        .clipShape(RoundedRectangle(cornerRadius: 28))
        .padding(.horizontal, 24)
        .padding(.vertical, 32)
    }
}
