package id.iiyh.inatrading.feature.profile.presentation

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.animateScrollBy
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import androidx.compose.material.icons.outlined.MoreVert
import androidx.compose.material.icons.outlined.Shield
import androidx.compose.material.icons.outlined.Visibility
import androidx.compose.material.icons.outlined.VisibilityOff
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
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.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import id.iiyh.inatrading.R
import id.iiyh.inatrading.core.ui.components.InaPrimaryButton
import id.iiyh.inatrading.core.ui.components.InaTextField
import id.iiyh.inatrading.core.ui.theme.AccentPurple
import id.iiyh.inatrading.core.ui.theme.AccentPurpleContainer
import id.iiyh.inatrading.core.ui.theme.Background
import id.iiyh.inatrading.core.ui.theme.BrandRed
import id.iiyh.inatrading.core.ui.theme.ManropeFontFamily
import id.iiyh.inatrading.core.ui.theme.OnSurface
import id.iiyh.inatrading.core.ui.theme.OnSurfaceVariant
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerHighest
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerLow
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerLowest
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@Composable
fun ChangePasswordScreen(
    onBack: () -> Unit,
    onLoggedOut: () -> Unit,
    viewModel: ChangePasswordViewModel = hiltViewModel(),
) {
    val uiState by viewModel.uiState.collectAsState()
    val snackbarHostState = remember { SnackbarHostState() }
    val successMessage = stringResource(R.string.change_password_success)
    val coroutineScope = rememberCoroutineScope()
    val listState = rememberLazyListState()
    val density = LocalDensity.current
    val desiredFieldTopPx = with(density) { 96.dp.toPx() }
    var oldPasswordTopPx by remember { mutableFloatStateOf(0f) }
    var newPasswordTopPx by remember { mutableFloatStateOf(0f) }
    var confirmPasswordTopPx by remember { mutableFloatStateOf(0f) }

    LaunchedEffect(uiState.infoMessage) {
        uiState.infoMessage?.let { message ->
            snackbarHostState.showSnackbar(message)
            viewModel.consumeInfoMessage()
        }
    }

    LaunchedEffect(uiState.isLoggedOut) {
        if (uiState.isLoggedOut) {
            onLoggedOut()
        }
    }

    Scaffold(
        topBar = { ChangePasswordTopBar(onBack = onBack) },
        snackbarHost = { SnackbarHost(snackbarHostState) },
        containerColor = Background,
        bottomBar = {
            Surface(
                shadowElevation = 8.dp,
                color = Color.White.copy(alpha = 0.92f),
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 24.dp, vertical = 16.dp),
                    contentAlignment = Alignment.Center,
                ) {
                    InaPrimaryButton(
                        text = stringResource(R.string.change_password_save),
                        onClick = { viewModel.onSaveClick(successMessage) },
                        isLoading = uiState.isSaving,
                    )
                }
            }
        },
    ) { innerPadding ->
        ChangePasswordContent(
            uiState = uiState,
            onOldPasswordChange = viewModel::onOldPasswordChange,
            onNewPasswordChange = viewModel::onNewPasswordChange,
            onConfirmPasswordChange = viewModel::onConfirmPasswordChange,
            onToggleOldPasswordVisibility = viewModel::toggleOldPasswordVisibility,
            onToggleNewPasswordVisibility = viewModel::toggleNewPasswordVisibility,
            onToggleConfirmPasswordVisibility = viewModel::toggleConfirmPasswordVisibility,
            listState = listState,
            oldPasswordModifier = Modifier.onGloballyPositioned {
                oldPasswordTopPx = it.positionInRoot().y
            },
            newPasswordModifier = Modifier.onGloballyPositioned {
                newPasswordTopPx = it.positionInRoot().y
            },
            confirmPasswordModifier = Modifier.onGloballyPositioned {
                confirmPasswordTopPx = it.positionInRoot().y
            },
            onOldPasswordFocused = {
                coroutineScope.launch {
                    delay(150)
                    scrollFieldNearTop(
                        listState = listState,
                        fieldTopPx = oldPasswordTopPx,
                        desiredTopPx = desiredFieldTopPx,
                    )
                }
            },
            onNewPasswordFocused = {
                coroutineScope.launch {
                    delay(150)
                    scrollFieldNearTop(
                        listState = listState,
                        fieldTopPx = newPasswordTopPx,
                        desiredTopPx = desiredFieldTopPx,
                    )
                }
            },
            onConfirmPasswordFocused = {
                coroutineScope.launch {
                    delay(150)
                    scrollFieldNearTop(
                        listState = listState,
                        fieldTopPx = confirmPasswordTopPx,
                        desiredTopPx = desiredFieldTopPx,
                    )
                }
            },
            modifier = Modifier.padding(innerPadding),
        )
    }
}

