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()
            }
        }
    }
}

private struct EmptyContactsView: View {
    var body: some View {
        VStack(spacing: Design.Spacing.large) {
            Image(systemName: "person.2.slash")
                .font(.system(size: Design.BaseFontSize.display))
                .foregroundStyle(Color.Text.secondary)
            
            Text("No contacts yet")
                .font(.headline)
                .foregroundStyle(Color.Text.primary)
            
            Text("Tap + to add a contact, scan a QR code, or track who you share your card with.")
                .font(.subheadline)
                .foregroundStyle(Color.Text.secondary)
                .multilineTextAlignment(.center)
                .padding(.horizontal, Design.Spacing.xLarge)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.AppBackground.base)
    }
}

private struct ContactsListView: View {
    @Bindable var contactsStore: ContactsStore
    
    var body: some View {
        List {
            // Follow-up reminders section
            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)
                }
            }
            
            // Received cards section
            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")
                }
            }
            
            // Shared with section
            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")
                        .font(.headline)
                        .bold()
                }
            }
        }
        .listStyle(.plain)
        .navigationDestination(for: Contact.self) { contact in
            ContactDetailView(contact: contact)
        }
    }
}

private struct ContactRowView: View {
    let contact: Contact
    let relativeDate: String

    var body: some View {
        HStack(spacing: Design.Spacing.medium) {
            ContactAvatarView(contact: contact)

            VStack(alignment: .leading, spacing: Design.Spacing.xxSmall) {
                HStack(spacing: Design.Spacing.xSmall) {
                    Text(contact.name)
                        .font(.headline)
                        .foregroundStyle(Color.Text.primary)
                    
                    if contact.isReceivedCard {
                        Image(systemName: "arrow.down.circle.fill")
                            .font(.caption)
                            .foregroundStyle(Color.Accent.mint)
                    }
                    
                    if contact.hasFollowUp {
                        Image(systemName: contact.isFollowUpOverdue ? "exclamationmark.circle.fill" : "clock.fill")
                            .font(.caption)
                            .foregroundStyle(contact.isFollowUpOverdue ? Color.Accent.red : Color.Accent.gold)
                    }
                }
                
                if !contact.role.isEmpty || !contact.company.isEmpty {
                    Text("\(contact.role)\(contact.role.isEmpty || contact.company.isEmpty ? "" : " · ")\(contact.company)")
                        .font(.subheadline)
                        .foregroundStyle(Color.Text.secondary)
                        .lineLimit(1)
                }
                
                if !contact.tagList.isEmpty {
                    HStack(spacing: Design.Spacing.xSmall) {
                        ForEach(contact.tagList.prefix(2), id: \.self) { tag in
                            Text(tag)
                                .font(.caption2)
                                .padding(.horizontal, Design.Spacing.xSmall)
                                .padding(.vertical, Design.Spacing.xxSmall)
                                .background(Color.AppBackground.accent)
                                .clipShape(.rect(cornerRadius: Design.CornerRadius.small))
                        }
                    }
                }
            }

            Spacer()

            VStack(alignment: .trailing, spacing: Design.Spacing.xxSmall) {
                Text(relativeDate)
                    .font(.caption)
                    .foregroundStyle(Color.Text.secondary)
                Text(String.localized(contact.cardLabel))
                    .font(.caption)
                    .padding(.horizontal, Design.Spacing.small)
                    .padding(.vertical, Design.Spacing.xxSmall)
                    .background(Color.AppBackground.base)
                    .clipShape(.rect(cornerRadius: Design.CornerRadius.medium))
            }
        }
        .accessibilityElement(children: .ignore)
        .accessibilityLabel(contact.name)
        .accessibilityValue("\(contact.role), \(contact.company)")
    }
}

private struct ContactAvatarView: View {
    let contact: Contact
    
    var body: some View {
        if let photoData = contact.photoData, let uiImage = UIImage(data: photoData) {
            Image(uiImage: uiImage)
                .resizable()
                .scaledToFill()
                .frame(width: Design.CardSize.avatarSize, height: Design.CardSize.avatarSize)
                .clipShape(.rect(cornerRadius: Design.CornerRadius.medium))
        } else {
            Image(systemName: contact.avatarSystemName)
                .font(.title2)
                .foregroundStyle(Color.Accent.red)
                .frame(width: Design.CardSize.avatarSize, height: Design.CardSize.avatarSize)
                .background(Color.AppBackground.accent)
                .clipShape(.rect(cornerRadius: Design.CornerRadius.medium))
        }
    }
}

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