package com.tt.honeyDue.ui.subscription

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.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.tt.honeyDue.data.DataManager
import com.tt.honeyDue.ui.screens.subscription.FeatureComparisonScreen
import com.tt.honeyDue.ui.theme.AppRadius
import com.tt.honeyDue.ui.theme.AppSpacing
import com.tt.honeyDue.utils.SubscriptionProducts

/**
 * Full inline paywall screen for upgrade prompts.
 * Shows feature benefits, subscription products with pricing, and action buttons.
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UpgradeFeatureScreen(
    triggerKey: String,
    icon: ImageVector,
    onNavigateBack: () -> Unit
) {
    var showFeatureComparison by remember { mutableStateOf(false) }
    var isProcessing by remember { mutableStateOf(false) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    var showSuccessAlert by remember { mutableStateOf(false) }

    // 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."
    val buttonText = triggerData?.buttonText ?: "Upgrade to Pro"

    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 (star gradient like iOS)
            Icon(
                imageVector = Icons.Default.Stars,
                contentDescription = null, // decorative
                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)
                ) {
                    FeatureRow(Icons.Default.Home, "Unlimited properties")
                    FeatureRow(Icons.Default.CheckCircle, "Unlimited tasks")
                    FeatureRow(Icons.Default.People, "Contractor management")
                    FeatureRow(Icons.Default.Description, "Document & warranty storage")
                }
            }

            Spacer(Modifier.height(AppSpacing.xl))

            // Subscription Products Section
            // Note: On Android, BillingManager provides real pricing
            // This is a placeholder showing static options
            SubscriptionProductsSection(
                isProcessing = isProcessing,
                onProductSelected = { productId ->
                    // Trigger purchase flow
                    // On Android, this connects to BillingManager
                    isProcessing = true
                    errorMessage = null
                    // Purchase will be handled by platform-specific code
                },
                onRetryLoad = {
                    // Retry loading products
                }
            )

            // Error Message
            errorMessage?.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 = "Warning",
                            tint = MaterialTheme.colorScheme.error
                        )
                        Text(
                            error,
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.error
                        )
                    }
                }
            }

            Spacer(Modifier.height(AppSpacing.lg))

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

            // Restore Purchases
            TextButton(onClick = {
                // Trigger restore purchases
                isProcessing = true
                errorMessage = null
            }) {
                Text(
                    "Restore Purchases",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }

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

        if (showFeatureComparison) {
            // P2 Stream E — replaces the old FeatureComparisonDialog with
            // the full-screen FeatureComparisonScreen. Render as overlay
            // so dismiss returns to this paywall (matches iOS sheet).
            FeatureComparisonScreen(
                onNavigateBack = { showFeatureComparison = false },
                onNavigateToUpgrade = { showFeatureComparison = false },
            )
        }

        if (showSuccessAlert) {
            AlertDialog(
                onDismissRequest = { showSuccessAlert = false },
                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 FeatureRow(icon: ImageVector, text: String) {
    Row(
        horizontalArrangement = Arrangement.spacedBy(AppSpacing.md),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null, // decorative
            modifier = Modifier.size(24.dp),
            tint = MaterialTheme.colorScheme.primary
        )
        Text(
            text,
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

@Composable
private fun SubscriptionProductsSection(
    isProcessing: Boolean,
    onProductSelected: (String) -> Unit,
    onRetryLoad: () -> Unit
) {
    // Static subscription options (pricing will be updated by platform billing)
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = AppSpacing.lg),
        verticalArrangement = Arrangement.spacedBy(AppSpacing.md)
    ) {
        // Monthly Option
        SubscriptionProductCard(
            productId = SubscriptionProducts.MONTHLY,
            name = "honeyDue Pro Monthly",
            price = "$2.99/month",
            description = "Billed monthly",
            savingsBadge = null,
            isSelected = false,
            isProcessing = isProcessing,
            onSelect = { onProductSelected(SubscriptionProducts.MONTHLY) }
        )

        // Annual Option
        SubscriptionProductCard(
            productId = SubscriptionProducts.ANNUAL,
            name = "honeyDue Pro Annual",
            price = "$27.99/year",
            description = "Billed annually",
            savingsBadge = "Save 22%",
            isSelected = false,
            isProcessing = isProcessing,
            onSelect = { onProductSelected(SubscriptionProducts.ANNUAL) }
        )
    }
}

@Composable
private fun SubscriptionProductCard(
    productId: String,
    name: String,
    price: String,
    description: String,
    savingsBadge: String?,
    isSelected: Boolean,
    isProcessing: Boolean,
    onSelect: () -> Unit
) {
    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)
            androidx.compose.foundation.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(
                        name,
                        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(
                    description,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }

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