import SwiftUI

/// Lightweight local-only IATA airport picker, backed by AirportDatabase.
/// No network — used by the route-explorer flows where we only need the
/// IATA code, not a flightconnections.com ID.
struct IATAAirportPicker: View {
    let label: String
    @Binding var selection: MapAirport?
    let database: AirportDatabase

    @State private var query: String = ""
    @State private var isFocused: Bool = false
    @FocusState private var fieldFocused: Bool

    private var suggestions: [MapAirport] {
        let q = query.trimmingCharacters(in: .whitespaces).uppercased()
        guard q.count >= 2 else { return [] }

        // Score: exact IATA match first, then prefix on IATA, then any name contains.
        var exact: [MapAirport] = []
        var iataPrefix: [MapAirport] = []
        var nameMatch: [MapAirport] = []

        for airport in database.airports {
            if airport.iata == q {
                exact.append(airport)
            } else if airport.iata.hasPrefix(q) {
                iataPrefix.append(airport)
            } else if airport.name.uppercased().contains(q) {
                nameMatch.append(airport)
            }
            if exact.count + iataPrefix.count + nameMatch.count > 30 { break }
        }
        return Array((exact + iataPrefix + nameMatch).prefix(10))
    }

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            HStack {
                TextField(label, text: $query)
                    .textInputAutocapitalization(.characters)
                    .autocorrectionDisabled()
                    .focused($fieldFocused)
                    .onChange(of: fieldFocused) { _, new in
                        isFocused = new
                    }
                    .onChange(of: selection) { _, new in
                        if let new {
                            query = "\(new.iata) — \(new.name)"
                            fieldFocused = false
                        }
                    }

                if selection != nil {
                    Button {
                        selection = nil
                        query = ""
                    } label: {
                        Image(systemName: "xmark.circle.fill")
                            .foregroundStyle(.secondary)
                    }
                    .buttonStyle(.plain)
                }
            }
            .padding(.horizontal, 14)
            .padding(.vertical, 12)
            .background(FlightTheme.cardBackground)
            .clipShape(RoundedRectangle(cornerRadius: 12))

            if isFocused, !suggestions.isEmpty, selection?.iata != suggestions.first?.iata {
                VStack(spacing: 0) {
                    ForEach(suggestions) { airport in
                        Button {
                            selection = airport
                            query = "\(airport.iata) — \(airport.name)"
                            fieldFocused = false
                        } label: {
                            HStack {
                                Text(airport.iata)
                                    .font(FlightTheme.flightNumber(14))
                                    .foregroundStyle(FlightTheme.accent)
                                    .frame(width: 44, alignment: .leading)
                                VStack(alignment: .leading, spacing: 2) {
                                    Text(airport.name)
                                        .font(.subheadline)
                                        .foregroundStyle(FlightTheme.textPrimary)
                                        .lineLimit(1)
                                    Text(airport.country)
                                        .font(.caption)
                                        .foregroundStyle(FlightTheme.textSecondary)
                                }
                                Spacer()
                            }
                            .padding(.horizontal, 14)
                            .padding(.vertical, 10)
                            .contentShape(Rectangle())
                        }
                        .buttonStyle(.plain)

                        if airport.id != suggestions.last?.id {
                            Divider().padding(.leading, 14)
                        }
                    }
                }
                .background(FlightTheme.cardBackground)
                .clipShape(RoundedRectangle(cornerRadius: 12))
                .shadow(color: FlightTheme.cardShadow, radius: 6, y: 2)
            }
        }
    }
}
