package app.closer.ui.settings

import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
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.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.layout.size
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.automirrored.filled.OpenInNew
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import app.closer.R
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.closer.core.billing.EntitlementChecker
import app.closer.core.navigation.AppRoute
import app.closer.core.navigation.ExternalLinks
import app.closer.domain.repository.BillingRepository
import app.closer.domain.repository.BillingState
import app.closer.ui.components.LoadingState
import app.closer.ui.theme.closerBackgroundBrush
import app.closer.ui.theme.closerCardColor
import com.revenuecat.purchases.CustomerInfo
import dagger.hilt.android.lifecycle.HiltViewModel
import java.text.SimpleDateFormat
import java.util.Locale
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

private val BENEFITS = listOf(
    "Unlimited questions every day",
    "Every premium question pack",
    "Full answer history and insights",
    "Date planning and bucket list",
    "Connection Challenges and Desire Sync",
    "Memory Lane time capsules",
)

data class SubscriptionUiState(
    val isLoading: Boolean = true,
    val isPremium: Boolean = false,
    val renewalDateLabel: String? = null,
    val isRestoring: Boolean = false,
    val restoreSuccess: Boolean = false,
    val restoreError: String? = null,
)

@HiltViewModel
class SubscriptionViewModel @Inject constructor(
    private val entitlementChecker: EntitlementChecker,
    private val billingRepository: BillingRepository,
) : ViewModel() {

    private val _uiState = MutableStateFlow(SubscriptionUiState())
    val uiState: StateFlow<SubscriptionUiState> = _uiState.asStateFlow()

    init {
        entitlementChecker.isPremium()
            .onEach { premium -> _uiState.update { it.copy(isLoading = false, isPremium = premium) } }
            .launchIn(viewModelScope)

        billingRepository.getCustomerInfo()
            .onEach { state ->
                if (state is BillingState.Success) {
                    _uiState.update { it.copy(renewalDateLabel = state.data.renewalLabel()) }
                }
            }
            .launchIn(viewModelScope)
    }

    fun restore() {
        if (_uiState.value.isRestoring) return
        _uiState.update { it.copy(isRestoring = true, restoreError = null) }
        viewModelScope.launch {
            when (val result = billingRepository.restorePurchases()) {
                is BillingState.Success -> _uiState.update {
                    it.copy(isRestoring = false, restoreSuccess = true)
                }
                is BillingState.Error -> {
                    Log.w("SubscriptionVM", "Restore failed: ${result.message}")
                    _uiState.update { it.copy(isRestoring = false, restoreError = result.message) }
                }
                else -> _uiState.update { it.copy(isRestoring = false) }
            }
        }
    }

    fun consumeRestoreSuccess() = _uiState.update { it.copy(restoreSuccess = false) }
    fun consumeRestoreError() = _uiState.update { it.copy(restoreError = null) }
}

private fun CustomerInfo.renewalLabel(): String? {
    val expiry = latestExpirationDate ?: return null
    val fmt = SimpleDateFormat("MMM d, yyyy", Locale.getDefault())
    return "Renews ${fmt.format(expiry)}"
}

@Composable
fun SubscriptionScreen(
    onNavigate: (String) -> Unit = {},
    viewModel: SubscriptionViewModel = hiltViewModel()
) {
    val state by viewModel.uiState.collectAsState()
    val snackbar = remember { SnackbarHostState() }
    val context = LocalContext.current

    LaunchedEffect(state.restoreSuccess) {
        if (state.restoreSuccess) {
            snackbar.showSnackbar("Purchases restored.")
            viewModel.consumeRestoreSuccess()
        }
    }
    LaunchedEffect(state.restoreError) {
        state.restoreError?.let {
            snackbar.showSnackbar(it)
            viewModel.consumeRestoreError()
        }
    }

    Scaffold(
        snackbarHost = { SnackbarHost(snackbar) },
        containerColor = Color.Transparent,
        modifier = Modifier.background(closerBackgroundBrush())
    ) { padding ->
        if (state.isLoading) {
            LoadingState(modifier = Modifier.fillMaxSize().padding(padding))
        } else if (state.isPremium) {
            PremiumContent(
                state = state,
                onManage = { ExternalLinks.openUrl(context, ExternalLinks.MANAGE_SUBSCRIPTION) },
                onRestore = viewModel::restore,
                modifier = Modifier.padding(padding)
            )
        } else {
            FreeContent(
                state = state,
                onUpgrade = { onNavigate(AppRoute.PAYWALL) },
                onRestore = viewModel::restore,
                modifier = Modifier.padding(padding)
            )
        }
    }
}

