import SwiftUI

/// Aircraft Stats screen — Total / Newest / Oldest header row, then a
/// ranked list of types you've flown with real airframe photos as row
/// backgrounds, plus a "Most Flown Tail" hero card at the bottom.
struct AircraftStatsView: View {
    let allFlights: [LoggedFlight]
    let store: FlightHistoryStore
    let routeExplorer: RouteExplorerClient

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

    @State private var showingEnrich = false

    var body: some View {
        ScrollView {
            VStack(spacing: 16) {
                header
                if hasAnyAircraftData {
                    topStatsRow
                    typeListSection
                    mostFlownTailSection
                } else {
                    emptyState
                }
                Spacer(minLength: 60)
            }
            .padding(.horizontal, 16)
            .padding(.vertical, 4)
        }
        .background(HistoryStyle.background(scheme).ignoresSafeArea())
        .navigationTitle("")
        .toolbar {
            ToolbarItem(placement: .cancellationAction) {
                Button { dismiss() } label: { Image(systemName: "xmark") }
            }
            ToolbarItem(placement: .primaryAction) {
                Button {
                    showingEnrich = true
                } label: {
                    Image(systemName: "wand.and.stars")
                }
            }
        }
        .sheet(isPresented: $showingEnrich) {
            EnrichAircraftTypesView(store: store, routeExplorer: routeExplorer)
        }
    }

    /// True when at least one logged flight has an aircraft type OR
    /// a registration we could surface.
    private var hasAnyAircraftData: Bool {
        !uniqueTypeCodes.isEmpty || mostFlownTail != nil
    }

    private var emptyState: some View {
        VStack(spacing: 16) {
            Image(systemName: "airplane.circle")
                .font(.system(size: 56, weight: .heavy))
                .foregroundStyle(HistoryStyle.runwayOrange)
                .padding(.top, 32)
            Text("No aircraft data yet")
                .font(.system(size: 20, weight: .heavy))
                .foregroundStyle(HistoryStyle.ink(scheme))
            Text("Most flights in your log were imported from CSV — that export doesn't include the aircraft type. Look it up via the scheduled equipment, or fill in manually.")
                .multilineTextAlignment(.center)
                .foregroundStyle(HistoryStyle.inkSecondary(scheme))
                .font(.system(size: 14))
                .padding(.horizontal, 24)

            Button {
                showingEnrich = true
            } label: {
                HStack(spacing: 8) {
                    Image(systemName: "wand.and.stars")
                    Text("Look up missing types")
                        .font(.system(size: 15, weight: .heavy))
                }
                .padding(.horizontal, 20)
                .padding(.vertical, 12)
                .background(HistoryStyle.runwayOrange, in: Capsule())
                .foregroundStyle(.white)
            }
            .padding(.top, 8)

            VStack(alignment: .leading, spacing: 8) {
                Text("OTHER WAYS")
                    .font(.system(size: 11, weight: .heavy))
                    .tracking(1.3)
                    .foregroundStyle(HistoryStyle.inkTertiary(scheme))
                    .padding(.top, 24)
                bullet("Tap an aircraft on the Live tab and \"Add to my flights\"")
                bullet("Open any flight and edit the Tail # / Type by hand")
            }
            .font(.system(size: 13))
            .padding(.horizontal, 28)
        }
    }

    private func bullet(_ text: String) -> some View {
        HStack(alignment: .top, spacing: 10) {
            Circle()
                .fill(HistoryStyle.runwayOrange)
                .frame(width: 6, height: 6)
                .padding(.top, 6)
            Text(text)
                .foregroundStyle(HistoryStyle.inkSecondary(scheme))
        }
    }

    private var header: some View {
        VStack(spacing: 4) {
            Text("AIRCRAFT")
                .font(.system(size: 40, weight: .black))
                .tracking(-0.5)
                .foregroundStyle(HistoryStyle.ink(scheme))
            Rectangle()
                .fill(HistoryStyle.runwayOrange)
                .frame(width: 38, height: 3)
        }
        .frame(maxWidth: .infinity)
        .padding(.top, 8)
        .padding(.bottom, 8)
    }

    // MARK: - Top stats row (3 column tile bar)

    private var topStatsRow: some View {
        HStack(spacing: 10) {
            statTile(label: "Total", value: "\(uniqueTypeCodes.count)", subtitle: "types flown")
            statTile(
                label: "Newest",
                value: newestAirframeAgeLabel(),
                subtitle: newestAirframeYearLabel()
            )
            statTile(
                label: "Oldest",
                value: oldestAirframeAgeLabel(),
                subtitle: oldestAirframeYearLabel()
            )
        }
    }

