package com.tt.honeyDue.ui.screens.subscription

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.tt.honeyDue.analytics.AnalyticsEvents
import com.tt.honeyDue.analytics.PostHogAnalytics
import com.tt.honeyDue.data.LocalDataManager
import com.tt.honeyDue.models.FeatureBenefit
import com.tt.honeyDue.ui.components.common.StandardCard
import com.tt.honeyDue.ui.theme.AppSpacing

/**
 * FeatureComparisonScreen — full-screen Free vs. Pro comparison matching
 * iOS `iosApp/iosApp/Subscription/FeatureComparisonView.swift`.
 *
 * Replaces the old `ui/subscription/FeatureComparisonDialog.kt` (deleted
 * in P2 Stream E). The iOS view is a navigation-stack destination, not a
 * dialog — this screen mirrors that layout:
 *
 *  - Header ("Choose Your Plan" + subtitle)
 *  - Two-column comparison table rendered inside a [StandardCard]
 *    (Feature | Free | Pro) with N rows sourced from
 *    `LocalDataManager.current.featureBenefits` (resolves to the
 *    `DataManager` singleton in production), falling back to a 4-row
 *    default list.
 *  - CTA button at the bottom ("Upgrade to Pro") which fires analytics
 *    event [AnalyticsEvents.PAYWALL_COMPARE_CTA] and invokes
 *    [onNavigateToUpgrade].
 *  - Toolbar back button dismisses.
 *
 * Testable behavior lives on [FeatureComparisonScreenState] so it can be
 * exercised in `commonTest` without standing up the Compose recomposer.
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FeatureComparisonScreen(
    onNavigateBack: () -> Unit,
    onNavigateToUpgrade: () -> Unit,
) {
    val dataManager = LocalDataManager.current
    val benefits by dataManager.featureBenefits.collectAsStateWithLifecycle()
    val rows = FeatureComparisonScreenState.resolveFeatureRows(benefits)

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        text = "Choose Your Plan",
                        fontWeight = FontWeight.SemiBold,
                    )
                },
                navigationIcon = {
                    IconButton(onClick = {
                        FeatureComparisonScreenState.onClose(onBack = onNavigateBack)
                    }) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "Close",
                            tint = MaterialTheme.colorScheme.primary,
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.surface,
                ),
            )
        },
    ) { paddingValues: PaddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .verticalScroll(rememberScrollState())
                .padding(horizontal = AppSpacing.lg, vertical = AppSpacing.md),
            verticalArrangement = Arrangement.spacedBy(AppSpacing.lg),
        ) {
            Column(
                modifier = Modifier.fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.spacedBy(AppSpacing.sm),
            ) {
                Text(
                    text = "Choose Your Plan",
                    style = MaterialTheme.typography.headlineSmall,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onBackground,
                )
                Text(
                    text = "Upgrade to Pro for unlimited access",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    textAlign = TextAlign.Center,
                )
            }

            StandardCard(
                modifier = Modifier.fillMaxWidth(),
                contentPadding = 0.dp,
            ) {
                Column(modifier = Modifier.fillMaxWidth()) {
                    ComparisonHeaderRow()
                    HorizontalDivider()

                    rows.forEachIndexed { index, row ->
                        ComparisonRow(
                            featureName = row.featureName,
                            freeText = row.freeTierText,
                            proText = row.proTierText,
                            freeHas = FeatureComparisonScreenState.freeHasFeature(row),
                            proHas = FeatureComparisonScreenState.premiumHasFeature(row),
                        )
                        if (index != rows.lastIndex) {
                            HorizontalDivider()
                        }
                    }
                }
            }

            Button(
                onClick = {
                    FeatureComparisonScreenState.onUpgradeTap(
                        onNavigateToUpgrade = onNavigateToUpgrade,
                        captureEvent = { event, props ->
                            PostHogAnalytics.capture(event, props)
                        },
                    )
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(56.dp),
                shape = MaterialTheme.shapes.medium,
                colors = ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.primary,
                ),
            ) {
                Text(
                    text = "Upgrade to Pro",
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onPrimary,
                )
            }

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

@Composable
private fun ComparisonHeaderRow() {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        color = MaterialTheme.colorScheme.surfaceVariant,
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(AppSpacing.md),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Text(
                text = "Feature",
                modifier = Modifier.weight(1f),
                style = MaterialTheme.typography.titleSmall,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.onSurface,
            )
            Text(
                text = "Free",
                modifier = Modifier.width(80.dp),
                style = MaterialTheme.typography.titleSmall,
                fontWeight = FontWeight.Bold,
                textAlign = TextAlign.Center,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )
            Text(
                text = "Pro",
                modifier = Modifier.width(80.dp),
                style = MaterialTheme.typography.titleSmall,
                fontWeight = FontWeight.Bold,
                textAlign = TextAlign.Center,
                color = MaterialTheme.colorScheme.primary,
            )
        }
    }
}

@Composable
private fun ComparisonRow(
    featureName: String,
    freeText: String,
    proText: String,
    freeHas: Boolean,
    proHas: Boolean,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(AppSpacing.md),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Text(
            text = featureName,
            modifier = Modifier.weight(1f),
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurface,
        )

        Box(
            modifier = Modifier.width(80.dp),
            contentAlignment = Alignment.Center,
        ) {
            TierCell(
                text = freeText,
                hasFeature = freeHas,
                emphasize = false,
            )
        }

        Box(
            modifier = Modifier.width(80.dp),
            contentAlignment = Alignment.Center,
        ) {
            TierCell(
                text = proText,
                hasFeature = proHas,
                emphasize = true,
            )
        }
    }
}

/**
 * Single tier cell showing a check/cross glyph stacked with the limit
 * text. Matches the iOS `ComparisonRow` visual language where "Not
 * available" reads as the absence of the feature.
 */