@Composable
private fun PremiumContent(
    state: SubscriptionUiState,
    onManage: () -> Unit,
    onRestore: () -> Unit,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier
            .fillMaxSize()
            .safeDrawingPadding()
            .navigationBarsPadding()
            .verticalScroll(rememberScrollState())
            .padding(horizontal = 20.dp, vertical = 16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        Surface(
            modifier = Modifier.fillMaxWidth(),
            shape = RoundedCornerShape(24.dp),
            color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.24f),
            shadowElevation = 0.dp
        ) {
            Column(
                modifier = Modifier.padding(24.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.spacedBy(10.dp)
            ) {
                SubscriptionHeroImage()
                Text(
                    text = "You're Premium",
                    style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.SemiBold),
                    color = MaterialTheme.colorScheme.onSurface
                )
                state.renewalDateLabel?.let { label ->
                    Text(
                        text = label,
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
        }

        Surface(
            modifier = Modifier.fillMaxWidth(),
            shape = RoundedCornerShape(20.dp),
            color = closerCardColor(alpha = 0.9f),
            shadowElevation = 2.dp
        ) {
            Column(
                modifier = Modifier.padding(20.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                Text(
                    text = "What's included",
                    style = MaterialTheme.typography.labelLarge.copy(fontWeight = FontWeight.SemiBold),
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                BENEFITS.forEach { benefit ->
                    Row(
                        horizontalArrangement = Arrangement.spacedBy(10.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            imageVector = Icons.Filled.Check,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.size(16.dp)
                        )
                        Text(
                            text = benefit,
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                    }
                }
            }
        }

        Button(
            onClick = onManage,
            modifier = Modifier.fillMaxWidth(),
            shape = RoundedCornerShape(16.dp),
            colors = ButtonDefaults.buttonColors(
                containerColor = MaterialTheme.colorScheme.primary,
                contentColor = MaterialTheme.colorScheme.onPrimary
            )
        ) {
            Icon(
                Icons.AutoMirrored.Filled.OpenInNew,
                contentDescription = null,
                modifier = Modifier.size(16.dp)
            )
            Spacer(Modifier.size(6.dp))
            Text("Manage subscription", fontWeight = FontWeight.SemiBold)
        }

        TextButton(
            onClick = onRestore,
            enabled = !state.isRestoring,
            modifier = Modifier.fillMaxWidth()
        ) {
            Text(
                text = if (state.isRestoring) "Restoring…" else "Restore purchases",
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }

        Spacer(Modifier.height(8.dp))
    }
}

@Composable
private fun FreeContent(
    state: SubscriptionUiState,
    onUpgrade: () -> Unit,
    onRestore: () -> Unit,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier
            .fillMaxSize()
            .safeDrawingPadding()
            .navigationBarsPadding()
            .verticalScroll(rememberScrollState())
            .padding(horizontal = 20.dp, vertical = 16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp)
        ) {
            SubscriptionHeroImage()
            Spacer(Modifier.height(10.dp))
            Text(
                text = "Unlock Premium",
                style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.SemiBold),
                color = MaterialTheme.colorScheme.onSurface,
                textAlign = TextAlign.Center
            )
            Spacer(Modifier.height(4.dp))
            Text(
                text = "One subscription for both partners — no double billing.",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                textAlign = TextAlign.Center
            )
        }

        Surface(
            modifier = Modifier.fillMaxWidth(),
            shape = RoundedCornerShape(20.dp),
            color = closerCardColor(alpha = 0.9f),
            shadowElevation = 2.dp
        ) {
            Column(
                modifier = Modifier.padding(20.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                BENEFITS.forEach { benefit ->
                    Row(
                        horizontalArrangement = Arrangement.spacedBy(10.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            imageVector = Icons.Filled.Check,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.size(16.dp)
                        )
                        Text(
                            text = benefit,
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                    }
                }
            }
        }

        Button(
            onClick = onUpgrade,
            modifier = Modifier.fillMaxWidth(),
            shape = RoundedCornerShape(16.dp),
            colors = ButtonDefaults.buttonColors(
                containerColor = MaterialTheme.colorScheme.primary,
                contentColor = MaterialTheme.colorScheme.onPrimary
            )
        ) {
            Text("Upgrade to Premium", fontWeight = FontWeight.SemiBold)
        }

        TextButton(
            onClick = onRestore,
            enabled = !state.isRestoring,
            modifier = Modifier.fillMaxWidth()
        ) {
            Text(
                text = if (state.isRestoring) "Restoring…" else "Restore purchases",
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }

        Spacer(Modifier.height(8.dp))
    }
}

@Composable
private fun SubscriptionHeroImage(modifier: Modifier = Modifier) {
    Image(
        painter = painterResource(R.drawable.illustration_couple_subscription),
        contentDescription = null,
        contentScale = ContentScale.Crop,
        modifier = modifier
            .size(width = 188.dp, height = 220.dp)
            .clip(RoundedCornerShape(28.dp))
    )
}
