//
// NotesEditView.swift
// Workouts
//
// Copyright 2025 Rouslan Zenetl. All Rights Reserved.
//

import SwiftUI
import SwiftData

struct NotesEditView: View {
    @Environment(SyncEngine.self) private var sync
    @Environment(\.dismiss) private var dismiss

    let workout: Workout
    let logID: String

    @State private var notesText: String = ""

    var body: some View {
        NavigationStack {
            Form {
                Section {
                    TextEditor(text: $notesText)
                        .frame(minHeight: 200)
                }
            }
            .navigationTitle("Edit Notes")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Cancel") {
                        dismiss()
                    }
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button("Save") {
                        saveChanges()
                        dismiss()
                    }
                }
            }
            .onAppear {
                notesText = WorkoutDocument(from: workout)
                    .logs.first(where: { $0.id == logID })?.notes ?? ""
            }
        }
    }

    private func saveChanges() {
        var doc = WorkoutDocument(from: workout)
        guard let i = doc.logs.firstIndex(where: { $0.id == logID }) else { return }
        doc.logs[i].notes = notesText
        doc.logs[i].touch()
        doc.updatedAt = Date()
        let snapshot = doc
        Task { await sync.save(workout: snapshot) }
    }
}
