package com.tt.honeyDue.ui.components.documents

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Description
import androidx.compose.material.icons.filled.ReceiptLong
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
import com.tt.honeyDue.models.Document
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.testing.AccessibilityIds
import com.tt.honeyDue.ui.subscription.UpgradeFeatureScreen
import com.tt.honeyDue.utils.SubscriptionHelper

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DocumentsTabContent(
    state: ApiResult<List<Document>>,
    filteredDocuments: List<Document> = emptyList(),
    isWarrantyTab: Boolean,
    onDocumentClick: (Int) -> Unit,
    onRetry: () -> Unit,
    onNavigateBack: () -> Unit = {}
) {
    val shouldShowUpgradePrompt = SubscriptionHelper.shouldShowUpgradePromptForDocuments().allowed

    var isRefreshing by remember { mutableStateOf(false) }

    // Handle refresh state
    LaunchedEffect(state) {
        if (state !is ApiResult.Loading) {
            isRefreshing = false
        }
    }

    when (state) {
        is ApiResult.Loading -> {
            if (!isRefreshing) {
                Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                    CircularProgressIndicator()
                }
            }
        }
        is ApiResult.Success -> {
            // Use filteredDocuments if provided, otherwise fall back to state.data
            val documents = if (filteredDocuments.isNotEmpty() || state.data.isEmpty()) filteredDocuments else state.data
            if (documents.isEmpty()) {
                if (shouldShowUpgradePrompt) {
                    // Free tier users see upgrade prompt
                    UpgradeFeatureScreen(
                        triggerKey = "view_documents",
                        icon = if (isWarrantyTab) Icons.Default.ReceiptLong else Icons.Default.Description,
                        onNavigateBack = onNavigateBack
                    )
                } else {
                    // Pro users see empty state
                    EmptyState(
                        modifier = Modifier.testTag(AccessibilityIds.Document.emptyStateView),
                        icon = if (isWarrantyTab) Icons.Default.ReceiptLong else Icons.Default.Description,
                        message = if (isWarrantyTab) "No warranties found" else "No documents found"
                    )
                }
            } else {
                PullToRefreshBox(
                    isRefreshing = isRefreshing,
                    onRefresh = {
                        isRefreshing = true
                        onRetry()
                    },
                    modifier = Modifier.fillMaxSize()
                ) {
                    LazyColumn(
                        modifier = Modifier
                            .fillMaxSize()
                            .testTag(AccessibilityIds.Document.documentsList),
                        contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 96.dp),
                        verticalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        items(documents) { document ->
                            DocumentCard(
                                document = document,
                                isWarrantyCard = isWarrantyTab,
                                onClick = { document.id?.let { onDocumentClick(it) } }
                            )
                        }
                    }
                }
            }
        }
        is ApiResult.Error -> {
            ErrorState(message = state.message, onRetry = onRetry)
        }
        is ApiResult.Idle -> {}
    }
}
