package app.closer.ui.pairing

import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.heightIn
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.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Person
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color
import app.closer.ui.components.CelebrationOverlay
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.closer.core.navigation.AppRoute
import app.closer.domain.repository.AuthRepository
import app.closer.domain.repository.CoupleRepository
import app.closer.domain.repository.UserRepository
import coil.compose.AsyncImage
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
import app.closer.ui.settings.SettingsBackgroundBrush
import app.closer.ui.settings.SettingsInk
import app.closer.ui.settings.SettingsMuted
import app.closer.ui.settings.SettingsOnPrimary
import app.closer.ui.settings.SettingsPrimary
import app.closer.ui.settings.SettingsSoft

// ── ViewModel ────────────────────────────────────────────────────────────────

data class PairingSuccessUiState(
    val myName: String = "",
    val myPhotoUrl: String = "",
    val partnerName: String = "",
    val partnerPhotoUrl: String = "",
    val navigateTo: String? = null
)

@HiltViewModel
class PairingSuccessViewModel @Inject constructor(
    savedStateHandle: SavedStateHandle,
    private val authRepository: AuthRepository,
    private val userRepository: UserRepository,
    private val coupleRepository: CoupleRepository
) : ViewModel() {

    private val coupleId: String = savedStateHandle["coupleId"] ?: ""
    private val _uiState = MutableStateFlow(PairingSuccessUiState())
    val uiState: StateFlow<PairingSuccessUiState> = _uiState.asStateFlow()

    init {
        viewModelScope.launch {
            val myId = authRepository.currentUserId ?: return@launch
            val me = runCatching { userRepository.getUser(myId) }.getOrNull()
            val couple = coupleRepository.getCoupleForUser(myId)
            val partnerId = couple?.userIds?.firstOrNull { it != myId }
            val partner = partnerId?.let { runCatching { userRepository.getUser(it) }.getOrNull() }

            // Fall back to the Firebase Auth profile (e.g. the Google avatar) if the user
            // doc photo/name hasn't propagated yet, so both faces show on the congrats screen.
            val myPhoto = me?.photoUrl?.takeIf { it.isNotBlank() }
                ?: authRepository.currentUserPhotoUrl?.takeIf { it.isNotBlank() }
                ?: ""
            val myName = me?.displayName?.takeIf { n -> n.isNotBlank() }
                ?: authRepository.currentUserDisplayName?.takeIf { n -> n.isNotBlank() }
                ?: "You"
            _uiState.update {
                it.copy(
                    myName = myName,
                    myPhotoUrl = myPhoto,
                    partnerName = partner?.displayName?.takeIf { n -> n.isNotBlank() } ?: "Your partner",
                    partnerPhotoUrl = partner?.photoUrl ?: ""
                )
            }
        }
    }

    fun proceed() = _uiState.update { it.copy(navigateTo = AppRoute.HOME) }
    fun onNavigated() = _uiState.update { it.copy(navigateTo = null) }
}

// ── Screen ────────────────────────────────────────────────────────────────────

