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 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.foundation.clickable
import androidx.compose.material3.Checkbox
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.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel

data class DeleteAccountUiState(
    val showConfirm: Boolean = false,
    val isDeleting: Boolean = false,
    val canDelete: Boolean = false,
    val acknowledged: Boolean = false,
    val error: String? = null,
    val navigateTo: String? = null,
    val needsReauth: Boolean = false,
    val reauthPassword: String = "",
    val isReauthing: Boolean = false,
    val isGoogleUser: Boolean = false
)

@HiltViewModel
class DeleteAccountViewModel @Inject constructor(
    private val authRepository: AuthRepository
) : ViewModel() {

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

    fun requestDelete() = _uiState.update {
        it.copy(showConfirm = true, isGoogleUser = authRepository.isGoogleAccount)
    }
    fun dismissDelete() = _uiState.update { it.copy(showConfirm = false) }
    fun dismissReauth() = _uiState.update { it.copy(needsReauth = false, reauthPassword = "", error = null) }
    fun setAcknowledged(value: Boolean) = _uiState.update { it.copy(acknowledged = value, canDelete = value) }
    fun onReauthPasswordChanged(pw: String) = _uiState.update { it.copy(reauthPassword = pw, error = null) }

    fun confirmDelete() {
        if (!uiState.value.canDelete) return
        viewModelScope.launch {
            _uiState.update { it.copy(showConfirm = false, isDeleting = true, error = null) }
            // Delete the auth account first. The onUserDelete Cloud Function fires
            // asynchronously and handles all cascading cleanup: couple unpair,
            // partner notification, Firestore subcollections, and Storage.
            // Doing auth deletion first means a RecentLoginRequired failure stops
            // us before any data is touched (prevents the half-deleted state).
            authRepository.deleteAccount()
                .onSuccess {
                    _uiState.update { it.copy(isDeleting = false, navigateTo = AppRoute.ONBOARDING) }
                }
                .onFailure { e ->
                    _uiState.update { it.copy(isDeleting = false) }
                    if (e is com.google.firebase.auth.FirebaseAuthRecentLoginRequiredException) {
                        _uiState.update { it.copy(needsReauth = true, error = null) }
                    } else {
                        _uiState.update { it.copy(error = e.message ?: "Could not delete account.") }
                    }
                }
        }
    }

    fun submitReauth() {
        val password = _uiState.value.reauthPassword
        val email = authRepository.currentUserEmail ?: return
        if (password.isBlank()) {
            _uiState.update { it.copy(error = "Enter your password to continue.") }
            return
        }
        viewModelScope.launch {
            _uiState.update { it.copy(isReauthing = true, error = null) }
            authRepository.reauthenticateWithEmail(email, password)
                .onSuccess {
                    _uiState.update { it.copy(isReauthing = false, needsReauth = false, reauthPassword = "", canDelete = true) }
                    confirmDelete()
                }
                .onFailure { e ->
                    _uiState.update {
                        it.copy(
                            isReauthing = false,
                            error = if (e.message?.contains("password", ignoreCase = true) == true ||
                                        e.message?.contains("credential", ignoreCase = true) == true)
                                "Incorrect password. Please try again."
                            else
                                e.message ?: "Re-authentication failed."
                        )
                    }
                }
        }
    }

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

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

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

    if (state.showConfirm) {
        AlertDialog(
            onDismissRequest = viewModel::dismissDelete,
            title = { Text("Delete your account?") },
            text = {
                Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    Text("This permanently removes your profile and sign-in. Your partner will be unpaired. This cannot be undone.")
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(8.dp),
                        modifier = Modifier
                            .fillMaxWidth()
                            .heightIn(min = 48.dp)
                            .clickable { viewModel.setAcknowledged(!state.acknowledged) }
                    ) {
                        Checkbox(
                            checked = state.acknowledged,
                            onCheckedChange = viewModel::setAcknowledged
                        )
                        Text(
                            text = "I understand this cannot be undone",
                            style = MaterialTheme.typography.bodyMedium
                        )
                    }
                }
            },
            confirmButton = {
                Button(
                    onClick = viewModel::confirmDelete,
                    enabled = state.canDelete,
                    colors = ButtonDefaults.buttonColors(
                        containerColor = SettingsDanger,
                        contentColor = Color.White
                    )
                ) {
                    Text("Delete", color = Color.White)
                }
            },
            dismissButton = {
                TextButton(onClick = viewModel::dismissDelete) { Text("Cancel") }
            }
        )
    }

    if (state.needsReauth) {
        AlertDialog(
            onDismissRequest = viewModel::dismissReauth,
            title = { Text("Confirm it's you") },
            text = {
                Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    if (state.isGoogleUser) {
                        Text(
                            "For security, please sign out and sign back in with Google, then try deleting your account again.",
                            style = MaterialTheme.typography.bodyMedium
                        )
                    } else {
                        Text(
                            "For security, re-enter your password before deleting your account.",
                            style = MaterialTheme.typography.bodyMedium
                        )
                        OutlinedTextField(
                            value = state.reauthPassword,
                            onValueChange = viewModel::onReauthPasswordChanged,
                            label = { Text("Password") },
                            singleLine = true,
                            visualTransformation = PasswordVisualTransformation(),
                            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
                            isError = state.error != null,
                            supportingText = state.error?.let { err ->
                                { Text(err, color = SettingsDanger) }
                            },
                            colors = OutlinedTextFieldDefaults.colors(
                                focusedBorderColor = SettingsDanger,
                                unfocusedBorderColor = SettingsMuted.copy(alpha = 0.4f),
                                cursorColor = SettingsDanger
                            ),
                            modifier = Modifier.fillMaxWidth()
                        )
                    }
                }
            },
            confirmButton = {
                if (state.isGoogleUser) {
                    TextButton(onClick = viewModel::dismissReauth) { Text("OK") }
                } else {
                    Button(
                        onClick = viewModel::submitReauth,
                        enabled = !state.isReauthing,
                        colors = ButtonDefaults.buttonColors(
                            containerColor = SettingsDanger,
                            contentColor = Color.White
                        )
                    ) {
                        if (state.isReauthing) {
                            CloserHeartLoader(size = 18.dp)
                        } else {
                            Text("Confirm", color = Color.White)
                        }
                    }
                }
            },
            dismissButton = {
                if (!state.isGoogleUser) {
                    TextButton(onClick = viewModel::dismissReauth) { Text("Cancel") }
                }
            }
        )
    }

    Scaffold(
        containerColor = Color.Transparent,
        modifier = Modifier.background(SettingsBackgroundBrush),
        topBar = {
            TopAppBar(
                title = { Text("Delete account", color = SettingsInk) },
                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 = "Deleting your account is permanent and cannot be reversed. Your profile, sign-in, and pairing will be removed immediately.",
                style = MaterialTheme.typography.bodyMedium,
                color = SettingsMuted
            )
            Text(
                text = "Your partner will be unpaired and can start fresh.",
                style = MaterialTheme.typography.bodyMedium,
                color = SettingsMuted
            )

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

            Spacer(Modifier.height(16.dp))

            Button(
                onClick = viewModel::requestDelete,
                enabled = !state.isDeleting,
                modifier = Modifier.fillMaxWidth().height(52.dp),
                shape = androidx.compose.foundation.shape.RoundedCornerShape(12.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = SettingsDanger,
                    contentColor = Color.White
                )
            ) {
                if (state.isDeleting) {
                    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                        CloserHeartLoader(size = 20.dp)
                        Text("Deleting…", color = Color.White)
                    }
                } else {
                    Text("Delete my account", color = Color.White, fontWeight = FontWeight.SemiBold)
                }
            }
        }
    }
}

@Preview
@Composable
fun DeleteAccountScreenPreview() {
    DeleteAccountScreen()
}
