import Foundation
import Observation

@MainActor
@Observable
final class RouteDetailViewModel {

    // MARK: - State

    var allSchedules: [FlightSchedule] = []
    var isLoading: Bool = false
    var error: String?
    var selectedDate: Date
    var loadingProgress: (completed: Int, total: Int)?

    // MARK: - Computed

    var flightsForDate: [FlightSchedule] {
        allSchedules
            .filter { $0.operatesOn(date: selectedDate) }
            .sorted { $0.departureTime < $1.departureTime }
    }

    var airlineGroups: [(airline: Airline, flights: [FlightSchedule])] {
        let flights = flightsForDate
        let grouped = Dictionary(grouping: flights) { $0.airline.id }

        return grouped
            .map { (_, schedules) in
                (airline: schedules[0].airline, flights: schedules.sorted { $0.departureTime < $1.departureTime })
            }
            .sorted { $0.airline.name.localizedCompare($1.airline.name) == .orderedAscending }
    }

    // MARK: - Private

    private let service: FlightService

    // MARK: - Init

    init(service: FlightService, date: Date) {
        self.service = service
        self.selectedDate = date
    }

    // MARK: - Loading

    func loadSchedules(dep: String, des: String) async {
        isLoading = true
        error = nil
        loadingProgress = nil

        do {
            let results = try await service.allSchedules(dep: dep, des: des) { [weak self] completed, total in
                Task { @MainActor [weak self] in
                    self?.loadingProgress = (completed: completed, total: total)
                }
            }
            if !Task.isCancelled {
                allSchedules = results
            }
        } catch {
            if !Task.isCancelled {
                self.error = error.localizedDescription
            }
        }

        if !Task.isCancelled {
            isLoading = false
        }
    }
}