@Composable
private fun ChangePasswordTopBar(
    onBack: () -> Unit,
) {
    Surface(
        shadowElevation = 2.dp,
        color = Color.White.copy(alpha = 0.88f),
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 20.dp, vertical = 12.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(10.dp),
            ) {
                IconButton(onClick = onBack) {
                    Icon(
                        imageVector = Icons.AutoMirrored.Outlined.ArrowBack,
                        contentDescription = stringResource(R.string.favorite_back),
                        tint = BrandRed,
                    )
                }
                Text(
                    text = stringResource(R.string.app_name),
                    fontFamily = ManropeFontFamily,
                    fontWeight = FontWeight.Black,
                    fontSize = 20.sp,
                    color = BrandRed,
                )
            }
            IconButton(onClick = {}) {
                Icon(
                    imageVector = Icons.Outlined.MoreVert,
                    contentDescription = null,
                    tint = OnSurfaceVariant,
                )
            }
        }
    }
}

@Composable
private fun ChangePasswordContent(
    uiState: ChangePasswordUiState,
    onOldPasswordChange: (String) -> Unit,
    onNewPasswordChange: (String) -> Unit,
    onConfirmPasswordChange: (String) -> Unit,
    onToggleOldPasswordVisibility: () -> Unit,
    onToggleNewPasswordVisibility: () -> Unit,
    onToggleConfirmPasswordVisibility: () -> Unit,
    listState: androidx.compose.foundation.lazy.LazyListState,
    oldPasswordModifier: Modifier = Modifier,
    newPasswordModifier: Modifier = Modifier,
    confirmPasswordModifier: Modifier = Modifier,
    onOldPasswordFocused: () -> Unit = {},
    onNewPasswordFocused: () -> Unit = {},
    onConfirmPasswordFocused: () -> Unit = {},
    modifier: Modifier = Modifier,
) {
    val strength = rememberPasswordStrength(uiState.newPassword)

    LazyColumn(
        state = listState,
        modifier = modifier
            .fillMaxSize()
            .background(Background),
        contentPadding = PaddingValues(start = 24.dp, end = 24.dp, top = 20.dp, bottom = 120.dp),
        verticalArrangement = Arrangement.spacedBy(24.dp),
    ) {
        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(Color.Transparent),
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(220.dp)
                        .background(SurfaceContainerHighest.copy(alpha = 0.42f), RoundedCornerShape(bottomStart = 36.dp))
                )

                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(24.dp),
                    verticalArrangement = Arrangement.spacedBy(14.dp),
                ) {
                    Text(
                        text = stringResource(R.string.change_password_eyebrow),
                        style = MaterialTheme.typography.labelSmall,
                        color = AccentPurple,
                        fontWeight = FontWeight.Bold,
                    )
                    Text(
                        text = stringResource(R.string.change_password_title),
                        fontFamily = ManropeFontFamily,
                        fontWeight = FontWeight.ExtraBold,
                        fontSize = 40.sp,
                        color = OnSurface,
                        lineHeight = 44.sp,
                    )
                    Text(
                        text = stringResource(R.string.change_password_body),
                        style = MaterialTheme.typography.bodyMedium,
                        color = OnSurfaceVariant,
                    )
                }
            }
        }

        item {
            Column(
                modifier = Modifier.fillMaxWidth(),
                verticalArrangement = Arrangement.spacedBy(20.dp),
            ) {
                ChangePasswordField(
                    label = stringResource(R.string.change_password_old_label),
                    value = uiState.oldPassword,
                    onValueChange = onOldPasswordChange,
                    placeholder = stringResource(R.string.change_password_old_placeholder),
                    modifier = oldPasswordModifier,
                    isPasswordHidden = !uiState.oldPasswordVisible,
                    isError = uiState.errors.oldPassword != null,
                    errorMessage = when (uiState.errors.oldPassword) {
                        "required" -> stringResource(R.string.change_password_error_old_required)
                        else -> ""
                    },
                    onToggleVisibility = onToggleOldPasswordVisibility,
                    isSaving = uiState.isSaving,
                    onFocused = onOldPasswordFocused,
                )

                Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
                    ChangePasswordField(
                        label = stringResource(R.string.change_password_new_label),
                        value = uiState.newPassword,
                        onValueChange = onNewPasswordChange,
                        placeholder = stringResource(R.string.change_password_new_placeholder),
                        modifier = newPasswordModifier,
                        isPasswordHidden = !uiState.newPasswordVisible,
                        isError = uiState.errors.newPassword != null,
                        errorMessage = when (uiState.errors.newPassword) {
                            "required" -> stringResource(R.string.change_password_error_new_required)
                            "min_length" -> stringResource(R.string.change_password_error_min_length)
                            "must_differ" -> stringResource(R.string.change_password_error_must_differ)
                            else -> ""
                        },
                        onToggleVisibility = onToggleNewPasswordVisibility,
                        isSaving = uiState.isSaving,
                        onFocused = onNewPasswordFocused,
                    )
                    PasswordStrengthMeter(
                        score = strength.score,
                        label = strength.label,
                    )
                }

                ChangePasswordField(
                    label = stringResource(R.string.change_password_confirm_label),
                    value = uiState.confirmPassword,
                    onValueChange = onConfirmPasswordChange,
                    placeholder = stringResource(R.string.change_password_confirm_placeholder),
                    modifier = confirmPasswordModifier,
                    isPasswordHidden = !uiState.confirmPasswordVisible,
                    isError = uiState.errors.confirmPassword != null,
                    errorMessage = when (uiState.errors.confirmPassword) {
                        "mismatch" -> stringResource(R.string.change_password_error_confirmation)
                        else -> ""
                    },
                    onToggleVisibility = onToggleConfirmPasswordVisibility,
                    isSaving = uiState.isSaving,
                    onFocused = onConfirmPasswordFocused,
                )
            }
        }

        item {
            Surface(
                shape = RoundedCornerShape(24.dp),
                color = SurfaceContainerLowest,
                shadowElevation = 2.dp,
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(18.dp),
                    horizontalArrangement = Arrangement.spacedBy(14.dp),
                    verticalAlignment = Alignment.Top,
                ) {
                    Box(
                        modifier = Modifier
                            .size(42.dp)
                            .background(AccentPurpleContainer, CircleShape),
                        contentAlignment = Alignment.Center,
                    ) {
                        Icon(
                            imageVector = Icons.Outlined.Shield,
                            contentDescription = null,
                            tint = AccentPurple,
                            modifier = Modifier.size(20.dp),
                        )
                    }
                    Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
                        Text(
                            text = stringResource(R.string.change_password_tip_title),
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold,
                            color = OnSurface,
                        )
                        Text(
                            text = stringResource(R.string.change_password_tip_body),
                            style = MaterialTheme.typography.bodySmall,
                            color = OnSurfaceVariant,
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun ChangePasswordField(
    label: String,
    value: String,
    onValueChange: (String) -> Unit,
    placeholder: String,
    modifier: Modifier = Modifier,
    isPasswordHidden: Boolean,
    isError: Boolean,
    errorMessage: String,
    onToggleVisibility: () -> Unit,
    isSaving: Boolean,
    onFocused: () -> Unit = {},
) {
    Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
        Text(
            text = label,
            style = MaterialTheme.typography.labelSmall,
            color = OnSurfaceVariant,
            fontWeight = FontWeight.Bold,
        )
        InaTextField(
            value = value,
            onValueChange = onValueChange,
            modifier = modifier,
            placeholder = placeholder,
            isPassword = isPasswordHidden,
            isError = isError,
            errorMessage = errorMessage,
            onFocusChanged = {
                if (it.isFocused) onFocused()
            },
            trailingIcon = {
                Icon(
                    imageVector = if (isPasswordHidden) {
                        Icons.Outlined.Visibility
                    } else {
                        Icons.Outlined.VisibilityOff
                    },
                    contentDescription = null,
                    tint = OnSurfaceVariant,
                    modifier = Modifier
                        .size(20.dp)
                        .clickable(enabled = !isSaving, onClick = onToggleVisibility),
                )
            },
        )
    }
}

private suspend fun scrollFieldNearTop(
    listState: androidx.compose.foundation.lazy.LazyListState,
    fieldTopPx: Float,
    desiredTopPx: Float,
) {
    if (fieldTopPx <= 0f) return

    val scrollDelta = fieldTopPx - desiredTopPx
    if (scrollDelta > 0f) {
        listState.animateScrollBy(scrollDelta)
    }
}

@Composable
private fun PasswordStrengthMeter(
    score: Int,
    label: String,
) {
    val activeColor = when (score) {
        1 -> BrandRed
        2 -> Color(0xFFD97706)
        3 -> AccentPurple
        else -> Color(0xFF2E7D32)
    }

    Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            repeat(4) { index ->
                Box(
                    modifier = Modifier
                        .weight(1f)
                        .height(4.dp)
                        .background(
                            color = if (index < score) activeColor else SurfaceContainerLow,
                            shape = RoundedCornerShape(999.dp),
                        ),
                )
            }
            Text(
                text = label.uppercase(),
                style = MaterialTheme.typography.labelSmall,
                color = if (score == 0) OnSurfaceVariant else activeColor,
                fontWeight = FontWeight.Bold,
                textAlign = TextAlign.End,
            )
        }
    }
}

@Composable
private fun rememberPasswordStrength(password: String): PasswordStrengthUi {
    val score = buildList {
        if (password.length >= 8) add(Unit)
        if (password.any(Char::isUpperCase) || password.any(Char::isLowerCase)) add(Unit)
        if (password.any(Char::isDigit)) add(Unit)
        if (password.any { !it.isLetterOrDigit() } || password.length >= 12) add(Unit)
    }.size.coerceIn(0, 4)

    val labelRes = when (score) {
        0, 1 -> R.string.change_password_strength_weak
        2 -> R.string.change_password_strength_fair
        3 -> R.string.change_password_strength_good
        else -> R.string.change_password_strength_strong
    }

    return PasswordStrengthUi(
        score = score,
        label = stringResource(labelRes),
    )
}

private data class PasswordStrengthUi(
    val score: Int,
    val label: String,
)
