//
//  SystemEditorView.swift
//  Cable
//
//  Created by Stefan Lange-Hegermann on 16.09.25.
//

import SwiftUI

struct SystemEditorView: View {
    @Binding var systemName: String
    @Binding var location: String
    @Binding var iconName: String
    @Binding var colorName: String
    
    @State private var tempLocation: String
    
    private let systemIcons = [
        "building.2", "house", "building", "tent", "sailboat",
        "airplane", "ferry", "bus", "truck.box",
        "server.rack", "externaldrive", "cpu", "gear", "wrench.adjustable", "hammer",
        "lightbulb", "bolt", "powerplug", "battery.100","sun.max",
        "engine.combustion", "fuelpump", "drop", "flame", "snowflake", "thermometer"
    ]
    
    init(systemName: Binding<String>, location: Binding<String>, iconName: Binding<String>, colorName: Binding<String>) {
        self._systemName = systemName
        self._location = location
        self._iconName = iconName
        self._colorName = colorName
        self._tempLocation = State(initialValue: location.wrappedValue)
    }
    
    var body: some View {
        let editorTitle = String(localized: "editor.system.title", comment: "Title for the system editor")
        let namePlaceholder = String(localized: "editor.system.name_field", comment: "Label for the system name text field")
        let locationPlaceholder = String(localized: "editor.system.location.optional", comment: "Placeholder text shown when no location is specified")

        ItemEditorView(
            title: editorTitle,
            nameFieldLabel: namePlaceholder,
            previewSubtitle: tempLocation.isEmpty ? locationPlaceholder : tempLocation,
            icons: systemIcons,
            name: $systemName,
            iconName: $iconName,
            colorName: $colorName,
            additionalFields: {
                AnyView(
                    TextField(locationPlaceholder, text: $tempLocation)
                        .autocapitalization(.words)
                        .onChange(of: tempLocation) { _, newValue in
                            location = newValue
                        }
                )
            }
        )
        .onAppear {
            tempLocation = location
        }
    }
}

#Preview {
    @Previewable @State var name = "My System"
    @Previewable @State var location = "Main Building"
    @Previewable @State var icon = "building.2"
    @Previewable @State var color = "blue"
    
    return SystemEditorView(systemName: $name, location: $location, iconName: $icon, colorName: $color)
}
