import SwiftUI
import Bedrock

/// Grid view for selecting contact field types to add
struct ContactFieldPickerView: View {
    var themeColor: Color = Color(red: 0.2, green: 0.2, blue: 0.2)
    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")
                    .typography(.subheading)
                    .foregroundStyle(Color.Text.secondary)
                
                Spacer()
                
                Image(systemName: "plus")
                    .typography(.caption)
                    .foregroundStyle(Color.Text.secondary)
            }
            .padding(.horizontal, Design.Spacing.medium)
            .padding(.vertical, Design.Spacing.small)
            .background(Color.AppBackground.secondary)
            .clipShape(.rect(cornerRadius: Design.CornerRadius.medium))
            
            LazyVGrid(columns: columns, spacing: Design.Spacing.large) {
                ForEach(ContactFieldType.allCases) { fieldType in
                    FieldTypeButton(fieldType: fieldType, themeColor: themeColor) {
                        onSelect(fieldType)
                    }
                }
            }
        }
        .padding(Design.Spacing.large)
        .background(Color.AppBackground.secondary)
        .clipShape(.rect(cornerRadius: Design.CornerRadius.large))
        .overlay(
            RoundedRectangle(cornerRadius: Design.CornerRadius.large)
                .stroke(Color.Text.tertiary.opacity(Design.Opacity.subtle), lineWidth: Design.LineWidth.thin)
        )
    }
}

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

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