package app.closer.ui.settings

import androidx.compose.foundation.background
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 dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
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 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.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.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import app.closer.ui.components.CloserHeartLoader
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel

data class RelationshipSettingsUiState(
    val showLeaveConfirm: Boolean = false,
    val isLeaving: Boolean = false,
    val error: String? = null,
    val navigateTo: String? = null
)

@HiltViewModel
class RelationshipSettingsViewModel @Inject constructor(
    private val authRepository: AuthRepository,
    private val coupleRepository: CoupleRepository
) : ViewModel() {

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

    fun requestLeave() = _uiState.update { it.copy(showLeaveConfirm = true) }
    fun dismissLeave() = _uiState.update { it.copy(showLeaveConfirm = false) }

    fun confirmLeave() {
        val uid = authRepository.currentUserId ?: return
        viewModelScope.launch {
            _uiState.update { it.copy(showLeaveConfirm = false, isLeaving = true, error = null) }
            coupleRepository.leaveCouple(uid)
                .onSuccess {
                    _uiState.update { it.copy(isLeaving = false, navigateTo = AppRoute.CREATE_INVITE) }
                }
                .onFailure { e ->
                    _uiState.update { it.copy(isLeaving = false, error = e.message ?: "Could not leave couple.") }
                }
        }
    }

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

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RelationshipSettingsScreen(
    onNavigate: (String) -> Unit = {},
    viewModel: RelationshipSettingsViewModel = hiltViewModel()
) {
    val state by viewModel.uiState.collectAsState()

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

    if (state.showLeaveConfirm) {
        AlertDialog(
            onDismissRequest = viewModel::dismissLeave,
            title = { Text("Leave this couple?") },
            text = {
                Text("Both you and your partner will be unpaired. Your conversation history stays in your account. This cannot be undone.")
            },
            confirmButton = {
                Button(
                    onClick = viewModel::confirmLeave,
                    enabled = !state.isLeaving,
                    colors = ButtonDefaults.buttonColors(
                        containerColor = SettingsDanger,
                        contentColor = Color.White
                    )
                ) {
                    Text("Leave", color = Color.White)
                }
            },
            dismissButton = {
                TextButton(onClick = viewModel::dismissLeave) { Text("Cancel") }
            }
        )
    }

    Scaffold(
        containerColor = Color.Transparent,
        modifier = Modifier.background(SettingsBackgroundBrush),
        topBar = {
            TopAppBar(
                title = { Text("Relationship", color = SettingsInk, maxLines = 1, overflow = TextOverflow.Ellipsis) },
                navigationIcon = {
                    IconButton(onClick = { onNavigate("back") }) {
                        Icon(
                            Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "Back",
                            tint = SettingsInk
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent)
            )
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .safeDrawingPadding()
                .navigationBarsPadding()
                .verticalScroll(rememberScrollState())
                .padding(padding)
                .padding(horizontal = 16.dp, vertical = 8.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Text(
                text = "Your relationship data stays private. Leaving unlinks you and your partner — it does not delete your account or answers.",
                style = MaterialTheme.typography.bodyMedium,
                color = SettingsMuted,
                maxLines = 4,
                overflow = TextOverflow.Ellipsis
            )

            state.error?.let { err ->
                Text(
                    text = err,
                    style = MaterialTheme.typography.bodySmall,
                    color = SettingsDanger,
                    maxLines = 3,
                    overflow = TextOverflow.Ellipsis
                )
            }

            Spacer(Modifier.height(16.dp))

            Button(
                onClick = viewModel::requestLeave,
                enabled = !state.isLeaving,
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(min = 52.dp),
                shape = androidx.compose.foundation.shape.RoundedCornerShape(12.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = SettingsDanger,
                    contentColor = Color.White
                )
            ) {
                if (state.isLeaving) {
                    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                        CloserHeartLoader(size = 20.dp)
                        Text("Leaving…", color = Color.White)
                    }
                } else {
                    Text("Leave this couple", color = Color.White, fontWeight = FontWeight.SemiBold)
                }
            }
        }
    }
}

@Preview
@Composable
fun RelationshipSettingsScreenPreview() {
    RelationshipSettingsScreen()
}
