import SwiftUI
import Bedrock

/// Manages all contact, social, and payment fields with a picker-based UI
/// Tap to add opens a sheet, tap on existing field opens edit sheet
struct ContactFieldsManagerView: View {
    @Binding var fields: [AddedContactField]
    
    @State private var selectedFieldTypeForAdd: ContactFieldType?
    @State private var fieldToEdit: AddedContactField?
    
    var body: some View {
        VStack(spacing: Design.Spacing.medium) {
            // Added fields list
            AddedContactFieldsView(fields: $fields) { field in
                fieldToEdit = field
            }
            
            // Field picker grid
            ContactFieldPickerView { fieldType in
                selectedFieldTypeForAdd = fieldType
            }
        }
        .sheet(item: $selectedFieldTypeForAdd) { fieldType in
            ContactFieldEditorSheet(
                fieldType: fieldType,
                initialValue: "",
                initialTitle: fieldType.titleSuggestions.first ?? "",
                onSave: { value, title in
                    addField(fieldType: fieldType, value: value, title: title)
                }
            )
        }
        .sheet(item: $fieldToEdit) { field in
            ContactFieldEditorSheet(
                fieldType: field.fieldType,
                initialValue: field.value,
                initialTitle: field.title,
                onSave: { value, title in
                    updateField(id: field.id, value: value, title: title)
                },
                onDelete: {
                    deleteField(id: field.id)
                }
            )
        }
    }
    
    private func addField(fieldType: ContactFieldType, value: String, title: String) {
        guard !value.isEmpty else { return }
        withAnimation {
            let newField = AddedContactField(
                fieldType: fieldType,
                value: value,
                title: title
            )
            fields.append(newField)
        }
    }
    
    private func updateField(id: UUID, value: String, title: String) {
        if let index = fields.firstIndex(where: { $0.id == id }) {
            withAnimation {
                fields[index].value = value
                fields[index].title = title
            }
        }
    }
    
    private func deleteField(id: UUID) {
        withAnimation {
            fields.removeAll { $0.id == id }
        }
    }
}

#Preview {
    @Previewable @State var fields: [AddedContactField] = [
        AddedContactField(fieldType: .email, value: "matt@example.com", title: "Work"),
        AddedContactField(fieldType: .phone, value: "+1 (555) 123-4567", title: "Cell")
    ]
    
    ScrollView {
        ContactFieldsManagerView(fields: $fields)
    }
    .background(Color.AppBackground.base)
}
