package com.tt.honeyDue.ui.subscription

import android.app.Activity
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
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.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.android.billingclient.api.ProductDetails
import com.tt.honeyDue.data.DataManager
import com.tt.honeyDue.ui.screens.subscription.FeatureComparisonScreen
import com.tt.honeyDue.platform.BillingManager
import com.tt.honeyDue.ui.theme.AppSpacing
import kotlinx.coroutines.launch

/**
 * Android-specific upgrade screen that connects to Google Play Billing.
 * This version shows real product pricing from Google Play Console.
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UpgradeFeatureScreenAndroid(
    triggerKey: String,
    icon: ImageVector,
    billingManager: BillingManager,
    onNavigateBack: () -> Unit
) {
    val context = LocalContext.current
    val activity = context as? Activity
    val scope = rememberCoroutineScope()

    var showFeatureComparison by remember { mutableStateOf(false) }
    var selectedProductId by remember { mutableStateOf<String?>(null) }
    var showSuccessAlert by remember { mutableStateOf(false) }

    // Observe billing manager state
    val isLoading by billingManager.isLoading.collectAsState()
    val products by billingManager.products.collectAsState()
    val purchaseError by billingManager.purchaseError.collectAsState()
    val purchasedProductIDs by billingManager.purchasedProductIDs.collectAsState()

    // Look up trigger data from cache
    val triggerData by remember { derivedStateOf {
        DataManager.upgradeTriggers.value[triggerKey]
    } }

    // Fallback values if trigger not found
    val title = triggerData?.title ?: "Upgrade Required"
    val message = triggerData?.message ?: "This feature is available with a Pro subscription."

    // Load products on launch
    LaunchedEffect(Unit) {
        billingManager.loadProducts()
    }

    // Check for successful purchase
    LaunchedEffect(purchasedProductIDs) {
        if (purchasedProductIDs.isNotEmpty()) {
            showSuccessAlert = true
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(title, fontWeight = FontWeight.SemiBold) },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.surface
                )
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .verticalScroll(rememberScrollState()),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Spacer(Modifier.height(AppSpacing.xl))

            // Feature Icon
            Icon(
                imageVector = Icons.Default.Stars,
                contentDescription = null,
                modifier = Modifier.size(80.dp),
                tint = MaterialTheme.colorScheme.tertiary
            )

            Spacer(Modifier.height(AppSpacing.lg))

            // Title
            Text(
                title,
                style = MaterialTheme.typography.headlineMedium,
                fontWeight = FontWeight.Bold,
                textAlign = TextAlign.Center,
                modifier = Modifier.padding(horizontal = AppSpacing.lg)
            )

            Spacer(Modifier.height(AppSpacing.md))

            // Description
            Text(
                message,
                style = MaterialTheme.typography.bodyLarge,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                textAlign = TextAlign.Center,
                modifier = Modifier.padding(horizontal = AppSpacing.lg)
            )

            Spacer(Modifier.height(AppSpacing.xl))

            // Pro Features Preview Card
            Surface(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = AppSpacing.lg),
                shape = MaterialTheme.shapes.large,
                color = MaterialTheme.colorScheme.surfaceVariant
            ) {
                Column(
                    modifier = Modifier.padding(AppSpacing.lg),
                    verticalArrangement = Arrangement.spacedBy(AppSpacing.md)
                ) {
                    FeatureRowAndroid(Icons.Default.Home, "Unlimited properties")
                    FeatureRowAndroid(Icons.Default.CheckCircle, "Unlimited tasks")
                    FeatureRowAndroid(Icons.Default.People, "Contractor management")
                    FeatureRowAndroid(Icons.Default.Description, "Document & warranty storage")
                }
            }

            Spacer(Modifier.height(AppSpacing.xl))

            // Subscription Products Section
            if (isLoading && products.isEmpty()) {
                CircularProgressIndicator(
                    modifier = Modifier.padding(AppSpacing.lg),
                    color = MaterialTheme.colorScheme.primary
                )
            } else if (products.isNotEmpty()) {
                // Calculate savings for annual
                val monthlyProduct = billingManager.getMonthlyProduct()
                val annualProduct = billingManager.getAnnualProduct()
                val annualSavings = billingManager.calculateAnnualSavings(monthlyProduct, annualProduct)

                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = AppSpacing.lg),
                    verticalArrangement = Arrangement.spacedBy(AppSpacing.md)
                ) {
                    products.forEach { product ->
                        val isAnnual = product.productId.contains("annual")
                        val savingsBadge = if (isAnnual && annualSavings != null) {
                            "Save $annualSavings%"
                        } else null

                        SubscriptionProductCardAndroid(
                            productDetails = product,
                            formattedPrice = billingManager.getFormattedPrice(product) ?: "Loading...",
                            savingsBadge = savingsBadge,
                            isSelected = selectedProductId == product.productId,
                            isProcessing = isLoading && selectedProductId == product.productId,
                            onSelect = {
                                selectedProductId = product.productId
                                activity?.let { act ->
                                    billingManager.launchPurchaseFlow(
                                        activity = act,
                                        productDetails = product,
                                        onSuccess = { showSuccessAlert = true },
                                        onError = { /* Error shown via purchaseError flow */ }
                                    )
                                }
                            }
                        )
                    }
                }
            } else {
                // Fallback if no products loaded
                Button(
                    onClick = {
                        scope.launch {
                            billingManager.loadProducts()
                        }
                    },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = AppSpacing.lg)
                ) {
                    Text("Retry Loading Products")
                }
            }

            // Error Message
            purchaseError?.let { error ->
                Spacer(Modifier.height(AppSpacing.md))
                Surface(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = AppSpacing.lg),
                    shape = MaterialTheme.shapes.medium,
                    color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.3f)
                ) {
                    Row(
                        modifier = Modifier.padding(AppSpacing.md),
                        horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            Icons.Default.Warning,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.error
                        )
                        Text(
                            error,
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.error,
                            modifier = Modifier.weight(1f)
                        )
                        IconButton(
                            onClick = { billingManager.clearError() },
                            modifier = Modifier.size(24.dp)
                        ) {
                            Icon(
                                Icons.Default.Close,
                                contentDescription = "Dismiss",
                                modifier = Modifier.size(16.dp)
                            )
                        }
                    }
                }
            }

            Spacer(Modifier.height(AppSpacing.lg))

            // Compare Plans
            TextButton(onClick = { showFeatureComparison = true }) {
                Text("Compare Free vs Pro")
            }

            // Restore Purchases
            TextButton(onClick = {
                scope.launch {
                    val restored = billingManager.restorePurchases()
                    if (restored) {
                        showSuccessAlert = true
                    }
                }
            }) {
                Text(
                    "Restore Purchases",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }

            Spacer(Modifier.height(AppSpacing.xl * 2))
        }

        if (showFeatureComparison) {
            // P2 Stream E — replaces FeatureComparisonDialog with the
            // shared full-screen FeatureComparisonScreen.
            FeatureComparisonScreen(
                onNavigateBack = { showFeatureComparison = false },
                onNavigateToUpgrade = {
                    showFeatureComparison = false
                    products.firstOrNull()?.let { product ->
                        selectedProductId = product.productId
                        activity?.let { act ->
                            billingManager.launchPurchaseFlow(
                                activity = act,
                                productDetails = product,
                                onSuccess = { showSuccessAlert = true },
                                onError = { }
                            )
                        }
                    }
                },
            )
        }

        if (showSuccessAlert) {
            AlertDialog(
                onDismissRequest = {
                    showSuccessAlert = false
                    onNavigateBack()
                },
                title = { Text("Subscription Active") },
                text = { Text("You now have full access to all Pro features!") },
                confirmButton = {
                    TextButton(onClick = {
                        showSuccessAlert = false
                        onNavigateBack()
                    }) {
                        Text("Done")
                    }
                }
            )
        }
    }
}

