package com.aiosman.ravenow.ui.account

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.padding
import androidx.compose.material3.Text
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.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.AppStore
import com.aiosman.ravenow.Messaging
import com.aiosman.ravenow.R
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.NavigationRoute
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

@Composable
fun RemoveAccountScreen() {
    val appColors = LocalAppTheme.current
    val navController = LocalNavController.current
    var inputPassword by remember { mutableStateOf("") }
    var passwordError by remember { mutableStateOf<String?>(null) }
    val scope = rememberCoroutineScope()
    val context = LocalContext.current
    
    // 暗色模式下的 hint 文本颜色
    val isDarkMode = AppState.darkMode
    val hintColor = if (isDarkMode) {
        Color(0xFFFFFFFF).copy(alpha = 0.7f)
    } else {
        null // 使用默认颜色
    }

    fun removeAccount(password: String) {
        // 使用通用密码校验器
        val passwordValidation = PasswordValidator.validateCurrentPassword(password, context)
        if (!passwordValidation.isValid) {
            passwordError = passwordValidation.errorMessage
            return
        }

        scope.launch {
            try {
                val accountService = AccountServiceImpl()
                accountService.removeAccount(password)
                Messaging.unregisterDevice(context)
                AppStore.apply {
                    token = null
                    rememberMe = false
                    saveData()
                }
                //返回到登录页面
                navController.navigate(NavigationRoute.Login.route) {
                    popUpTo(NavigationRoute.Login.route) {
                        inclusive = true
                    }
                }
                //重置AppState
                AppState.ReloadAppState(context)
                Toast.makeText(context, "Account has been deleted", Toast.LENGTH_SHORT).show()
            } catch (e: ServiceException) {
                passwordError = "Incorrect  password"
               // e.errorType.showToast(context)
            }  catch (e: Exception) {
                e.printStackTrace()
                Toast.makeText(context, "An error occurred. Please try again.", Toast.LENGTH_SHORT).show()
            }
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(appColors.background),
    ) {
        StatusBarSpacer()
        Box(
            modifier = Modifier.padding(horizontal = 24.dp, vertical = 16.dp)
        ) {
            NoticeScreenHeader(
                title = stringResource(R.string.remove_account),
                moreIcon = false
            )
        }
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(horizontal = 24.dp, vertical = 16.dp)
                .background(appColors.background),
        ) {
            Box(
                modifier = Modifier
                    .padding(bottom = 32.dp, top = 16.dp)
                    .fillMaxWidth(),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    stringResource(R.string.remove_account_desc),
                    fontSize = 16.sp,
                    modifier = Modifier.fillMaxWidth(),
                    textAlign = TextAlign.Center,
                    color = appColors.text
                )
            }
            TextInputField(
                modifier = Modifier.fillMaxWidth(),
                text = inputPassword,
                onValueChange = {
                    inputPassword = it
                    if (passwordError != null) {
                        passwordError = null
                    }
                },
                password = true,
                hint = stringResource(R.string.remove_account_password_hint),
                error = passwordError,
                customHintColor = hintColor
            )

            Spacer(modifier = Modifier.weight(1f))
            ActionButton(
                text = stringResource(R.string.remove_account),
                fullWidth = true,
                enabled = true,
                click = {
                    removeAccount(inputPassword)
                }
            )
        }
    }
}
