package com.tt.honeyDue.ui.subscription

import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
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 honeydue.composeapp.generated.resources.*
import com.tt.honeyDue.data.DataManager
import com.tt.honeyDue.ui.theme.AppRadius
import com.tt.honeyDue.ui.theme.AppSpacing
import com.tt.honeyDue.utils.SubscriptionProducts
import org.jetbrains.compose.resources.stringResource

/**
 * Full-screen upgrade experience matching iOS UpgradeFeatureView.
 *
 * Features:
 * - Hero section with gradient
 * - Plan selection (Monthly/Yearly)
 * - Feature comparison
 * - Purchase button with loading state
 * - Restore purchases option
 * - Terms and conditions
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UpgradeScreen(
    onNavigateBack: () -> Unit,
    onPurchase: (planId: String) -> Unit,
    onRestorePurchases: () -> Unit
) {
    var selectedPlan by remember { mutableStateOf(PlanType.YEARLY) }
    var isPurchasing by remember { mutableStateOf(false) }
    var isRestoring by remember { mutableStateOf(false) }

    val featureBenefits = DataManager.featureBenefits.value

    Scaffold(
        topBar = {
            TopAppBar(
                title = {},
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.Default.Close, contentDescription = "Close")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color.Transparent
                )
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .verticalScroll(rememberScrollState())
        ) {
            // Hero Section
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(
                        Brush.verticalGradient(
                            colors = listOf(
                                MaterialTheme.colorScheme.primaryContainer,
                                MaterialTheme.colorScheme.background
                            )
                        )
                    )
                    .padding(AppSpacing.xl),
                contentAlignment = Alignment.Center
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.spacedBy(AppSpacing.md)
                ) {
                    // Crown Icon
                    Box(
                        modifier = Modifier
                            .size(80.dp)
                            .clip(CircleShape)
                            .background(MaterialTheme.colorScheme.primary),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            Icons.Default.Stars,
                            contentDescription = null, // decorative
                            modifier = Modifier.size(48.dp),
                            tint = MaterialTheme.colorScheme.onPrimary
                        )
                    }

                    Text(
                        text = "Upgrade to Pro",
                        style = MaterialTheme.typography.headlineMedium,
                        fontWeight = FontWeight.Bold
                    )

                    Text(
                        text = "Unlock the full potential of honeyDue",
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        textAlign = TextAlign.Center
                    )
                }
            }

            Spacer(modifier = Modifier.height(AppSpacing.lg))

            // Plan Selection
            Column(
                modifier = Modifier.padding(horizontal = AppSpacing.lg),
                verticalArrangement = Arrangement.spacedBy(AppSpacing.md)
            ) {
                Text(
                    text = "Choose Your Plan",
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.SemiBold
                )

                // Yearly Plan (Recommended)
                PlanCard(
                    title = "Yearly",
                    price = "$29.99/year",
                    savings = "Save 50%",
                    isSelected = selectedPlan == PlanType.YEARLY,
                    isRecommended = true,
                    onClick = { selectedPlan = PlanType.YEARLY }
                )

                // Monthly Plan
                PlanCard(
                    title = "Monthly",
                    price = "$4.99/month",
                    savings = null,
                    isSelected = selectedPlan == PlanType.MONTHLY,
                    isRecommended = false,
                    onClick = { selectedPlan = PlanType.MONTHLY }
                )
            }

            Spacer(modifier = Modifier.height(AppSpacing.xl))

            // Features Section
            Column(
                modifier = Modifier.padding(horizontal = AppSpacing.lg),
                verticalArrangement = Arrangement.spacedBy(AppSpacing.md)
            ) {
                Text(
                    text = "What's Included",
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.SemiBold
                )

                FeatureItem(
                    icon = Icons.Default.Home,
                    title = "Unlimited Properties",
                    description = "Track maintenance for all your homes"
                )

                FeatureItem(
                    icon = Icons.Default.CheckCircle,
                    title = "Unlimited Tasks",
                    description = "Never forget a maintenance task again"
                )

                FeatureItem(
                    icon = Icons.Default.People,
                    title = "Contractor Management",
                    description = "Save and rate your trusted contractors"
                )

                FeatureItem(
                    icon = Icons.Default.Description,
                    title = "Document Vault",
                    description = "Store warranties, receipts, and manuals"
                )

                FeatureItem(
                    icon = Icons.Default.Share,
                    title = "Family Sharing",
                    description = "Invite family members to collaborate"
                )

                FeatureItem(
                    icon = Icons.Default.Notifications,
                    title = "Smart Reminders",
                    description = "Get notified when tasks are due"
                )
            }

            Spacer(modifier = Modifier.height(AppSpacing.xl))

            // Purchase Button
            Button(
                onClick = {
                    isPurchasing = true
                    val planId = if (selectedPlan == PlanType.YEARLY) SubscriptionProducts.ANNUAL else SubscriptionProducts.MONTHLY
                    onPurchase(planId)
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = AppSpacing.lg)
                    .height(56.dp),
                enabled = !isPurchasing && !isRestoring,
                shape = RoundedCornerShape(AppRadius.md)
            ) {
                if (isPurchasing) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(24.dp),
                        color = MaterialTheme.colorScheme.onPrimary,
                        strokeWidth = 2.dp
                    )
                } else {
                    Text(
                        text = "Subscribe Now",
                        fontWeight = FontWeight.Bold,
                        style = MaterialTheme.typography.titleMedium
                    )
                }
            }

            // Restore Purchases
            TextButton(
                onClick = {
                    isRestoring = true
                    onRestorePurchases()
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = AppSpacing.lg),
                enabled = !isPurchasing && !isRestoring
            ) {
                if (isRestoring) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(20.dp),
                        strokeWidth = 2.dp
                    )
                    Spacer(modifier = Modifier.width(AppSpacing.sm))
                }
                Text("Restore Purchases")
            }

            // Terms
            Text(
                text = "Subscription automatically renews unless cancelled at least 24 hours before the end of the current period. Manage subscriptions in your device settings.",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                textAlign = TextAlign.Center,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = AppSpacing.xl, vertical = AppSpacing.md)
            )

            // Terms Links
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = AppSpacing.xl),
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                TextButton(onClick = { /* Open terms */ }) {
                    Text(
                        "Terms of Use",
                        style = MaterialTheme.typography.bodySmall
                    )
                }
                Text(
                    " • ",
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                TextButton(onClick = { /* Open privacy */ }) {
                    Text(
                        "Privacy Policy",
                        style = MaterialTheme.typography.bodySmall
                    )
                }
            }
        }
    }
}