    private func statTile(label: String, value: String, subtitle: String) -> some View {
        VStack(alignment: .leading, spacing: 4) {
            Text(label.uppercased())
                .font(HistoryStyle.label(10))
                .tracking(1.3)
                .foregroundStyle(HistoryStyle.inkSecondary(scheme))
            Text(value)
                .font(HistoryStyle.displayNumber(22))
                .foregroundStyle(HistoryStyle.ink(scheme))
                .lineLimit(1)
                .minimumScaleFactor(0.6)
            Text(subtitle)
                .font(.system(size: 11))
                .foregroundStyle(HistoryStyle.inkTertiary(scheme))
        }
        .frame(maxWidth: .infinity, alignment: .leading)
        .padding(14)
        .background(HistoryStyle.card(scheme), in: RoundedRectangle(cornerRadius: 16))
    }

    // MARK: - Type list

    private var typeListSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            HistorySectionLabel("By type")
            VStack(spacing: 10) {
                ForEach(rankedTypes, id: \.code) { item in
                    AircraftTypeCard(type: item)
                }
            }
        }
        .padding(.top, 8)
    }

    struct TypeRanked {
        let code: String
        let displayName: String
        let count: Int
        let sampleRegistration: String?
    }

    private var rankedTypes: [TypeRanked] {
        let byType = Dictionary(grouping: allFlights.filter { $0.aircraftType != nil }) { $0.aircraftType! }
        return byType.map { code, list in
            TypeRanked(
                code: code,
                displayName: AircraftDatabase.shared.displayName(forTypeCode: code),
                count: list.count,
                sampleRegistration: list.compactMap { $0.registration }.first
            )
        }
        .sorted { $0.count > $1.count }
    }

    // MARK: - Most-flown tail hero

    @ViewBuilder
    private var mostFlownTailSection: some View {
        if let top = mostFlownTail {
            VStack(alignment: .leading, spacing: 12) {
                HistorySectionLabel("Most flown airframe")
                MostFlownTailCard(reg: top.reg, count: top.count, sample: top.sampleFlight)
            }
            .padding(.top, 8)
        }
    }

    private struct MostFlownTail {
        let reg: String
        let count: Int
        let sampleFlight: LoggedFlight
    }

    private var mostFlownTail: MostFlownTail? {
        let byReg = Dictionary(grouping: allFlights.filter { $0.registration != nil }) { $0.registration! }
        guard let top = byReg.max(by: { $0.value.count < $1.value.count }),
              let sample = top.value.first
        else { return nil }
        return MostFlownTail(reg: top.key, count: top.value.count, sampleFlight: sample)
    }

    // MARK: - Computed metadata helpers

    private var uniqueTypeCodes: Set<String> {
        Set(allFlights.compactMap { $0.aircraftType })
    }

    /// Look up airframes with metadata and find the youngest one we've
    /// flown on. Falls back to a "—" if no airframe has firstFlight
    /// data cached yet.
    private func newestAirframeAgeLabel() -> String {
        guard let m = airframeWith(.newest), let date = m.firstFlightDate else { return "—" }
        let years = Calendar.current.dateComponents([.year], from: date, to: Date()).year ?? 0
        return "\(years)y"
    }
    private func newestAirframeYearLabel() -> String {
        guard let m = airframeWith(.newest), let date = m.firstFlightDate else { return "—" }
        let f = DateFormatter(); f.dateFormat = "yyyy"
        return f.string(from: date)
    }
    private func oldestAirframeAgeLabel() -> String {
        guard let m = airframeWith(.oldest), let date = m.firstFlightDate else { return "—" }
        let years = Calendar.current.dateComponents([.year], from: date, to: Date()).year ?? 0
        return "\(years)y"
    }
    private func oldestAirframeYearLabel() -> String {
        guard let m = airframeWith(.oldest), let date = m.firstFlightDate else { return "—" }
        let f = DateFormatter(); f.dateFormat = "yyyy"
        return f.string(from: date)
    }

    private enum AirframePick { case newest, oldest }

    private func airframeWith(_ pick: AirframePick) -> AirframeMetadata? {
        let regs = Set(allFlights.compactMap { $0.registration })
        let metas = regs.compactMap { store.airframe(for: $0) }
            .filter { $0.firstFlightDate != nil }
        switch pick {
        case .newest: return metas.max(by: { ($0.firstFlightDate ?? .distantPast) < ($1.firstFlightDate ?? .distantPast) })
        case .oldest: return metas.min(by: { ($0.firstFlightDate ?? .distantPast) < ($1.firstFlightDate ?? .distantPast) })
        }
    }
}

