import SwiftUI

struct EditRouteSheet: View {
    let routeId: Int

    @Environment(\.dismiss) private var dismiss

    @State private var name: String
    @State private var beschreibung: String
    @State private var isPublic: Bool
    @State private var isSaving = false
    @State private var errorMessage: String?

    let onSaved: (RouteDetail) -> Void

    init(detail: RouteDetail, onSaved: @escaping (RouteDetail) -> Void) {
        self.routeId = detail.id
        self.onSaved = onSaved
        _name = State(initialValue: detail.name)
        _beschreibung = State(initialValue: detail.beschreibung ?? "")
        _isPublic = State(initialValue: false) // backend field; default to private
    }

    var body: some View {
        NavigationStack {
            Form {
                Section("Name") {
                    TextField("Name", text: $name)
                }
                Section("Beschreibung") {
                    TextField("Beschreibung", text: $beschreibung, axis: .vertical)
                        .lineLimit(3...8)
                }
                Section {
                    Toggle("Öffentlich sichtbar", isOn: $isPublic)
                }
                if let errorMessage {
                    Section {
                        Text(errorMessage).font(.footnote).foregroundStyle(.red)
                    }
                }
            }
            .navigationTitle("Tour bearbeiten")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Abbrechen") { dismiss() }
                        .disabled(isSaving)
                }
                ToolbarItem(placement: .confirmationAction) {
                    if isSaving {
                        ProgressView()
                    } else {
                        Button("Sichern") { Task { await save() } }
                            .disabled(name.trimmingCharacters(in: .whitespaces).isEmpty)
                    }
                }
            }
            .interactiveDismissDisabled(isSaving)
        }
    }

    private func save() async {
        isSaving = true
        errorMessage = nil
        defer { isSaving = false }
        let body = RouteUpdateBody(
            name: name.trimmingCharacters(in: .whitespaces),
            beschreibung: beschreibung.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
                ? nil : beschreibung.trimmingCharacters(in: .whitespacesAndNewlines),
            isPublic: isPublic
        )
        do {
            let updated: RouteDetail = try await APIClient.shared.patch(
                "/api/routes/\(routeId)",
                body: body
            )
            onSaved(updated)
            dismiss()
        } catch {
            errorMessage = error.localizedDescription
        }
    }
}
