import android.widget.Toast
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.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.data.AccountService
import com.aiosman.ravenow.data.AccountServiceImpl
import com.aiosman.ravenow.data.ServiceException
import com.aiosman.ravenow.data.api.ErrorCode
import com.aiosman.ravenow.data.api.showToast
import com.aiosman.ravenow.data.api.toErrorMessage
import com.aiosman.ravenow.ui.comment.NoticeScreenHeader
import com.aiosman.ravenow.ui.composables.ActionButton
import com.aiosman.ravenow.ui.composables.StatusBarSpacer
import com.aiosman.ravenow.ui.composables.TextInputField
import com.aiosman.ravenow.utils.PasswordValidator
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 context = LocalContext.current
    val viewModel = remember { ChangePasswordViewModel() }
    var currentPassword by remember { mutableStateOf("") }
    var newPassword by remember { mutableStateOf("") }
    var confirmPassword 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) }
    val AppColors = LocalAppTheme.current
    fun validate(): Boolean {
        // 使用通用密码校验器校验当前密码
        val currentPasswordValidation = PasswordValidator.validateCurrentPassword(currentPassword, context)
        oldPasswordError = if (!currentPasswordValidation.isValid) currentPasswordValidation.errorMessage else null
        
        // 使用通用密码校验器校验新密码
        val newPasswordValidation = PasswordValidator.validatePassword(newPassword, context)
        passwordError = if (!newPasswordValidation.isValid) newPasswordValidation.errorMessage else null
        
        // 使用通用密码确认校验器
        val confirmPasswordValidation = PasswordValidator.validatePasswordConfirmation(newPassword, confirmPassword, context)
        confirmPasswordError = if (!confirmPasswordValidation.isValid) confirmPasswordValidation.errorMessage else null
        
        return passwordError == null && confirmPasswordError == null && oldPasswordError == null
    }
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(AppColors.background),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        StatusBarSpacer()
        Box(
            modifier = Modifier.padding(horizontal = 24.dp, vertical = 16.dp)
        ) {
            NoticeScreenHeader(
                title = stringResource(R.string.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 = stringResource(R.string.current_password),
                hint = stringResource(R.string.current_password_tip5),
                error = oldPasswordError
            )
            Spacer(modifier = Modifier.height(4.dp))
            TextInputField(
                text = newPassword,
                onValueChange = { newPassword = it },
                password = true,
                label = stringResource(R.string.new_password),
                hint = stringResource(R.string.new_password),
                error = passwordError
            )
            Spacer(modifier = Modifier.height(4.dp))
            TextInputField(
                text = confirmPassword,
                onValueChange = { confirmPassword = it },
                password = true,
                label = stringResource(R.string.confirm_new_password_tip1),
                hint = stringResource(R.string.new_password_tip1),
                error = confirmPasswordError
            )
            Spacer(modifier = Modifier.height(50.dp))
            ActionButton(
                modifier = Modifier
                    .width(345.dp),
                text = stringResource(R.string.lets_ride_upper),
            ) {
                if (validate()) {
                    scope.launch {
                        try {
                            viewModel.changePassword(currentPassword, newPassword)

                            navController.navigateUp()
                        } catch (e: ServiceException) {
                            when (e.errorType) {
                                ErrorCode.IncorrectOldPassword ->
                                    oldPasswordError = e.errorType.toErrorMessage(context)
                                else ->
                                    e.errorType.showToast(context)
                            }
                        } catch (e: Exception) {
                            Toast.makeText(context, e.message, Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }
        }

    }

}