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 {
                // Background gradient
                LinearGradient(
                    colors: [Color.AppBackground.base, Color.AppBackground.accent],
                    startPoint: .top,
                    endPoint: .bottom
                )
                .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.")
            }
        }
    }
}

// MARK: - Card Page View

private struct CardPageView: View {
    let card: BusinessCard
    
    var body: some View {
        ScrollView {
            VStack(spacing: Design.Spacing.large) {
                BusinessCardView(card: card)
            }
            .padding(.horizontal, Design.Spacing.large)
            .padding(.vertical, Design.Spacing.xLarge)
        }
        .scrollIndicators(.hidden)
    }
}

// MARK: - Empty State

private struct EmptyCardsView: View {
    let onCreateCard: () -> Void
    
    var body: some View {
        VStack(spacing: Design.Spacing.xLarge) {
            Spacer()
            
            Image(systemName: "rectangle.stack.badge.plus")
                .font(.system(size: Design.BaseFontSize.display))
                .foregroundStyle(Color.Text.secondary)
            
            VStack(spacing: Design.Spacing.small) {
                Text("Create your first card")
                    .font(.title2)
                    .bold()
                    .foregroundStyle(Color.Text.primary)
                
                Text("Design and share polished digital business cards for every context.")
                    .font(.subheadline)
                    .foregroundStyle(Color.Text.secondary)
                    .multilineTextAlignment(.center)
            }
            .padding(.horizontal, Design.Spacing.xLarge)
            
            PrimaryActionButton(
                title: String.localized("Create Card"),
                systemImage: "plus"
            ) {
                onCreateCard()
            }
            
            Spacer()
        }
    }
}

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