package com.tt.honeyDue.ui.screens

import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.tt.honeyDue.testing.AccessibilityIds
import com.tt.honeyDue.ui.support.enableTestTagsAsResourceId
import com.tt.honeyDue.ui.components.documents.DocumentsTabContent
import com.tt.honeyDue.ui.subscription.UpgradeFeatureScreen
import com.tt.honeyDue.utils.SubscriptionHelper
import com.tt.honeyDue.viewmodel.DocumentViewModel
import com.tt.honeyDue.models.*
import com.tt.honeyDue.analytics.PostHogAnalytics
import com.tt.honeyDue.analytics.AnalyticsEvents
import com.tt.honeyDue.ui.theme.*
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.stringResource

enum class DocumentTab {
    WARRANTIES, DOCUMENTS
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DocumentsScreen(
    onNavigateBack: () -> Unit,
    residenceId: Int? = null,
    onNavigateToAddDocument: (residenceId: Int, documentType: String) -> Unit = { _, _ -> },
    onNavigateToDocumentDetail: (documentId: Int) -> Unit = {},
    documentViewModel: DocumentViewModel = viewModel { DocumentViewModel() }
) {
    var selectedTab by remember { mutableStateOf(DocumentTab.WARRANTIES) }
    val documentsState by documentViewModel.documentsState.collectAsStateWithLifecycle()
    // Fallback to DataManager cache so populated snapshots render + first-paint
    // is instant on cached launch. See HomeScreen for the same pattern.
    val dataManager = com.tt.honeyDue.data.LocalDataManager.current
    // Use .collectAsState() (not WithLifecycle) so we get the flow's current
    // value synchronously — in snapshot tests we capture in one frame and
    // can't wait for Lifecycle's async re-emission.
    val cachedDocs by dataManager.documents.collectAsState()
    val effectiveDocs: List<com.tt.honeyDue.models.Document> =
        (documentsState as? com.tt.honeyDue.network.ApiResult.Success)?.data
            ?: cachedDocs.ifEmpty { dataManager.documents.value }

    // Check if screen should be blocked (limit=0). SubscriptionHelper reads
    // the global DataManager singleton so in snapshot tests it always sees the
    // empty free tier even when LocalDataManager is a premium fixture.
    // Derive the blocking flag from LocalDataManager.subscription first; only
    // fall back to the helper when no ambient subscription is present.
    val ambientSubscription by dataManager.subscription.collectAsStateWithLifecycle()
    val isBlocked = if (ambientSubscription != null) {
        val tier = ambientSubscription?.tier?.lowercase()
        val blocked = tier != "pro" && tier != "premium"
        SubscriptionHelper.UsageCheck(
            allowed = blocked,
            triggerKey = if (blocked) "view_documents" else null
        )
    } else SubscriptionHelper.isDocumentsBlocked()
    // Get current count for checking when adding
    val currentCount = effectiveDocs.size

    var selectedCategory by remember { mutableStateOf<String?>(null) }
    var selectedDocType by remember { mutableStateOf<String?>(null) }
    var showActiveOnly by remember { mutableStateOf(true) }
    var showFiltersMenu by remember { mutableStateOf(false) }
    var showUpgradeDialog by remember { mutableStateOf(false) }

    LaunchedEffect(Unit) {
        // Track screen view
        PostHogAnalytics.screen(AnalyticsEvents.DOCUMENTS_SCREEN_SHOWN)
        // Load all documents once - filtering happens client-side
        documentViewModel.loadAllDocuments(residenceId = residenceId)
    }

    // Client-side filtering - no API calls on filter changes
    val filteredDocuments = remember(effectiveDocs, selectedTab, selectedCategory, selectedDocType, showActiveOnly) {
        val allDocuments = effectiveDocs
        allDocuments.filter { document ->
            val matchesTab = if (selectedTab == DocumentTab.WARRANTIES) {
                document.documentType == "warranty"
            } else {
                document.documentType != "warranty"
            }
            val matchesCategory = selectedCategory == null || document.category == selectedCategory
            val matchesDocType = selectedDocType == null || document.documentType == selectedDocType
            val matchesActive = if (selectedTab == DocumentTab.WARRANTIES && showActiveOnly) {
                document.isActive == true
            } else {
                true
            }
            matchesTab && matchesCategory && matchesDocType && matchesActive
        }
    }

    Scaffold(
        modifier = Modifier.enableTestTagsAsResourceId(),
        topBar = {
            Column {
                TopAppBar(
                    title = { Text(stringResource(Res.string.documents_and_warranties), fontWeight = FontWeight.Bold) },
                    navigationIcon = {
                        IconButton(onClick = onNavigateBack) {
                            Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(Res.string.common_back))
                        }
                    },
                    actions = {
                        if (selectedTab == DocumentTab.WARRANTIES) {
                            // Active filter toggle for warranties
                            IconButton(onClick = { showActiveOnly = !showActiveOnly }) {
                                Icon(
                                    if (showActiveOnly) Icons.Default.CheckCircle else Icons.Default.CheckCircleOutline,
                                    stringResource(Res.string.documents_filter_active),
                                    tint = if (showActiveOnly) MaterialTheme.colorScheme.secondary else LocalContentColor.current
                                )
                            }
                        }

                        // Filter menu
                        Box {
                            IconButton(
                                modifier = Modifier.testTag(AccessibilityIds.Common.filterButton),
                                onClick = { showFiltersMenu = true }
                            ) {
                                Icon(
                                    Icons.Default.FilterList,
                                    stringResource(Res.string.documents_filters),
                                    tint = if (selectedCategory != null || selectedDocType != null)
                                        MaterialTheme.colorScheme.primary else LocalContentColor.current
                                )
                            }

                            DropdownMenu(
                                expanded = showFiltersMenu,
                                onDismissRequest = { showFiltersMenu = false }
                            ) {
                                if (selectedTab == DocumentTab.WARRANTIES) {
                                    DropdownMenuItem(
                                        text = { Text(stringResource(Res.string.documents_all_categories)) },
                                        onClick = {
                                            selectedCategory = null
                                            showFiltersMenu = false
                                        }
                                    )
                                    OrganicDivider()
                                    DocumentCategory.values().forEach { category ->
                                        DropdownMenuItem(
                                            text = { Text(category.displayName) },
                                            onClick = {
                                                selectedCategory = category.value
                                                showFiltersMenu = false
                                            }
                                        )
                                    }
                                } else {
                                    DropdownMenuItem(
                                        text = { Text(stringResource(Res.string.documents_all_types)) },
                                        onClick = {
                                            selectedDocType = null
                                            showFiltersMenu = false
                                        }
                                    )
                                    OrganicDivider()
                                    DocumentType.values().forEach { type ->
                                        DropdownMenuItem(
                                            text = { Text(type.displayName) },
                                            onClick = {
                                                selectedDocType = type.value
                                                showFiltersMenu = false
                                            }
                                        )
                                    }
                                }
                            }
                        }
                    }
                )

                // Tabs
                TabRow(selectedTabIndex = selectedTab.ordinal) {
                    Tab(
                        selected = selectedTab == DocumentTab.WARRANTIES,
                        onClick = { selectedTab = DocumentTab.WARRANTIES },
                        text = { Text(stringResource(Res.string.documents_warranties_tab)) },
                        icon = { Icon(Icons.Default.VerifiedUser, null) }
                    )
                    Tab(
                        selected = selectedTab == DocumentTab.DOCUMENTS,
                        onClick = { selectedTab = DocumentTab.DOCUMENTS },
                        text = { Text(stringResource(Res.string.documents_documents_tab)) },
                        icon = { Icon(Icons.Default.Description, null) }
                    )
                }
            }
        },
        floatingActionButton = {
            // Don't show FAB if screen is blocked (limit=0)
            if (!isBlocked.allowed) {
                Box(modifier = Modifier.padding(bottom = 80.dp)) {
                    FloatingActionButton(
                        modifier = Modifier.testTag(AccessibilityIds.Document.addButton),
                        onClick = {
                            // Check if user can add based on current count
                            val canAdd = SubscriptionHelper.canAddDocument(currentCount)
                            if (canAdd.allowed) {
                                val documentType = if (selectedTab == DocumentTab.WARRANTIES) "warranty" else "other"
                                // Pass residenceId even if null - AddDocumentScreen will handle it
                                onNavigateToAddDocument(residenceId ?: -1, documentType)
                            } else {
                                PostHogAnalytics.capture(
                                    AnalyticsEvents.DOCUMENTS_PAYWALL_SHOWN,
                                    mapOf("current_count" to currentCount)
                                )
                                showUpgradeDialog = true
                            }
                        },
                        containerColor = MaterialTheme.colorScheme.primary
                    ) {
                        Icon(Icons.Default.Add, stringResource(Res.string.documents_add_button))
                    }
                }
            }
        }
    ) { padding ->
        WarmGradientBackground {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(padding)
            ) {
                if (isBlocked.allowed) {
                    // Screen is blocked (limit=0) - show upgrade prompt
                    UpgradeFeatureScreen(
                        triggerKey = isBlocked.triggerKey ?: "view_documents",
                        icon = Icons.Default.Description,
                        onNavigateBack = onNavigateBack
                    )
                } else {
                    // Pro users see normal content - use client-side filtered documents
                    DocumentsTabContent(
                        // Always prefer fixture/cached documents when available — VM state
                        // may be Error (no network in test) even when DataManager has real data.
                        state = if (cachedDocs.isNotEmpty())
                            com.tt.honeyDue.network.ApiResult.Success(cachedDocs)
                        else if (documentsState is com.tt.honeyDue.network.ApiResult.Loading)
                            documentsState
                        else if (documentsState is com.tt.honeyDue.network.ApiResult.Success)
                            documentsState
                        else
                            com.tt.honeyDue.network.ApiResult.Success(emptyList()),
                        filteredDocuments = filteredDocuments,
                        isWarrantyTab = selectedTab == DocumentTab.WARRANTIES,
                        onDocumentClick = onNavigateToDocumentDetail,
                        onRetry = {
                            // Reload all documents on pull-to-refresh
                            documentViewModel.loadAllDocuments(residenceId = residenceId)
                        },
                        onNavigateBack = onNavigateBack
                    )
                }
            }
        }
    }

    // Show upgrade dialog when user hits limit
    if (showUpgradeDialog) {
        AlertDialog(
            onDismissRequest = { showUpgradeDialog = false },
            title = { Text(stringResource(Res.string.documents_upgrade_required)) },
            text = {
                Text(stringResource(Res.string.documents_upgrade_message))
            },
            confirmButton = {
                TextButton(onClick = { showUpgradeDialog = false }) {
                    Text(stringResource(Res.string.common_ok))
                }
            }
        )
    }
}
