package com.tt.honeyDue.ui.screens

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
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.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.platform.LocalUriHandler
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.tt.honeyDue.ui.components.HandleErrors
import com.tt.honeyDue.ui.components.common.ErrorCard
import com.tt.honeyDue.ui.components.dialogs.DeleteAccountDialog
import com.tt.honeyDue.utils.SubscriptionHelper
import com.tt.honeyDue.ui.theme.AppRadius
import com.tt.honeyDue.ui.theme.AppSpacing
import com.tt.honeyDue.ui.theme.ThemeManager
import com.tt.honeyDue.ui.theme.*
import com.tt.honeyDue.viewmodel.AuthViewModel
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.network.APILayer
import com.tt.honeyDue.data.LocalDataManager
import com.tt.honeyDue.ui.subscription.UpgradePromptDialog
import androidx.compose.runtime.getValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.tt.honeyDue.analytics.PostHogAnalytics
import com.tt.honeyDue.analytics.AnalyticsEvents
import com.tt.honeyDue.platform.BiometricResult
import com.tt.honeyDue.platform.rememberBiometricAuth
import com.tt.honeyDue.storage.BiometricPreference
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.stringResource

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProfileScreen(
    onNavigateBack: () -> Unit,
    onLogout: () -> Unit,
    onAccountDeleted: () -> Unit = {},
    onNavigateToNotificationPreferences: () -> Unit = {},
    onNavigateToThemeSelection: () -> Unit = {},
    onNavigateToUpgrade: (() -> Unit)? = null,
    viewModel: AuthViewModel = viewModel { AuthViewModel() }
) {
    var firstName by remember { mutableStateOf("") }
    var lastName by remember { mutableStateOf("") }
    var email by remember { mutableStateOf("") }
    var errorMessage by remember { mutableStateOf("") }
    var isLoading by remember { mutableStateOf(false) }
    var successMessage by remember { mutableStateOf("") }
    var isLoadingUser by remember { mutableStateOf(true) }
    var showUpgradePrompt by remember { mutableStateOf(false) }
    var showDeleteAccountDialog by remember { mutableStateOf(false) }

    val biometricAuth = rememberBiometricAuth()
    val isBiometricAvailable = remember { biometricAuth.isBiometricAvailable() }
    var isBiometricEnabled by remember { mutableStateOf(BiometricPreference.isBiometricEnabled()) }

    val updateState by viewModel.updateProfileState.collectAsStateWithLifecycle()
    val deleteAccountState by viewModel.deleteAccountState.collectAsStateWithLifecycle()
    val currentTheme by remember { derivedStateOf { ThemeManager.currentTheme } }
    val dataManager = LocalDataManager.current
    val currentSubscription by dataManager.subscription.collectAsStateWithLifecycle()
    val currentUser by dataManager.currentUser.collectAsStateWithLifecycle()

    // Handle errors for profile update
    updateState.HandleErrors(
        onRetry = {
            viewModel.updateProfile(
                firstName = firstName.ifBlank { null },
                lastName = lastName.ifBlank { null },
                email = email
            )
        },
        errorTitle = stringResource(Res.string.profile_update_failed)
    )

    // Track screen view and load current user data
    LaunchedEffect(Unit) {
        PostHogAnalytics.screen(AnalyticsEvents.SETTINGS_SCREEN_SHOWN)
        when (val result = APILayer.getCurrentUser()) {
            is ApiResult.Success -> {
                firstName = result.data.firstName ?: ""
                lastName = result.data.lastName ?: ""
                email = result.data.email
                isLoadingUser = false
            }
            is ApiResult.Error -> {
                errorMessage = if (result.code == 401) "profile_not_authenticated" else "profile_load_failed"
                isLoadingUser = false
            }
            else -> {
                errorMessage = "profile_load_failed"
                isLoadingUser = false
            }
        }
    }

    // Handle delete account state
    LaunchedEffect(deleteAccountState) {
        when (deleteAccountState) {
            is ApiResult.Success -> {
                showDeleteAccountDialog = false
                viewModel.resetDeleteAccountState()
                onAccountDeleted()
            }
            is ApiResult.Error -> {
                // Error is shown in the dialog via isLoading becoming false
                // The user can see the error and retry
            }
            else -> {}
        }
    }

    // TODO: Re-enable profile update functionality
    /*
    LaunchedEffect(updateState) {
        when (updateState) {
            is ApiResult.Success -> {
                successMessage = "Profile updated successfully"
                isLoading = false
                errorMessage = ""
            }
            is ApiResult.Error -> {
                errorMessage = com.tt.honeyDue.util.ErrorMessageParser.parse((updateState as ApiResult.Error).message)
                isLoading = false
                successMessage = ""
            }
            is ApiResult.Loading -> {
                isLoading = true
                errorMessage = ""
                successMessage = ""
            }
            is ApiResult.Idle -> {
                // Do nothing - initial state, no loading indicator needed
            }
            else -> {}
        }
    }
    */

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(stringResource(Res.string.profile_title), fontWeight = FontWeight.SemiBold) },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.common_back))
                    }
                },
                actions = {
                    IconButton(onClick = onLogout) {
                        Icon(Icons.Default.Logout, contentDescription = stringResource(Res.string.profile_logout))
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.surface
                )
            )
        }
    ) { paddingValues ->
        WarmGradientBackground {
            if (isLoadingUser) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            } else {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues)
                        .imePadding()
                        .verticalScroll(rememberScrollState())
                        .padding(start = 24.dp, end = 24.dp, top = 24.dp, bottom = 96.dp),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                ) {
                    Spacer(modifier = Modifier.height(OrganicSpacing.sm))

                    // Profile Icon
                    OrganicIconContainer(
                        icon = Icons.Default.AccountCircle,
                        size = 80.dp,
                        iconSize = 48.dp
                    )

                    Text(
                        stringResource(Res.string.profile_update_title),
                        style = MaterialTheme.typography.headlineSmall,
                        fontWeight = FontWeight.Bold
                    )

                    Spacer(modifier = Modifier.height(OrganicSpacing.sm))

                    // Edit Profile Section
                    OrganicCard(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { /* Profile fields are below - could add scroll behavior */ }
                            .naturalShadow()
                    ) {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(OrganicSpacing.lg),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Column(
                                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.xs)
                            ) {
                                Text(
                                    text = stringResource(Res.string.profile_edit_profile),
                                    style = MaterialTheme.typography.titleMedium,
                                    fontWeight = FontWeight.SemiBold
                                )
                                Text(
                                    text = if (firstName.isNotBlank() || lastName.isNotBlank())
                                        "$firstName $lastName".trim()
                                    else email,
                                    style = MaterialTheme.typography.bodyMedium,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                            Icon(
                                imageVector = Icons.Default.Person,
                                contentDescription = stringResource(Res.string.profile_edit_profile),
                                tint = MaterialTheme.colorScheme.primary
                            )
                        }
                    }

                    // Theme Selector Section
                    OrganicCard(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { onNavigateToThemeSelection() }
                            .naturalShadow()
                    ) {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(OrganicSpacing.lg),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Column(
                                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.xs)
                            ) {
                                Text(
                                    text = stringResource(Res.string.profile_appearance),
                                    style = MaterialTheme.typography.titleMedium,
                                    fontWeight = FontWeight.SemiBold
                                )
                                Text(
                                    text = currentTheme.displayName,
                                    style = MaterialTheme.typography.bodyMedium,
                                    color = MaterialTheme.colorScheme.primary
                                )
                            }
                            Icon(
                                imageVector = Icons.Default.Palette,
                                contentDescription = stringResource(Res.string.profile_change_theme),
                                tint = MaterialTheme.colorScheme.primary
                            )
                        }
                    }

                    // Notification Preferences Section
                    OrganicCard(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { onNavigateToNotificationPreferences() }
                            .naturalShadow()
                    ) {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(OrganicSpacing.lg),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Column(
                                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.xs)
                            ) {
                                Text(
                                    text = stringResource(Res.string.profile_notifications),
                                    style = MaterialTheme.typography.titleMedium,
                                    fontWeight = FontWeight.SemiBold
                                )
                                Text(
                                    text = stringResource(Res.string.profile_notifications_subtitle),
                                    style = MaterialTheme.typography.bodyMedium,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                            Icon(
                                imageVector = Icons.Default.Notifications,
                                contentDescription = stringResource(Res.string.profile_notifications),
                                tint = MaterialTheme.colorScheme.primary
                            )
                        }
                    }

                    // Biometric Lock Section - only show if device supports biometrics
                    if (isBiometricAvailable) {
                        val biometricPromptTitle = stringResource(Res.string.biometric_prompt_title)
                        val biometricPromptSubtitle = stringResource(Res.string.biometric_prompt_subtitle)

                        OrganicCard(
                            modifier = Modifier
                                .fillMaxWidth()
                                .naturalShadow()
                        ) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(OrganicSpacing.lg),
                                horizontalArrangement = Arrangement.SpaceBetween,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Column(
                                    modifier = Modifier.weight(1f),
                                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.xs)
                                ) {
                                    Text(
                                        text = stringResource(Res.string.biometric_lock_setting_title),
                                        style = MaterialTheme.typography.titleMedium,
                                        fontWeight = FontWeight.SemiBold
                                    )
                                    Text(
                                        text = stringResource(Res.string.biometric_lock_setting_subtitle),
                                        style = MaterialTheme.typography.bodyMedium,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                                Switch(
                                    checked = isBiometricEnabled,
                                    onCheckedChange = { newValue ->
                                        // Authenticate before toggling
                                        biometricAuth.authenticate(
                                            title = biometricPromptTitle,
                                            subtitle = biometricPromptSubtitle
                                        ) { result ->
                                            when (result) {
                                                is BiometricResult.Success -> {
                                                    BiometricPreference.setBiometricEnabled(newValue)
                                                    isBiometricEnabled = newValue
                                                }
                                                is BiometricResult.Failed,
                                                is BiometricResult.NotAvailable -> {
                                                    // Auth failed, don't change the toggle
                                                }
                                            }
                                        }
                                    }
                                )
                            }
                        }
                    }

                    // Contact Support Section
                    val uriHandler = LocalUriHandler.current
                    OrganicCard(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable {
                                uriHandler.openUri("mailto:honeydueSupport@treymail.com?subject=honeyDue%20Support%20Request")
                            }
                            .naturalShadow()
                    ) {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(OrganicSpacing.lg),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Column(
                                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.xs)
                            ) {
                                Text(
                                    text = stringResource(Res.string.profile_contact_support),
                                    style = MaterialTheme.typography.titleMedium,
                                    fontWeight = FontWeight.SemiBold
                                )
                                Text(
                                    text = stringResource(Res.string.profile_contact_support_subtitle),
                                    style = MaterialTheme.typography.bodyMedium,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                            Icon(
                                imageVector = Icons.Default.Email,
                                contentDescription = stringResource(Res.string.profile_contact_support),
                                tint = MaterialTheme.colorScheme.primary
                            )
                        }
                    }

                    // Privacy Policy Section
                    OrganicCard(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable {
                                uriHandler.openUri("https://honeyDue.treytartt.com/privacy")
                            }
                            .naturalShadow()
                    ) {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(OrganicSpacing.lg),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Column(
                                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.xs)
                            ) {
                                Text(
                                    text = stringResource(Res.string.profile_privacy),
                                    style = MaterialTheme.typography.titleMedium,
                                    fontWeight = FontWeight.SemiBold
                                )
                                Text(
                                    text = stringResource(Res.string.profile_privacy_subtitle),
                                    style = MaterialTheme.typography.bodyMedium,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                            Icon(
                                imageVector = Icons.Default.Lock,
                                contentDescription = stringResource(Res.string.profile_privacy),
                                tint = MaterialTheme.colorScheme.primary
                            )
                        }
                    }

                    // Subscription Section - Only show if limitations are enabled
                    if (currentSubscription?.limitationsEnabled == true) {
                        OrganicDivider(modifier = Modifier.padding(vertical = OrganicSpacing.sm))

                        OrganicCard(
                            modifier = Modifier
                                .fillMaxWidth()
                                .naturalShadow()
                        ) {
                            Column(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(OrganicSpacing.lg),
                                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                            ) {
                                Row(
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                                ) {
                                    Icon(
                                        imageVector = Icons.Default.Star,
                                        contentDescription = "Subscription",
                                        tint = if (SubscriptionHelper.currentTier == "pro") MaterialTheme.colorScheme.tertiary else MaterialTheme.colorScheme.onSurfaceVariant
                                    )

                                    Column(
                                        verticalArrangement = Arrangement.spacedBy(OrganicSpacing.xs)
                                    ) {
                                        Text(
                                            text = if (SubscriptionHelper.currentTier == "pro") stringResource(Res.string.profile_pro_plan) else stringResource(Res.string.profile_free_plan),
                                            style = MaterialTheme.typography.titleMedium,
                                            fontWeight = FontWeight.SemiBold
                                        )

                                        Text(
                                            text = if (SubscriptionHelper.currentTier == "pro" && currentSubscription?.expiresAt != null) {
                                                stringResource(Res.string.profile_active_until, currentSubscription?.expiresAt ?: "")
                                            } else {
                                                stringResource(Res.string.profile_limited_features)
                                            },
                                            style = MaterialTheme.typography.bodySmall,
                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                    }
                                }

                                if (SubscriptionHelper.currentTier != "pro") {
                                    // Upgrade Benefits List
                                    Column(
                                        modifier = Modifier.padding(vertical = OrganicSpacing.sm),
                                        verticalArrangement = Arrangement.spacedBy(OrganicSpacing.sm)
                                    ) {
                                        Text(
                                            text = stringResource(Res.string.profile_upgrade_benefits_title),
                                            style = MaterialTheme.typography.titleSmall,
                                            fontWeight = FontWeight.SemiBold,
                                            color = MaterialTheme.colorScheme.primary
                                        )

                                        UpgradeBenefitRow(
                                            icon = Icons.Default.Home,
                                            text = stringResource(Res.string.profile_benefit_unlimited_properties)
                                        )
                                        UpgradeBenefitRow(
                                            icon = Icons.Default.Folder,
                                            text = stringResource(Res.string.profile_benefit_document_vault)
                                        )
                                        UpgradeBenefitRow(
                                            icon = Icons.Default.People,
                                            text = stringResource(Res.string.profile_benefit_residence_sharing)
                                        )
                                        UpgradeBenefitRow(
                                            icon = Icons.Default.Share,
                                            text = stringResource(Res.string.profile_benefit_contractor_sharing)
                                        )
                                        UpgradeBenefitRow(
                                            icon = Icons.Default.Notifications,
                                            text = stringResource(Res.string.profile_benefit_actionable_notifications)
                                        )
                                        UpgradeBenefitRow(
                                            icon = Icons.Default.Widgets,
                                            text = stringResource(Res.string.profile_benefit_widgets)
                                        )
                                    }

                                    Button(
                                        onClick = {
                                            if (onNavigateToUpgrade != null) {
                                                onNavigateToUpgrade()
                                            } else {
                                                showUpgradePrompt = true
                                            }
                                        },
                                        modifier = Modifier.fillMaxWidth(),
                                        colors = ButtonDefaults.buttonColors(
                                            containerColor = MaterialTheme.colorScheme.primary
                                        )
                                    ) {
                                        Icon(
                                            imageVector = Icons.Default.KeyboardArrowUp,
                                            contentDescription = null // decorative
                                        )
                                        Spacer(modifier = Modifier.width(OrganicSpacing.sm))
                                        Text(stringResource(Res.string.profile_upgrade_to_pro), fontWeight = FontWeight.SemiBold)
                                    }
                                } else {
                                    Text(
                                        text = stringResource(Res.string.profile_manage_subscription),
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                                        modifier = Modifier.padding(top = OrganicSpacing.xs)
                                    )
                                }
                            }
                        }

                        OrganicDivider(modifier = Modifier.padding(vertical = OrganicSpacing.sm))
                    }

                    Text(
                        stringResource(Res.string.profile_information),
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.SemiBold,
                        modifier = Modifier.align(Alignment.Start)
                    )

                    OutlinedTextField(
                        value = firstName,
                        onValueChange = { firstName = it },
                        label = { Text(stringResource(Res.string.profile_first_name)) },
                        leadingIcon = {
                            Icon(Icons.Default.Person, contentDescription = null) // decorative
                        },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                        shape = RoundedCornerShape(AppRadius.md)
                    )

                    OutlinedTextField(
                        value = lastName,
                        onValueChange = { lastName = it },
                        label = { Text(stringResource(Res.string.profile_last_name)) },
                        leadingIcon = {
                            Icon(Icons.Default.Person, contentDescription = null) // decorative
                        },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                        shape = RoundedCornerShape(AppRadius.md)
                    )

                    OutlinedTextField(
                        value = email,
                        onValueChange = { email = it },
                        label = { Text(stringResource(Res.string.profile_email)) },
                        leadingIcon = {
                            Icon(Icons.Default.Email, contentDescription = null) // decorative
                        },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                        shape = RoundedCornerShape(AppRadius.md)
                    )

                    if (errorMessage.isNotEmpty()) {
                        val displayError = when (errorMessage) {
                            "profile_load_failed" -> stringResource(Res.string.profile_load_failed)
                            "profile_not_authenticated" -> stringResource(Res.string.profile_not_authenticated)
                            "profile_update_coming_soon" -> stringResource(Res.string.profile_update_coming_soon)
                            "profile_email_required" -> stringResource(Res.string.profile_email_required)
                            else -> errorMessage
                        }
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.errorContainer
                            ),
                            shape = RoundedCornerShape(AppRadius.md)
                        ) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(AppSpacing.lg),
                                horizontalArrangement = Arrangement.spacedBy(AppSpacing.md),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(
                                    Icons.Default.Error,
                                    contentDescription = "Error",
                                    tint = MaterialTheme.colorScheme.error
                                )
                                Text(
                                    displayError,
                                    color = MaterialTheme.colorScheme.error,
                                    style = MaterialTheme.typography.bodyMedium,
                                    fontWeight = FontWeight.SemiBold
                                )
                            }
                        }
                    }

                    if (successMessage.isNotEmpty()) {
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.primaryContainer
                            ),
                            shape = RoundedCornerShape(AppRadius.md)
                        ) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(AppSpacing.lg),
                                horizontalArrangement = Arrangement.spacedBy(AppSpacing.md),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(
                                    Icons.Default.CheckCircle,
                                    contentDescription = "Success",
                                    tint = MaterialTheme.colorScheme.onPrimaryContainer
                                )
                                Text(
                                    successMessage,
                                    color = MaterialTheme.colorScheme.onPrimaryContainer,
                                    style = MaterialTheme.typography.bodyMedium,
                                    fontWeight = FontWeight.SemiBold
                                )
                            }
                        }
                    }

                    Spacer(modifier = Modifier.height(OrganicSpacing.sm))

                    Button(
                        onClick = {
                            if (email.isNotEmpty()) {
                                // viewModel.updateProfile not available yet
                                errorMessage = "profile_update_coming_soon"
                            } else {
                                errorMessage = "profile_email_required"
                            }
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(56.dp),
                        enabled = email.isNotEmpty() && !isLoading,
                        shape = RoundedCornerShape(AppRadius.md)
                    ) {
                        if (isLoading) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(24.dp),
                                color = MaterialTheme.colorScheme.onPrimary,
                                strokeWidth = 2.dp
                            )
                        } else {
                            Row(
                                horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(Icons.Default.Save, contentDescription = null) // decorative
                                Text(
                                    stringResource(Res.string.profile_save),
                                    style = MaterialTheme.typography.titleMedium,
                                    fontWeight = FontWeight.SemiBold
                                )
                            }
                        }
                    }

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

                    // Delete Account Section
                    OrganicDivider(modifier = Modifier.padding(vertical = OrganicSpacing.md))
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { showDeleteAccountDialog = true },
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.errorContainer
                        ),
                        shape = RoundedCornerShape(AppRadius.md)
                    ) {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(OrganicSpacing.lg),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Column(
                                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.xs)
                            ) {
                                Text(
                                    text = stringResource(Res.string.delete_account_title),
                                    style = MaterialTheme.typography.titleMedium,
                                    fontWeight = FontWeight.SemiBold,
                                    color = MaterialTheme.colorScheme.error
                                )
                                Text(
                                    text = stringResource(Res.string.delete_account_subtitle),
                                    style = MaterialTheme.typography.bodyMedium,
                                    color = MaterialTheme.colorScheme.error.copy(alpha = 0.7f)
                                )
                            }
                            Icon(
                                imageVector = Icons.Default.Delete,
                                contentDescription = stringResource(Res.string.delete_account_title),
                                tint = MaterialTheme.colorScheme.error
                            )
                        }
                    }

                    // App Version Section
                    OrganicDivider(modifier = Modifier.padding(vertical = OrganicSpacing.md))
                    Column(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.spacedBy(OrganicSpacing.xs)
                    ) {
                        Text(
                            text = stringResource(Res.string.profile_app_name),
                            style = MaterialTheme.typography.labelMedium,
                            fontWeight = FontWeight.SemiBold,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        Text(
                            text = stringResource(Res.string.profile_app_version, getAppVersion()),
                            style = MaterialTheme.typography.labelSmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
                        )
                    }

                    Spacer(modifier = Modifier.height(OrganicSpacing.lg))
                }
            }
        }

        // Delete Account Dialog
        if (showDeleteAccountDialog) {
            val isSocialAuth = currentUser?.authProvider?.let {
                it == "apple" || it == "google"
            } ?: false

            DeleteAccountDialog(
                isSocialAuthUser = isSocialAuth,
                onConfirm = { password, confirmation ->
                    viewModel.deleteAccount(password = password, confirmation = confirmation)
                },
                onDismiss = {
                    showDeleteAccountDialog = false
                    viewModel.resetDeleteAccountState()
                },
                isLoading = deleteAccountState is ApiResult.Loading
            )
        }

        // Upgrade Prompt Dialog
        if (showUpgradePrompt) {
            UpgradePromptDialog(
                triggerKey = "profile_upgrade",
                onUpgrade = {
                    // Handle upgrade action - on Android this would open Play Store
                    // For now, just close the dialog
                    showUpgradePrompt = false
                },
                onDismiss = { showUpgradePrompt = false }
            )
        }
    }
}

@Composable
private fun UpgradeBenefitRow(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    text: String
) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.sm)
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null, // decorative
            modifier = Modifier.size(18.dp),
            tint = MaterialTheme.colorScheme.primary
        )
        Text(
            text = text,
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

/**
 * Get app version - in a real implementation this would come from
 * platform-specific build configuration
 */
private fun getAppVersion(): String {
    // This would be replaced with actual version from build config
    // For now, return a placeholder that matches iOS
    return "1.0.0"
}
