import SwiftUI
import SwiftData

// MARK: - MeetingEditFlowView
// Erlaubt das nachträgliche Bearbeiten einer bereits abgegebenen Sofort-Bewertung.
// Lädt die gespeicherten Rating-Werte vor und überschreibt sie beim Speichern.

struct MeetingEditFlowView: View {
    @Environment(\.modelContext) private var modelContext
    @Environment(\.dismiss) private var dismiss

    let moment: Moment

    private let questions = RatingQuestion.immediate
    @State private var currentIndex: Int = 0
    @State private var values: [Int?]
    @State private var showNoteStep: Bool = false
    @State private var note: String

    init(moment: Moment) {
        self.moment = moment
        // Vorbefüllen mit gespeicherten Sofort-Rating-Werten
        var prefilled: [Int?] = Array(repeating: nil, count: RatingQuestion.immediate.count)
        if let ratings = moment.ratings {
            for r in ratings where !r.isAftermath {
                if r.questionIndex < prefilled.count {
                    prefilled[r.questionIndex] = r.value
                }
            }
        }
        _values = State(initialValue: prefilled)
        _note = State(initialValue: moment.text)
    }

    var body: some View {
        NavigationStack {
            Group {
                if showNoteStep {
                    noteStep
                } else {
                    questionStep
                }
            }
            .navigationTitle("Bewertung bearbeiten")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Abbrechen") { dismiss() }
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button(nextButtonLabel) { advance() }
                }
            }
        }
    }

    // MARK: - Fragen-Screen

    private var questionStep: some View {
        ZStack {
            RatingQuestionView(
                question: questions[currentIndex],
                index: currentIndex,
                total: questions.count,
                value: $values[currentIndex]
            )
            .id(currentIndex)
            .transition(.asymmetric(
                insertion: .move(edge: .trailing),
                removal: .move(edge: .leading)
            ))
        }
        .clipped()
    }

    // MARK: - Notiz-Screen

    private var noteStep: some View {
        VStack(alignment: .leading, spacing: 20) {
            Text("Notiz anpassen")
                .font(.title3.weight(.semibold))
                .padding(.horizontal, 24)
                .padding(.top, 24)

            ZStack(alignment: .topLeading) {
                RoundedRectangle(cornerRadius: 12)
                    .fill(Color(.secondarySystemBackground))
                if note.isEmpty {
                    Text("Optional – z. B. was besonders war…")
                        .foregroundStyle(.tertiary)
                        .padding(16)
                }
                TextEditor(text: $note)
                    .padding(12)
                    .scrollContentBackground(.hidden)
            }
            .frame(minHeight: 120)
            .padding(.horizontal, 24)

            Spacer()
        }
    }

    // MARK: - Navigation

    private var nextButtonLabel: LocalizedStringKey {
        if showNoteStep { return "Speichern" }
        return "Weiter"
    }

    private func advance() {
        if showNoteStep {
            saveEdits()
            return
        }
        if currentIndex < questions.count - 1 {
            withAnimation(.easeInOut(duration: 0.25)) { currentIndex += 1 }
        } else {
            withAnimation { showNoteStep = true }
        }
    }

    // MARK: - Speichern

    private func saveEdits() {
        // Bestehende Sofort-Ratings in-place aktualisieren
        if let ratings = moment.ratings {
            for rating in ratings where !rating.isAftermath {
                if rating.questionIndex < values.count {
                    rating.value = values[rating.questionIndex]
                }
            }
        }
        let trimmed = note.trimmingCharacters(in: .whitespacesAndNewlines)
        if !trimmed.isEmpty {
            moment.text = trimmed
        }
        moment.updatedAt = Date()

        do {
            try modelContext.save()
            AppEventLog.shared.record(
                "Treffen-Bewertung bearbeitet: Moment \(moment.id.uuidString)",
                level: .info, category: "Meeting"
            )
        } catch {
            AppEventLog.shared.record(
                "Fehler beim Aktualisieren der Bewertung: \(error.localizedDescription)",
                level: .error, category: "Meeting"
            )
        }
        dismiss()
    }
}
