//
//  BatteryCheckpointEditorSheetView.swift
//  USB Meter
//
//  Created by Codex on 10/04/2026.
//

import SwiftUI

struct BatteryCheckpointEditorSheetView: View {
    @EnvironmentObject private var appData: AppData
    @EnvironmentObject private var meter: Meter
    @Environment(\.dismiss) private var dismiss

    @State private var batteryPercent = ""
    @State private var label = ""

    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("Checkpoint")) {
                    TextField("Battery %", text: $batteryPercent)
                        .keyboardType(.decimalPad)
                    TextField("Label (optional)", text: $label)
                }

                Section {
                    Text("The checkpoint is stored on the active charge session and later used for capacity estimation and the typical charge curve.")
                        .font(.footnote)
                        .foregroundColor(.secondary)
                }
            }
            .navigationTitle("Battery Checkpoint")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Cancel") {
                        dismiss()
                    }
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button("Save") {
                        guard let percent = Double(batteryPercent) else {
                            return
                        }

                        let didSave = appData.addBatteryCheckpoint(
                            percent: percent,
                            label: label,
                            for: meter
                        )
                        if didSave {
                            dismiss()
                        }
                    }
                    .disabled(
                        (Double(batteryPercent) ?? -1) < 0
                            || (Double(batteryPercent) ?? 101) > 100
                            || appData.activeChargeSessionSummary(for: meter.btSerial.macAddress.description) == nil
                    )
                }
            }
        }
        .navigationViewStyle(StackNavigationViewStyle())
    }
}