@Composable
fun PairingSuccessScreen(
    coupleId: String,
    onNavigate: (String) -> Unit = {},
    viewModel: PairingSuccessViewModel = hiltViewModel()
) {
    val state by viewModel.uiState.collectAsState()

    LaunchedEffect(state.navigateTo) {
        state.navigateTo?.let { onNavigate(it); viewModel.onNavigated() }
    }

    val pulse by rememberInfiniteTransition(label = "heart").animateFloat(
        initialValue = 0.92f,
        targetValue = 1.12f,
        animationSpec = infiniteRepeatable(
            animation = tween(750, easing = FastOutSlowInEasing),
            repeatMode = RepeatMode.Reverse
        ),
        label = "heartScale"
    )

    // Hero springs in on arrival — the "we're really connected" beat.
    var appeared by remember { mutableStateOf(false) }
    LaunchedEffect(Unit) { appeared = true }
    val heroScale by animateFloatAsState(
        targetValue = if (appeared) 1f else 0.6f,
        animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow),
        label = "heroScale"
    )

    Box(modifier = Modifier.fillMaxSize().background(SettingsBackgroundBrush)) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .safeDrawingPadding()
            .navigationBarsPadding()
            .padding(horizontal = 32.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Spacer(Modifier.weight(1f))

        // Hero: both partners' photos, joined by a heart, springing in for impact.
        Box(
            modifier = Modifier
                .scale(heroScale)
                .width(248.dp)
                .height(152.dp),
            contentAlignment = Alignment.Center
        ) {
            PairAvatar(
                url = state.myPhotoUrl,
                modifier = Modifier
                    .size(142.dp)
                    .align(Alignment.CenterStart)
                    .zIndex(1f)
            )
            PairAvatar(
                url = state.partnerPhotoUrl,
                modifier = Modifier
                    .size(142.dp)
                    .align(Alignment.CenterEnd)
                    .zIndex(1f)
            )
            Box(
                modifier = Modifier
                    .size(60.dp)
                    .zIndex(2f)
                    .align(Alignment.Center)
                    .clip(CircleShape)
                    .background(MaterialTheme.colorScheme.background)
                    .padding(5.dp)
                    .clip(CircleShape)
                    .background(SettingsPrimary),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    Icons.Filled.Favorite,
                    contentDescription = null,
                    tint = SettingsOnPrimary,
                    modifier = Modifier
                        .size(28.dp)
                        .scale(pulse)
                )
            }
        }

        Spacer(Modifier.height(32.dp))

        Text(
            text = "You're connected",
            style = MaterialTheme.typography.displaySmall,
            fontWeight = FontWeight.Bold,
            color = SettingsInk,
            textAlign = TextAlign.Center
        )

        if (state.myName.isNotBlank() && state.partnerName.isNotBlank()) {
            Spacer(Modifier.height(10.dp))
            Text(
                text = "${state.myName} & ${state.partnerName}",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold,
                color = SettingsPrimary,
                textAlign = TextAlign.Center
            )
        }

        Spacer(Modifier.height(14.dp))

        Text(
            text = "Two phones, one private space. Everything from here is just for the two of you.",
            style = MaterialTheme.typography.bodyLarge,
            color = SettingsMuted,
            textAlign = TextAlign.Center
        )

        Spacer(Modifier.weight(1f))

        Button(
            onClick = viewModel::proceed,
            modifier = Modifier
                .fillMaxWidth()
                .heightIn(min = 56.dp),
            shape = RoundedCornerShape(16.dp),
            colors = ButtonDefaults.buttonColors(
                containerColor = SettingsPrimary,
                contentColor = SettingsOnPrimary
            )
        ) {
            Text("Start together", style = MaterialTheme.typography.labelLarge)
        }

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

        // Celebrate the moment you connect — the same hearts as a reveal/streak.
        var celebrate by remember { mutableStateOf(true) }
        CelebrationOverlay(visible = celebrate, intensity = 2.4f, onFinished = { celebrate = false })
    }
}

// ── Shared avatar composable ──────────────────────────────────────────────────

@Composable
private fun PairAvatar(url: String, modifier: Modifier = Modifier) {
    val cleanUrl = url.takeIf { it.isNotBlank() }
    if (cleanUrl != null) {
        AsyncImage(
            model = cleanUrl,
            contentDescription = null,
            contentScale = ContentScale.Crop,
            placeholder = rememberVectorPainter(Icons.Filled.Person),
            error = rememberVectorPainter(Icons.Filled.Person),
            modifier = modifier
                .clip(CircleShape)
                .border(4.dp, Color.White, CircleShape)
                .background(SettingsSoft)
        )
    } else {
        // No photo yet — warm pastel placeholder rather than a flat grey chip.
        Box(
            modifier = modifier
                .clip(CircleShape)
                .border(4.dp, Color.White, CircleShape)
                .background(SettingsSoft),
            contentAlignment = Alignment.Center
        ) {
            Icon(
                Icons.Filled.Person,
                contentDescription = null,
                tint = SettingsPrimary,
                modifier = Modifier.fillMaxSize(0.5f)
            )
        }
    }
}
