import SwiftUI
import Bedrock
import SwiftData

struct CardsHomeView: View {
    @Environment(AppState.self) private var appState
    @State private var showingCreateCard = false
    @State private var showingEditCard = false
    @State private var showingDeleteConfirmation = false

    var body: some View {
        @Bindable var cardStore = appState.cardStore
        
        NavigationStack {
            ZStack {
                Color.AppBackground.base
                    .ignoresSafeArea()
                
                if cardStore.cards.isEmpty {
                    EmptyCardsView(onCreateCard: { showingCreateCard = true })
                } else {
                    // Full-screen swipeable cards
                    TabView(selection: $cardStore.selectedCardID) {
                        ForEach(cardStore.cards) { card in
                            CardPageView(card: card)
                                .tag(Optional(card.id))
                        }
                    }
                    .tabViewStyle(.page(indexDisplayMode: .automatic))
                    .indexViewStyle(.page(backgroundDisplayMode: .automatic))
                }
            }
            .navigationTitle(String.localized("My Cards"))
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .topBarLeading) {
                    Button(String.localized("Add Card"), systemImage: "plus") {
                        showingCreateCard = true
                    }
                    .accessibilityHint(String.localized("Create a new business card"))
                }
                
                if cardStore.cards.count > 1 && cardStore.selectedCard != nil {
                    ToolbarItem(placement: .topBarTrailing) {
                        Button(String.localized("Delete"), systemImage: "trash") {
                            showingDeleteConfirmation = true
                        }
                        .accessibilityHint(String.localized("Delete this card"))
                    }
                }
                
                if cardStore.selectedCard != nil {
                    ToolbarItem(placement: .topBarTrailing) {
                        Button(String.localized("Edit"), systemImage: "pencil") {
                            showingEditCard = true
                        }
                        .accessibilityHint(String.localized("Edit this card"))
                    }
                }
            }
            .sheet(isPresented: $showingCreateCard) {
                CardEditorView(card: nil) { newCard in
                    appState.cardStore.addCard(newCard)
                }
            }
            .sheet(isPresented: $showingEditCard) {
                if let card = cardStore.selectedCard {
                    CardEditorView(card: card) { updatedCard in
                        appState.cardStore.updateCard(updatedCard)
                    }
                }
            }
            .alert(String.localized("Delete Card"), isPresented: $showingDeleteConfirmation) {
                Button(String.localized("Cancel"), role: .cancel) { }
                Button(String.localized("Delete"), role: .destructive) {
                    if let card = cardStore.selectedCard {
                        appState.cardStore.deleteCard(card)
                    }
                }
            } message: {
                Text("Are you sure you want to delete this card? This action cannot be undone.")
            }
            .onAppear {
                presentPendingCreateCardFlowIfNeeded()
            }
            .onChange(of: appState.shouldPresentCreateCardFlow) { _, _ in
                presentPendingCreateCardFlowIfNeeded()
            }
        }
    }

    private func presentPendingCreateCardFlowIfNeeded() {
        guard appState.shouldPresentCreateCardFlow else { return }
        appState.shouldPresentCreateCardFlow = false
        showingCreateCard = true
    }
}

#Preview {
    let container = try! ModelContainer(for: BusinessCard.self, Contact.self, AppSettings.self)
    return CardsHomeView()
        .environment(AppState(modelContext: container.mainContext))
}
