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.PaddingValues
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.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.ConstVars
import com.aiosman.ravenow.data.api.ErrorCode
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.DictService
import com.aiosman.ravenow.data.DictServiceImpl
import com.aiosman.ravenow.data.ServiceException
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 kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@Composable
fun ResetPasswordScreen() {
    var username by remember { mutableStateOf("") }
    val accountService: AccountService = AccountServiceImpl()
    val dictService: DictService = DictServiceImpl()
    val scope = rememberCoroutineScope()
    val context = LocalContext.current
    var isSendSuccess by remember { mutableStateOf<Boolean?>(null) }
    var isLoading by remember { mutableStateOf(false) }
    val navController = LocalNavController.current
    var usernameError by remember { mutableStateOf<String?>(null) }
    var countDown by remember { mutableStateOf<Int?>(null) }
    var countDownMax by remember { mutableStateOf(60) }
    val appColors = LocalAppTheme.current
    fun validate(): Boolean {
        if (username.isEmpty()) {
            usernameError = context.getString(R.string.text_error_email_required)
            return false
        }
        usernameError = null
        return true
    }

    LaunchedEffect(Unit) {
        try {
            dictService.getDictByKey(ConstVars.DIC_KEY_RESET_EMAIL_INTERVAL).let {
                countDownMax = it.value as? Int ?: 60
            }
        } catch (e: Exception) {
            countDownMax = 60
        }
    }

    fun startCountDown() {
        scope.launch {
            countDown = countDownMax
            while (countDown!! > 0) {
                delay(1000)
                countDown = countDown!! - 1
            }
            countDown = null
        }
    }

    fun resetPassword() {
        if (!validate()) return
        scope.launch {
            isLoading = true
            try {
                accountService.resetPassword(username)
                isSendSuccess = true
                startCountDown()
            } catch (e: ServiceException) {
                if (e.code == ErrorCode.USER_NOT_EXIST.code){
                    usernameError = context.getString(R.string.error_40002_user_not_exist)
                } else {
                    // 其他错误，不显示Toast
                    isSendSuccess = false
                }
            } catch (e: Exception) {
                // 异常错误，不显示Toast
                isSendSuccess = false
            } finally {
                isLoading = false
            }
        }
    }


    Column(
        modifier = Modifier.fillMaxSize().background(color = appColors.background)
    ) {
        StatusBarSpacer()
        Box(
            modifier = Modifier.padding(
                start = 16.dp,
                end = 16.dp,
                top = 16.dp,
                bottom = 0.dp
            )
        ) {
            NoticeScreenHeader(
                stringResource(R.string.recover_account_upper),
                moreIcon = false
            )
        }
        Spacer(modifier = Modifier.height(72.dp))
        Column(
            modifier = Modifier.padding(horizontal = 24.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 暗色模式下的 hint 文本颜色
            val isDarkMode = AppState.darkMode
            val hintColor = if (isDarkMode) {
                Color(0xFFFFFFFF).copy(alpha = 0.7f)
            } else {
                null // 使用默认颜色
            }
            
            TextInputField(
                text = username,
                onValueChange = { username = it },
                hint = stringResource(R.string.text_hint_email),
                enabled = !isLoading && countDown == null,
                error = usernameError,
                customHintColor = hintColor
            )
            Spacer(modifier = Modifier.height(16.dp))
            Box(
                modifier = Modifier.height(72.dp)
            ) {
                isSendSuccess?.let {
                    if (it) {
                        Text(
                            text = stringResource(R.string.reset_mail_send_success),
                            style = TextStyle(
                                color = appColors.text,
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Bold
                            ),
                            modifier = Modifier.fillMaxSize()
                        )
                    } else {
                        Text(
                            text = stringResource(R.string.reset_mail_send_failed),
                            style = TextStyle(
                                color = appColors.text,
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Bold
                            ),
                            modifier = Modifier.fillMaxSize()
                        )
                    }
                }
            }

            ActionButton(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(48.dp),
                text = if (countDown != null) {
                    stringResource(R.string.resend, "(${countDown})")
                } else {
                    stringResource(R.string.recover)
                },
                backgroundColor = Color(0xFF7C45ED), // 紫色背景
                loadingBackgroundColor = Color(0xFF7C45ED), // loading 时保持紫色
                disabledBackgroundColor = Color(0xFF7C45ED), // disabled 时保持紫色
                color = appColors.mainText,
                isLoading = isLoading && countDown == null, // 只在未发送成功时显示loading
                contentPadding = PaddingValues(0.dp),
                enabled = countDown == null,
            ) {
                resetPassword()
            }
            isSendSuccess?.let {
                Spacer(modifier = Modifier.height(16.dp))
                ActionButton(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(48.dp),
                    text = stringResource(R.string.back_upper),
                    backgroundColor = Color(0xFF7C45ED), // 紫色背景
                    color = Color.White, // 白色文字
                    contentPadding = PaddingValues(0.dp),
                ) {
                    navController.navigateUp()
                }

            }

        }
    }
}