import SwiftUI
import Bedrock

/// Grid view for selecting contact field types to add
struct ContactFieldPickerView: View {
    let onSelect: (ContactFieldType) -> Void
    
    private let columns = Array(repeating: GridItem(.flexible(), spacing: Design.Spacing.medium), count: 3)
    
    var body: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.medium) {
            HStack {
                Text("Tap a field below to add it")
                    .font(.subheadline)
                    .foregroundStyle(Color.Text.primary)
                
                Spacer()
                
                Image(systemName: "plus")
                    .font(.caption)
                    .foregroundStyle(Color.Text.secondary)
            }
            .padding(.horizontal, Design.Spacing.medium)
            .padding(.vertical, Design.Spacing.small)
            .background(Color.AppBackground.accent)
            .clipShape(.rect(cornerRadius: Design.CornerRadius.medium))
            
            LazyVGrid(columns: columns, spacing: Design.Spacing.large) {
                ForEach(ContactFieldType.allCases) { fieldType in
                    FieldTypeButton(fieldType: fieldType) {
                        onSelect(fieldType)
                    }
                }
            }
        }
        .padding(Design.Spacing.large)
        .background(Color.AppBackground.elevated)
    }
}

private struct FieldTypeButton: View {
    let fieldType: ContactFieldType
    let action: () -> Void
    
    var body: some View {
        Button(action: action) {
            VStack(spacing: Design.Spacing.small) {
                Circle()
                    .fill(fieldType.iconColor)
                    .frame(width: Design.CardSize.avatarSize, height: Design.CardSize.avatarSize)
                    .overlay(
                        fieldType.iconImage()
                            .font(.title3)
                            .foregroundStyle(.white)
                    )
                
                Text(fieldType.displayName)
                    .font(.caption)
                    .foregroundStyle(Color.Text.primary)
                    .multilineTextAlignment(.center)
                    .lineLimit(2)
                    .frame(height: Design.Spacing.xLarge * 2)
            }
        }
        .buttonStyle(.plain)
        .accessibilityLabel(fieldType.displayName)
    }
}

#Preview {
    ContactFieldPickerView { fieldType in
        print("Selected: \(fieldType.displayName)")
    }
}
