import SwiftUI
import Bedrock

struct ContactsListView: View {
    @Bindable var contactsStore: ContactsStore

    var body: some View {
        List {
            let overdueContacts = contactsStore.visibleContacts.filter { $0.isFollowUpOverdue }
            if !overdueContacts.isEmpty {
                Section {
                    ForEach(overdueContacts) { contact in
                        NavigationLink(value: contact) {
                            ContactRowView(contact: contact, relativeDate: contactsStore.relativeShareDate(for: contact))
                        }
                    }
                } header: {
                    Label(String.localized("Follow-up Overdue"), systemImage: "exclamationmark.circle")
                        .foregroundStyle(Color.Accent.red)
                }
            }

            let receivedCards = contactsStore.visibleContacts.filter { $0.isReceivedCard && !$0.isFollowUpOverdue }
            if !receivedCards.isEmpty {
                Section {
                    ForEach(receivedCards) { contact in
                        NavigationLink(value: contact) {
                            ContactRowView(contact: contact, relativeDate: contactsStore.relativeShareDate(for: contact))
                        }
                    }
                    .onDelete { indexSet in
                        for index in indexSet {
                            contactsStore.deleteContact(receivedCards[index])
                        }
                    }
                } header: {
                    Label(String.localized("Received Cards"), systemImage: "tray.and.arrow.down")
                }
            }

            let sharedContacts = contactsStore.visibleContacts.filter { !$0.isReceivedCard && !$0.isFollowUpOverdue }
            if !sharedContacts.isEmpty {
                Section {
                    ForEach(sharedContacts) { contact in
                        NavigationLink(value: contact) {
                            ContactRowView(contact: contact, relativeDate: contactsStore.relativeShareDate(for: contact))
                        }
                    }
                    .onDelete { indexSet in
                        for index in indexSet {
                            contactsStore.deleteContact(sharedContacts[index])
                        }
                    }
                } header: {
                    Text("Shared With")
                        .typography(.heading)
                        .bold()
                }
            }
        }
        .listStyle(.plain)
        .navigationDestination(for: Contact.self) { contact in
            ContactDetailView(contact: contact)
        }
    }
}
