import SwiftUI

/// Shared add-flight form. Used by:
///   - The "+" toolbar on the History tab (no prefill — full manual entry)
///   - The "Add to my flights" button on a live aircraft sheet (prefilled
///     from FR24 enrichment)
///   - Calendar import (prefilled from a calendar event regex match)
///   - Mail Share Extension (prefilled from a parsed email)
///
/// The user can always edit any field. The "Look up" action hits
/// route-explorer's schedule endpoint to fill departure/arrival/times
/// given a carrier + flight # + date.
struct AddFlightView: View {
    let routeExplorer: RouteExplorerClient
    let database: AirportDatabase
    let store: FlightHistoryStore
    let prefill: Prefill?

    @Environment(\.dismiss) private var dismiss

    @State private var flightDate: Date = Date()
    @State private var carrierIATA: String = ""
    @State private var flightNumber: String = ""
    @State private var departureIATA: String = ""
    @State private var arrivalIATA: String = ""
    @State private var scheduledDeparture: Date?
    @State private var scheduledArrival: Date?
    @State private var aircraftType: String = ""
    @State private var registration: String = ""
    @State private var icao24: String = ""
    @State private var notes: String = ""

    @State private var isLooking = false
    @State private var lookupError: String?

    struct Prefill {
        var flightDate: Date
        var carrierICAO: String?
        var carrierIATA: String?
        var flightNumber: String?
        var departureIATA: String?
        var arrivalIATA: String?
        var scheduledDeparture: Date?
        var scheduledArrival: Date?
        var aircraftType: String?
        var registration: String?
        var icao24: String?
        var source: String
    }

    var body: some View {
        NavigationStack {
            Form {
                Section("Flight") {
                    DatePicker("Date", selection: $flightDate, displayedComponents: .date)
                    HStack {
                        TextField("Airline (e.g. WN)", text: $carrierIATA)
                            .autocorrectionDisabled()
                            .textInputAutocapitalization(.characters)
                            .frame(width: 100)
                        TextField("Flight #", text: $flightNumber)
                            .keyboardType(.numberPad)
                        Button(action: { Task { await runLookup() } }) {
                            if isLooking { ProgressView() }
                            else { Image(systemName: "magnifyingglass") }
                        }
                        .disabled(carrierIATA.isEmpty || flightNumber.isEmpty || isLooking)
                    }
                    if let lookupError {
                        Text(lookupError)
                            .font(.caption)
                            .foregroundStyle(.red)
                    }
                }
                Section("Route") {
                    TextField("From (IATA)", text: $departureIATA)
                        .autocorrectionDisabled()
                        .textInputAutocapitalization(.characters)
                    TextField("To (IATA)", text: $arrivalIATA)
                        .autocorrectionDisabled()
                        .textInputAutocapitalization(.characters)
                    if let dep = Binding($scheduledDeparture) {
                        DatePicker("Departure", selection: dep)
                    } else {
                        Button("Add scheduled departure") { scheduledDeparture = flightDate }
                    }
                    if let arr = Binding($scheduledArrival) {
                        DatePicker("Arrival", selection: arr)
                    } else {
                        Button("Add scheduled arrival") { scheduledArrival = flightDate }
                    }
                }
                Section("Aircraft") {
                    TextField("Type (e.g. B738)", text: $aircraftType)
                        .autocorrectionDisabled()
                        .textInputAutocapitalization(.characters)
                    TextField("Tail # (e.g. N281WN)", text: $registration)
                        .autocorrectionDisabled()
                        .textInputAutocapitalization(.characters)
                }
                Section("Notes") {
                    TextField("Optional", text: $notes, axis: .vertical)
                        .lineLimit(3...8)
                }
            }
            .navigationTitle("Add flight")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Cancel") { dismiss() }
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button("Save") { save() }
                        .disabled(!isValid)
                }
            }
            .onAppear { applyPrefill() }
        }
    }

    private var isValid: Bool {
        !departureIATA.isEmpty && !arrivalIATA.isEmpty
            && departureIATA.count >= 3 && arrivalIATA.count >= 3
    }

    private func applyPrefill() {
        guard let p = prefill else { return }
        flightDate = p.flightDate
        carrierIATA = p.carrierIATA ?? ""
        flightNumber = p.flightNumber ?? ""
        departureIATA = (p.departureIATA ?? "").uppercased()
        arrivalIATA = (p.arrivalIATA ?? "").uppercased()
        scheduledDeparture = p.scheduledDeparture
        scheduledArrival = p.scheduledArrival
        aircraftType = (p.aircraftType ?? "").uppercased()
        registration = (p.registration ?? "").uppercased()
        icao24 = (p.icao24 ?? "").lowercased()
    }

    private func runLookup() async {
        isLooking = true
        defer { isLooking = false }
        lookupError = nil
        guard let num = Int(flightNumber.trimmingCharacters(in: .whitespaces)) else {
            lookupError = "Flight number must be numeric"
            return
        }
        let day = Calendar.current.startOfDay(for: flightDate)
        let next = Calendar.current.date(byAdding: .day, value: 1, to: day) ?? day
        let results = await routeExplorer.searchSchedule(
            carrierCode: carrierIATA.uppercased(),
            flightNumber: num,
            startDate: day,
            endDate: next
        )
        guard let r = results.first else {
            lookupError = "No schedule match for \(carrierIATA)\(flightNumber) on this date"
            return
        }
        departureIATA = r.departure.airportIata
        arrivalIATA = r.arrival.airportIata
        scheduledDeparture = r.departure.dateTime
        scheduledArrival = r.arrival.dateTime
    }

    private func save() {
        let carrierICAO = AircraftRegistry.shared.lookup(iata: carrierIATA)?.icao
        let f = LoggedFlight(
            flightDate: flightDate,
            carrierICAO: carrierICAO,
            carrierIATA: carrierIATA.isEmpty ? nil : carrierIATA.uppercased(),
            flightNumber: flightNumber.isEmpty ? nil : flightNumber,
            departureIATA: departureIATA.uppercased(),
            arrivalIATA: arrivalIATA.uppercased(),
            scheduledDeparture: scheduledDeparture,
            scheduledArrival: scheduledArrival,
            aircraftType: aircraftType.isEmpty ? nil : aircraftType.uppercased(),
            registration: registration.isEmpty ? nil : registration.uppercased(),
            icao24: icao24.isEmpty ? nil : icao24.lowercased(),
            notes: notes.isEmpty ? nil : notes,
            source: prefill?.source ?? "manual"
        )
        store.save(f)
        dismiss()
    }
}
