import SwiftUI

/// Single row in the history list. Loads the airframe photo
/// asynchronously and renders a thumb on the left, flight identity in
/// the middle, date on the right.
struct HistoryRowView: View {
    let flight: LoggedFlight
    let database: AirportDatabase

    @State private var photo: AircraftPhotoService.Photo?

    var body: some View {
        HStack(spacing: 12) {
            thumbnail
                .frame(width: 64, height: 48)
                .clipShape(RoundedRectangle(cornerRadius: 8))

            VStack(alignment: .leading, spacing: 4) {
                HStack(spacing: 6) {
                    Text(flight.flightLabel)
                        .font(.subheadline.weight(.bold).monospaced())
                        .foregroundStyle(FlightTheme.textPrimary)
                    if let type = flight.aircraftType {
                        Text("· \(type)")
                            .font(.caption.monospaced())
                            .foregroundStyle(FlightTheme.textTertiary)
                    }
                }
                HStack(spacing: 6) {
                    Text(flight.departureIATA)
                        .font(.caption.weight(.semibold).monospaced())
                        .foregroundStyle(FlightTheme.textSecondary)
                    Image(systemName: "arrow.right")
                        .font(.caption2)
                        .foregroundStyle(FlightTheme.textTertiary)
                    Text(flight.arrivalIATA)
                        .font(.caption.weight(.semibold).monospaced())
                        .foregroundStyle(FlightTheme.textSecondary)
                }
            }

            Spacer()

            Text(shortDate(flight.flightDate))
                .font(.caption.monospaced())
                .foregroundStyle(FlightTheme.textTertiary)
        }
        .padding(.vertical, 4)
        .task(id: flight.registration ?? flight.id.uuidString) {
            guard let reg = flight.registration, !reg.isEmpty else { return }
            photo = await AircraftPhotoService.shared.photo(
                registration: reg,
                icao24: ""
            )
        }
    }

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

    private var placeholder: some View {
        ZStack {
            FlightTheme.cardBackground
            Image(systemName: "airplane")
                .foregroundStyle(FlightTheme.textTertiary)
        }
    }

    private func shortDate(_ d: Date) -> String {
        let f = DateFormatter()
        f.dateFormat = "MMM d"
        return f.string(from: d)
    }
}
