import SwiftUI
import Bedrock
import SwiftData

struct ContactsView: View {
    @Environment(AppState.self) private var appState
    @State private var showingScanner = false
    @State private var showingAddContact = false

    var body: some View {
        @Bindable var contactsStore = appState.contactsStore
        NavigationStack {
            Group {
                if contactsStore.contacts.isEmpty {
                    EmptyContactsView()
                } else {
                    ContactsListView(contactsStore: contactsStore)
                }
            }
            .searchable(text: $contactsStore.searchQuery, prompt: String.localized("Search contacts"))
            .navigationTitle(String.localized("Contacts"))
            .toolbar {
                ToolbarItem(placement: .primaryAction) {
                    Button(String.localized("Scan Card"), systemImage: "qrcode.viewfinder") {
                        showingScanner = true
                    }
                    .accessibilityHint(String.localized("Scan someone else's QR code to save their card"))
                }
                
                ToolbarItem(placement: .primaryAction) {
                    Button(String.localized("Add Contact"), systemImage: "plus") {
                        showingAddContact = true
                    }
                    .accessibilityHint(String.localized("Manually add a new contact"))
                }
            }
            .sheet(isPresented: $showingScanner) {
                QRScannerView { scannedData in
                    if !scannedData.isEmpty {
                        appState.contactsStore.addReceivedCard(vCardData: scannedData)
                    }
                    showingScanner = false
                }
            }
            .sheet(isPresented: $showingAddContact) {
                AddContactSheet()
            }
        }
    }
}

#Preview {
    ContactsView()
        .environment(AppState(modelContext: try! ModelContainer(for: BusinessCard.self, Contact.self, AppSettings.self).mainContext))
}
