import androidx.compose.foundation.background
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.padding
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
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.unit.dp
import com.aiosman.riderpro.LocalNavController
import com.aiosman.riderpro.R
import com.aiosman.riderpro.data.AccountService
import com.aiosman.riderpro.data.AccountServiceImpl
import com.aiosman.riderpro.ui.comment.NoticeScreenHeader
import com.aiosman.riderpro.ui.composables.ActionButton
import com.aiosman.riderpro.ui.composables.StatusBarSpacer
import com.aiosman.riderpro.ui.composables.TextInputField
import kotlinx.coroutines.launch

/**
 * 修改密码页面的 ViewModel
 */
class ChangePasswordViewModel {
    val accountService: AccountService = AccountServiceImpl()

    /**
     * 修改密码
     * @param currentPassword 当前密码
     * @param newPassword 新密码
     */
    suspend fun changePassword(currentPassword: String, newPassword: String) {
        accountService.changeAccountPassword(currentPassword, newPassword)
    }
}

/**
 * 修改密码页面
 */
@Composable
fun ChangePasswordScreen() {
    val viewModel = remember { ChangePasswordViewModel() }
    var currentPassword by remember { mutableStateOf("") }
    var newPassword by remember { mutableStateOf("") }
    var confirmPassword by remember { mutableStateOf("") }
    var errorMessage by remember { mutableStateOf("") }
    val scope = rememberCoroutineScope()
    val navController = LocalNavController.current
    var oldPasswordError by remember { mutableStateOf<String?>(null) }
    var confirmPasswordError by remember { mutableStateOf<String?>(null) }
    var passwordError by remember { mutableStateOf<String?>(null) }
    fun validate(): Boolean {
        oldPasswordError =
            if (currentPassword.isEmpty()) "Please enter your current password" else null
        passwordError = when {
            newPassword.length < 8 -> "Password must be at least 8 characters long"
            !newPassword.any { it.isDigit() } -> "Password must contain at least one digit"
            !newPassword.any { it.isUpperCase() } -> "Password must contain at least one uppercase letter"
            !newPassword.any { it.isLowerCase() } -> "Password must contain at least one lowercase letter"
            else -> null
        }
        confirmPasswordError =
            if (newPassword != confirmPassword) "Passwords do not match" else null
        return passwordError == null && confirmPasswordError == null && oldPasswordError == null
    }
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        StatusBarSpacer()
        Box(
            modifier = Modifier.padding(horizontal = 24.dp, vertical = 16.dp)
        ) {
            NoticeScreenHeader(
                title = "Change password",
                moreIcon = false
            )

        }
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 24.dp)
        ) {
            Spacer(modifier = Modifier.height(80.dp))
            TextInputField(
                text = currentPassword,
                onValueChange = { currentPassword = it },
                password = true,
                label = "Current password",
                hint = "Enter your current password",
                error = oldPasswordError
            )
            Spacer(modifier = Modifier.height(24.dp))
            TextInputField(
                text = newPassword,
                onValueChange = { newPassword = it },
                password = true,
                label = "New password",
                hint = "Enter your new password",
                error = passwordError
            )
            Spacer(modifier = Modifier.height(24.dp))
            TextInputField(
                text = confirmPassword,
                onValueChange = { confirmPassword = it },
                password = true,
                label = "Confirm new password",
                hint = "Enter your new password again",
                error = confirmPasswordError
            )
            Spacer(modifier = Modifier.height(80.dp))
            ActionButton(
                modifier = Modifier
                    .width(345.dp)
                    .height(48.dp),
                text = "LET'S RIDE".uppercase(),
                backgroundImage = R.mipmap.rider_pro_signup_red_bg
            ) {
                if (validate()) {
                    scope.launch {
                        try {
                            viewModel.changePassword(currentPassword, newPassword)
                            navController.popBackStack()
                        } catch (e: Exception) {
                            errorMessage = e.message ?: "An error occurred"
                        }
                    }
                }
            }
        }

    }

}