import SwiftUI
import Bedrock

/// Sheet for adding or editing a contact field value
struct ContactFieldEditorSheet: View {
    @Environment(\.dismiss) private var dismiss
    
    private enum ActiveField: Hashable {
        case value
        case title
    }
    
    let fieldType: ContactFieldType
    let initialValue: String
    let initialTitle: String
    let themeColor: Color
    let onSave: (String, String) -> Void
    let onDelete: (() -> Void)?
    
    @State private var value: String
    @State private var title: String
    @State private var postalAddress: PostalAddress
    @FocusState private var activeField: ActiveField?
    
    init(
        fieldType: ContactFieldType,
        initialValue: String = "",
        initialTitle: String = "",
        themeColor: Color = Color(red: 0.2, green: 0.2, blue: 0.2),
        onSave: @escaping (String, String) -> Void,
        onDelete: (() -> Void)? = nil
    ) {
        self.fieldType = fieldType
        self.initialValue = initialValue
        self.initialTitle = initialTitle
        self.themeColor = themeColor
        self.onSave = onSave
        self.onDelete = onDelete
        _value = State(initialValue: initialValue)
        _title = State(initialValue: initialTitle)
        
        // Parse postal address if this is an address field
        if fieldType.id == "address" {
            if let parsed = PostalAddress.decode(from: initialValue), parsed.hasValue {
                _postalAddress = State(initialValue: parsed)
            } else {
                _postalAddress = State(initialValue: PostalAddress())
            }
        } else {
            _postalAddress = State(initialValue: PostalAddress())
        }
    }
    
    private var isAddressField: Bool {
        fieldType.id == "address"
    }
    
    private var isPhoneField: Bool {
        ContactFieldInputRules.shouldFormatAsPhone(fieldType.id)
    }
    
    private var isValid: Bool {
        if isAddressField {
            return postalAddress.hasValue
        }
        return ContactFieldInputRules.isValid(value, for: fieldType.id)
    }
    
    private var isEditing: Bool {
        !initialValue.isEmpty
    }
    
    var body: some View {
        NavigationStack {
            VStack(spacing: 0) {
                // Header with icon
                FieldHeaderView(fieldType: fieldType, themeColor: themeColor)
                
                Divider()
                
                // Form content
                VStack(alignment: .leading, spacing: Design.Spacing.xLarge) {
                    // Value field - different for address vs other fields
                    if isAddressField {
                        AddressEditorView(address: $postalAddress)
                    } else {
                        VStack(alignment: .leading, spacing: Design.Spacing.small) {
                            Text(fieldType.valueLabel)
                                .typography(.subheading)
                                .foregroundStyle(Color.Text.primary)
                            
                            TextField(fieldType.valuePlaceholder, text: $value)
                                .focused($activeField, equals: .value)
                                .keyboardType(fieldType.keyboardType)
                                .textInputAutocapitalization(fieldType.autocapitalization)
                                .textContentType(textContentType)
                                .onChange(of: value) { _, newValue in
                                    guard isPhoneField else { return }
                                    let formatted = PhoneNumberText.formatted(newValue)
                                    if formatted != newValue {
                                        value = formatted
                                    }
                                }
                            
                            if let validationMessage {
                                Text(validationMessage)
                                    .typography(.caption)
                                    .foregroundStyle(Color.Accent.red)
                            }
                            
                            Divider()
                        }
                    }
                    
                    // Title field
                    VStack(alignment: .leading, spacing: Design.Spacing.small) {
                        Text("Title (optional)")
                            .typography(.subheading)
                            .foregroundStyle(Color.Text.primary)
                        
                        TextField(String(localized: "e.g. Work, Personal"), text: $title)
                            .focused($activeField, equals: .title)
                        
                        Divider()
                        
                        // Suggestions
                        if !fieldType.titleSuggestions.isEmpty {
                            VStack(alignment: .leading, spacing: Design.Spacing.small) {
                                Text("Here are some suggestions for your title:")
                                    .typography(.caption)
                                    .foregroundStyle(Color.Text.secondary)
                                
                                FlowLayout(spacing: Design.Spacing.small) {
                                    ForEach(fieldType.titleSuggestions, id: \.self) { suggestion in
                                        SuggestionChip(text: suggestion) {
                                            title = suggestion
                                        }
                                    }
                                }
                            }
                        }
                    }
                    
                    Spacer()
                    
                    // Delete button for editing
                    if isEditing, let onDelete {
                        Button(role: .destructive) {
                            onDelete()
                            dismiss()
                        } label: {
                            HStack {
                                Spacer()
                                Label("Delete Field", systemImage: "trash")
                                Spacer()
                            }
                            .padding(Design.Spacing.medium)
                            .background(Color.Accent.red.opacity(Design.Opacity.subtle))
                            .clipShape(.rect(cornerRadius: Design.CornerRadius.medium))
                        }
                        .buttonStyle(.plain)
                        .foregroundStyle(Color.Accent.red)
                    }
                }
                .padding(Design.Spacing.large)
                .contentShape(.rect)
                .onTapGesture {
                    activeField = nil
                }
            }
            .background(Color.AppBackground.base)
            .navigationTitle(isEditing ? "Edit \(fieldType.displayName)" : "Add \(fieldType.displayName)")
            .navigationBarTitleDisplayMode(.inline)
            .keyboardDismissable()
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button {
                        dismiss()
                    } label: {
                        Image(systemName: "chevron.left")
                    }
                }
                
                ToolbarItem(placement: .confirmationAction) {
                    Button("Save") {
                        if isAddressField {
                            // Save postal address as JSON
                            onSave(postalAddress.encode(), title)
                        } else {
                            let valueToSave = ContactFieldInputRules.normalizedForStorage(value, for: fieldType.id)
                            onSave(valueToSave, title)
                        }
                        dismiss()
                    }
                    .disabled(!isValid)
                }
            }
        }
    }
    
    private var textContentType: UITextContentType? {
        switch fieldType.id {
        case "phone", "whatsapp", "signal": return .telephoneNumber
        case "email": return .emailAddress
        case "website": return .URL
        case "address": return .fullStreetAddress
        default: return nil
        }
    }
    
    private var validationMessage: String? {
        guard !isAddressField else { return nil }
        let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmed.isEmpty else { return nil }
        guard !isValid else { return nil }
        return ContactFieldInputRules.validationMessage(for: fieldType.id)
    }
}

#Preview("Add Email") {
    ContactFieldEditorSheet(fieldType: .email) { value, title in
        Design.debugLog("Saved: \(value), \(title)")
    }
}

#Preview("Edit LinkedIn") {
    ContactFieldEditorSheet(
        fieldType: .linkedIn,
        initialValue: "linkedin.com/in/mattbruce",
        initialTitle: "Connect with me"
    ) { value, title in
        Design.debugLog("Saved: \(value), \(title)")
    } onDelete: {
        Design.debugLog("Deleted")
    }
}

#Preview("Add Address") {
    ContactFieldEditorSheet(fieldType: .address) { value, title in
        Design.debugLog("Saved address: \(value), title: \(title)")
    }
}

#Preview("Edit Address") {
    let existingAddress = PostalAddress(
        street: "6565 Headquarters Dr",
        city: "Plano",
        state: "TX",
        postalCode: "75024"
    )
    
    ContactFieldEditorSheet(
        fieldType: .address,
        initialValue: existingAddress.encode(),
        initialTitle: "Work"
    ) { value, title in
        Design.debugLog("Saved: \(value), title: \(title)")
    } onDelete: {
        Design.debugLog("Deleted")
    }
}
