import SwiftUI
import ComposeApp

struct DocumentsTabContent: View {
    @ObservedObject var viewModel: DocumentViewModel
    @StateObject private var subscriptionCache = SubscriptionCacheWrapper.shared
    let searchText: String

    var filteredDocuments: [Document] {
        if searchText.isEmpty {
            return viewModel.documents
        }
        return viewModel.documents.filter {
            $0.title.localizedCaseInsensitiveContains(searchText) ||
            ($0.description_ ?? "").localizedCaseInsensitiveContains(searchText)
        }
    }

    var body: some View {
        ListAsyncContentView(
            items: filteredDocuments,
            isLoading: viewModel.isLoading,
            errorMessage: viewModel.errorMessage,
            content: { documents in
                DocumentsListContent(documents: documents)
            },
            emptyContent: {
                if !subscriptionCache.shouldShowUpgradePrompt(currentCount: filteredDocuments.count, limitKey: "documents") {
                    EmptyStateView(
                        icon: "doc",
                        title: L10n.Documents.noDocumentsFound,
                        message: L10n.Documents.noDocumentsMessage
                    )
                } else {
                    UpgradeFeatureView(
                        triggerKey: "view_documents",
                        icon: "doc.text.fill"
                    )
                }
            },
            onRefresh: {
                viewModel.loadDocuments(forceRefresh: true)
                for await loading in viewModel.$isLoading.values {
                    if !loading { break }
                }
            },
            onRetry: {
                viewModel.loadDocuments()
            }
        )
    }
}

// MARK: - Documents List Content

private struct DocumentsListContent: View {
    let documents: [Document]

    var body: some View {
        ScrollView {
            LazyVStack(spacing: AppSpacing.sm) {
                ForEach(documents, id: \.id) { document in
                    NavigationLink(destination: DocumentDetailView(documentId: document.id?.int32Value ?? 0)) {
                        DocumentCard(document: document)
                    }
                    .buttonStyle(PlainButtonStyle())
                }
            }
            .padding(AppSpacing.md)
            .padding(.bottom, AppSpacing.xxxl)
        }
        .safeAreaInset(edge: .bottom) {
            Color.clear.frame(height: 0)
        }
    }
}
