import SwiftUI
import ContactsManager
struct ContactsView: View {
    @State private var isLoading = false
    @State private var contacts: [Contact] = []
    @State private var errorMessage: String?
    
    var body: some View {
        VStack {
            if isLoading {
                ProgressView("Loading contacts...")
            } else if let error = errorMessage {
                Text("Error: \(error)")
                    .foregroundColor(.red)
                Button("Try Again") {
                    checkContactsAccess()
                }
                .padding()
            } else if contacts.isEmpty {
                Text("No contacts found")
                    .foregroundColor(.gray)
            } else {
                List(contacts, id: \.id) { contact in
                    Text(contact.displayName ?? "Unknown")
                }
            }
        }
        .navigationTitle("Contacts")
        .onAppear {
            checkContactsAccess()
        }
        // Show settings alert if needed
        .overlay(ContactsService.shared.settingsAlert)
    }
    
    private func checkContactsAccess() {
        Task {
            let status = ContactsService.shared.contactsAccessStatus
            
            switch status {
            case .notDetermined:
                // Request access
                let granted = await ContactsService.shared.requestContactsAccess()
                if granted {
                    loadContacts()
                } else {
                    errorMessage = "Contacts access denied"
                }
                
            case .authorized:
                // Already have access, load contacts
                loadContacts()
                
            case .denied, .restricted:
                // Access denied or restricted
                errorMessage = "Please grant contacts access in Settings"
            }
        }
    }
    
    private func loadContacts() {
        isLoading = true
        errorMessage = nil
        
        Task {
            do {
                // First ensure contacts are synced
                _ = try await ContactsService.shared.syncContacts()
                
                // Then fetch contacts
                let fetchedContacts = try await ContactsService.shared.fetchContacts(
                    fieldType: .any
                )
                
                DispatchQueue.main.async {
                    self.contacts = fetchedContacts
                    self.isLoading = false
                }
            } catch {
                DispatchQueue.main.async {
                    self.errorMessage = error.localizedDescription
                    self.isLoading = false
                }
            }
        }
    }
}