// MARK: - Aircraft type card with photo background

struct AircraftTypeCard: View {
    let type: AircraftStatsView.TypeRanked
    @State private var photo: AircraftPhotoService.Photo?
    @Environment(\.colorScheme) private var scheme

    var body: some View {
        ZStack(alignment: .bottomLeading) {
            background
                .frame(height: 120)
            LinearGradient(
                colors: [Color.black.opacity(0.0), Color.black.opacity(0.85)],
                startPoint: .top, endPoint: .bottom
            )
            .frame(height: 120)

            VStack(alignment: .leading, spacing: 4) {
                Text(type.displayName.uppercased())
                    .font(.system(size: 13, weight: .heavy))
                    .tracking(1.5)
                    .foregroundStyle(.white)
                Text(type.code)
                    .font(.system(size: 26, weight: .black).monospaced())
                    .foregroundStyle(.white)
            }
            .padding(14)

            VStack(alignment: .trailing, spacing: 2) {
                Text("\(type.count)")
                    .font(HistoryStyle.displayNumber(28))
                    .foregroundStyle(HistoryStyle.runwayOrange)
                Text("FLIGHTS")
                    .font(.system(size: 9, weight: .bold))
                    .tracking(1.3)
                    .foregroundStyle(.white.opacity(0.7))
            }
            .padding(14)
            .frame(maxWidth: .infinity, alignment: .trailing)
        }
        .frame(height: 120)
        .clipShape(RoundedRectangle(cornerRadius: 16))
        .task(id: type.sampleRegistration ?? type.code) {
            guard let reg = type.sampleRegistration else { return }
            photo = await AircraftPhotoService.shared.photo(registration: reg, icao24: "")
        }
    }

    @ViewBuilder
    private var background: some View {
        if let url = photo?.largeURL {
            AsyncImage(url: url) { phase in
                switch phase {
                case .success(let img): img.resizable().aspectRatio(contentMode: .fill)
                default: HistoryStyle.cardSubtle(scheme)
                }
            }
        } else {
            ZStack {
                HistoryStyle.cardSubtle(scheme)
                Image(systemName: "airplane")
                    .font(.system(size: 60, weight: .heavy))
                    .foregroundStyle(HistoryStyle.runwayOrange.opacity(0.25))
                    .rotationEffect(.degrees(-15))
            }
        }
    }
}

// MARK: - Most flown tail hero

struct MostFlownTailCard: View {
    let reg: String
    let count: Int
    let sample: LoggedFlight
    @State private var photo: AircraftPhotoService.Photo?
    @Environment(\.colorScheme) private var scheme

    var body: some View {
        ZStack(alignment: .bottomLeading) {
            background.frame(height: 240)
            LinearGradient(
                colors: [Color.black.opacity(0.0), Color.black.opacity(0.85)],
                startPoint: .center, endPoint: .bottom
            )
            .frame(height: 240)

            VStack(alignment: .leading, spacing: 6) {
                Text("REPEAT OFFENDER")
                    .font(.system(size: 10, weight: .heavy))
                    .tracking(1.8)
                    .foregroundStyle(HistoryStyle.runwayOrange)
                Text(reg)
                    .font(.system(size: 42, weight: .black).monospaced())
                    .foregroundStyle(.white)
                HStack(spacing: 16) {
                    if let type = sample.aircraftType {
                        kvp(value: type, label: "Type")
                    }
                    kvp(value: "\(count)×", label: "Flown")
                }
            }
            .padding(18)
        }
        .frame(height: 240)
        .clipShape(RoundedRectangle(cornerRadius: 20))
        .task(id: reg) {
            photo = await AircraftPhotoService.shared.photo(registration: reg, icao24: "")
        }
    }

    @ViewBuilder
    private var background: some View {
        if let url = photo?.largeURL {
            AsyncImage(url: url) { phase in
                switch phase {
                case .success(let img): img.resizable().aspectRatio(contentMode: .fill)
                default: HistoryStyle.heroNavyGradient
                }
            }
        } else {
            HistoryStyle.heroNavyGradient
        }
    }

    private func kvp(value: String, label: String) -> some View {
        VStack(alignment: .leading, spacing: 0) {
            Text(value)
                .font(.system(size: 14, weight: .heavy).monospaced())
                .foregroundStyle(.white)
            Text(label.uppercased())
                .font(.system(size: 9, weight: .bold))
                .tracking(0.8)
                .foregroundStyle(.white.opacity(0.7))
        }
    }
}