private enum class PlanType {
    MONTHLY, YEARLY
}

@Composable
private fun PlanCard(
    title: String,
    price: String,
    savings: String?,
    isSelected: Boolean,
    isRecommended: Boolean,
    onClick: () -> Unit
) {
    val borderColor by animateColorAsState(
        targetValue = if (isSelected) MaterialTheme.colorScheme.primary
                      else MaterialTheme.colorScheme.outline.copy(alpha = 0.3f),
        label = "borderColor"
    )

    val backgroundColor by animateColorAsState(
        targetValue = if (isSelected) MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.3f)
                      else MaterialTheme.colorScheme.surface,
        label = "backgroundColor"
    )

    Card(
        modifier = Modifier
            .fillMaxWidth()
            .border(
                width = if (isSelected) 2.dp else 1.dp,
                color = borderColor,
                shape = RoundedCornerShape(AppRadius.lg)
            )
            .clickable(onClick = onClick),
        shape = RoundedCornerShape(AppRadius.lg),
        colors = CardDefaults.cardColors(
            containerColor = backgroundColor
        )
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(AppSpacing.lg),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(AppSpacing.md)
            ) {
                // Radio button
                RadioButton(
                    selected = isSelected,
                    onClick = onClick,
                    colors = RadioButtonDefaults.colors(
                        selectedColor = MaterialTheme.colorScheme.primary
                    )
                )

                Column {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm)
                    ) {
                        Text(
                            text = title,
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.SemiBold
                        )
                        if (isRecommended) {
                            Surface(
                                shape = RoundedCornerShape(AppRadius.xs),
                                color = MaterialTheme.colorScheme.primary
                            ) {
                                Text(
                                    text = "BEST VALUE",
                                    style = MaterialTheme.typography.labelSmall,
                                    color = MaterialTheme.colorScheme.onPrimary,
                                    modifier = Modifier.padding(horizontal = AppSpacing.sm, vertical = 2.dp)
                                )
                            }
                        }
                    }

                    Text(
                        text = price,
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }

            savings?.let {
                Surface(
                    shape = RoundedCornerShape(AppRadius.sm),
                    color = MaterialTheme.colorScheme.tertiaryContainer
                ) {
                    Text(
                        text = it,
                        style = MaterialTheme.typography.labelMedium,
                        color = MaterialTheme.colorScheme.onTertiaryContainer,
                        fontWeight = FontWeight.SemiBold,
                        modifier = Modifier.padding(horizontal = AppSpacing.md, vertical = AppSpacing.xs)
                    )
                }
            }
        }
    }
}

@Composable
private fun FeatureItem(
    icon: ImageVector,
    title: String,
    description: String
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(AppSpacing.md),
        verticalAlignment = Alignment.Top
    ) {
        Box(
            modifier = Modifier
                .size(40.dp)
                .clip(CircleShape)
                .background(MaterialTheme.colorScheme.primaryContainer),
            contentAlignment = Alignment.Center
        ) {
            Icon(
                icon,
                contentDescription = null, // decorative
                modifier = Modifier.size(20.dp),
                tint = MaterialTheme.colorScheme.primary
            )
        }

        Column(
            modifier = Modifier.weight(1f)
        ) {
            Text(
                text = title,
                style = MaterialTheme.typography.titleSmall,
                fontWeight = FontWeight.SemiBold
            )
            Text(
                text = description,
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }

        Icon(
            Icons.Default.Check,
            contentDescription = "Included",
            tint = MaterialTheme.colorScheme.primary,
            modifier = Modifier.size(20.dp)
        )
    }
}