@Composable
private fun TierCell(
    text: String,
    hasFeature: Boolean,
    emphasize: Boolean,
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(AppSpacing.xs),
    ) {
        Icon(
            imageVector = if (hasFeature) Icons.Default.Check else Icons.Default.Close,
            contentDescription = if (hasFeature) "Included" else "Not included",
            modifier = Modifier.size(18.dp),
            tint = if (hasFeature) {
                if (emphasize) MaterialTheme.colorScheme.primary
                else MaterialTheme.colorScheme.onSurfaceVariant
            } else {
                MaterialTheme.colorScheme.onSurfaceVariant
            },
        )
        Text(
            text = text,
            style = MaterialTheme.typography.bodySmall,
            textAlign = TextAlign.Center,
            fontWeight = if (emphasize) FontWeight.Medium else FontWeight.Normal,
            color = if (emphasize && hasFeature) {
                MaterialTheme.colorScheme.primary
            } else {
                MaterialTheme.colorScheme.onSurfaceVariant
            },
        )
    }
}

/**
 * State helper for [FeatureComparisonScreen].
 *
 * Pulled out as a plain object so the behavior is unit-testable in
 * `commonTest` without standing up the Compose recomposer — same pattern
 * as [com.tt.honeyDue.ui.screens.theme.ThemeSelectionScreenState].
 *
 * The iOS reference (`FeatureComparisonView.swift`) sources rows from
 * `SubscriptionCacheWrapper.shared.featureBenefits` with a 4-row default
 * list when the cache is empty. This object exposes:
 *
 *   - [defaultFeatureRows] — the same 4-row default (Properties, Tasks,
 *     Contractors, Documents).
 *   - [resolveFeatureRows] — server-driven benefits if present, default
 *     otherwise.
 *   - [freeHasFeature] / [premiumHasFeature] — per-row booleans matching
 *     iOS: a tier "has" the feature unless its text reads "Not available"
 *     (case-insensitive).
 *   - [onUpgradeTap] — fires [AnalyticsEvents.PAYWALL_COMPARE_CTA] and
 *     navigates to the upgrade flow.
 *   - [onClose] — dismisses the screen.
 */
object FeatureComparisonScreenState {

    fun defaultFeatureRows(): List<FeatureBenefit> = listOf(
        FeatureBenefit(
            featureName = "Properties",
            freeTierText = "1 property",
            proTierText = "Unlimited",
        ),
        FeatureBenefit(
            featureName = "Tasks",
            freeTierText = "10 tasks",
            proTierText = "Unlimited",
        ),
        FeatureBenefit(
            featureName = "Contractors",
            freeTierText = "Not available",
            proTierText = "Unlimited",
        ),
        FeatureBenefit(
            featureName = "Documents",
            freeTierText = "Not available",
            proTierText = "Unlimited",
        ),
    )

    fun resolveFeatureRows(serverBenefits: List<FeatureBenefit>): List<FeatureBenefit> {
        return if (serverBenefits.isNotEmpty()) serverBenefits else defaultFeatureRows()
    }

    fun freeHasFeature(benefit: FeatureBenefit): Boolean =
        !isUnavailable(benefit.freeTierText)

    fun premiumHasFeature(benefit: FeatureBenefit): Boolean =
        !isUnavailable(benefit.proTierText)

    private fun isUnavailable(text: String): Boolean =
        text.trim().equals("Not available", ignoreCase = true)

    /**
     * CTA handler. Fires the paywall analytics event and navigates to
     * the upgrade flow. The [captureEvent] parameter is injected so tests
     * can record without touching the PostHog SDK.
     */
    fun onUpgradeTap(
        onNavigateToUpgrade: () -> Unit,
        captureEvent: (String, Map<String, Any>?) -> Unit,
    ) {
        captureEvent(AnalyticsEvents.PAYWALL_COMPARE_CTA, null)
        onNavigateToUpgrade()
    }

    fun onClose(onBack: () -> Unit) {
        onBack()
    }
}
