import SwiftUI
import ComposeApp

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

    var filteredWarranties: [Document] {
        let warranties = viewModel.documents.filter { $0.documentType == "warranty" }
        if searchText.isEmpty {
            return warranties
        }
        return warranties.filter {
            $0.title.localizedCaseInsensitiveContains(searchText) ||
            ($0.itemName ?? "").localizedCaseInsensitiveContains(searchText) ||
            ($0.provider ?? "").localizedCaseInsensitiveContains(searchText)
        }
    }

    var body: some View {
        ListAsyncContentView(
            items: filteredWarranties,
            isLoading: viewModel.isLoading,
            errorMessage: viewModel.errorMessage,
            content: { warranties in
                WarrantiesListContent(warranties: warranties)
            },
            emptyContent: {
                if !subscriptionCache.shouldShowUpgradePrompt(currentCount: filteredWarranties.count, limitKey: "documents") {
                    EmptyStateView(
                        icon: "doc.text.viewfinder",
                        title: L10n.Documents.noWarrantiesFound,
                        message: L10n.Documents.noWarrantiesMessage
                    )
                } 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: - Warranties List Content

private struct WarrantiesListContent: View {
    let warranties: [Document]

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