@Composable
private fun FeatureRowAndroid(icon: ImageVector, text: String) {
    Row(
        horizontalArrangement = Arrangement.spacedBy(AppSpacing.md),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            modifier = Modifier.size(24.dp),
            tint = MaterialTheme.colorScheme.primary
        )
        Text(
            text,
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

@Composable
private fun SubscriptionProductCardAndroid(
    productDetails: ProductDetails,
    formattedPrice: String,
    savingsBadge: String?,
    isSelected: Boolean,
    isProcessing: Boolean,
    onSelect: () -> Unit
) {
    val isAnnual = productDetails.productId.contains("annual")
    val productName = if (isAnnual) "honeyDue Pro Annual" else "honeyDue Pro Monthly"
    val billingPeriod = if (isAnnual) "Billed annually" else "Billed monthly"

    Card(
        onClick = onSelect,
        modifier = Modifier.fillMaxWidth(),
        shape = MaterialTheme.shapes.medium,
        colors = CardDefaults.cardColors(
            containerColor = if (isSelected)
                MaterialTheme.colorScheme.primaryContainer
            else
                MaterialTheme.colorScheme.surface
        ),
        border = if (isSelected)
            BorderStroke(2.dp, MaterialTheme.colorScheme.primary)
        else
            null
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(AppSpacing.lg),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(modifier = Modifier.weight(1f)) {
                Row(
                    horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        productName,
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.SemiBold
                    )
                    savingsBadge?.let { badge ->
                        Surface(
                            shape = MaterialTheme.shapes.small,
                            color = MaterialTheme.colorScheme.tertiaryContainer
                        ) {
                            Text(
                                badge,
                                modifier = Modifier.padding(
                                    horizontal = AppSpacing.sm,
                                    vertical = 2.dp
                                ),
                                style = MaterialTheme.typography.labelSmall,
                                color = MaterialTheme.colorScheme.tertiary,
                                fontWeight = FontWeight.Bold
                            )
                        }
                    }
                }
                Text(
                    billingPeriod,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }

            if (isProcessing) {
                CircularProgressIndicator(
                    modifier = Modifier.size(24.dp),
                    strokeWidth = 2.dp
                )
            } else {
                Text(
                    formattedPrice,
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.primary
                )
            }
        }
    }
}
