package app.dudu.app

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
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.systemBarsPadding
import androidx.compose.foundation.shape.RoundedCornerShape
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.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
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 app.dudu.BuildConfig
import app.dudu.data.AccountRepository
import app.dudu.data.AccountState
import app.dudu.data.MetricsQueue
import app.dudu.design.DText
import app.dudu.design.DuduLogoMark
import app.dudu.design.LocalDuduPalette
import app.dudu.net.ApiException
import app.dudu.net.DuduApi
import app.dudu.wechat.wechatAuth
import kotlinx.coroutines.launch

/** 微信绿——全局唯一例外色（仅登录按钮，见设计核查清单）。 */

/**
 * 登录页（13B）：居中字标 + 底部微信绿胶囊按钮。
 * 登录流：WechatAuth.requestCode()（mock）→ POST /v1/auth/wechat → 存 JWT →
 * GET /v1/me 刷新余额 → 回调 onLoggedIn。
 */
@Composable
fun LoginScreen(onLoggedIn: () -> Unit, onBack: () -> Unit) {
    val p = LocalDuduPalette.current
    val context = LocalContext.current
    val repo = remember { AccountRepository.get(context) }
    val metrics = remember { MetricsQueue.get(context) }
    val scope = rememberCoroutineScope()

    var loading by remember { mutableStateOf(false) }
    var error by remember { mutableStateOf<String?>(null) }

    fun doLogin() {
        if (loading) return
        loading = true
        error = null
        scope.launch {
            try {
                val code = wechatAuth.requestCode() // TODO(wechat-sdk): mock → OpenSDK
                val login = DuduApi.loginWechat(code)
                repo.setLogin(login.token, login.user.userId, login.user.nicknameMasked)
                val me = DuduApi.me(login.token)
                repo.applyMe(
                    userId = me.userId,
                    nicknameMasked = me.nicknameMasked,
                    balanceSeconds = me.balanceSeconds,
                    trialDailyLimit = me.trialDailyLimit,
                    trialUsedToday = me.trialUsedToday,
                )
                metrics.track("login.success")
                onLoggedIn()
            } catch (e: ApiException) {
                error = e.message
            } finally {
                loading = false
            }
        }
    }

    Column(
        Modifier
            .fillMaxSize()
            .background(p.bgApp)
            .systemBarsPadding()
            .padding(horizontal = 24.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        Box(Modifier.padding(top = 4.dp).fillMaxWidth()) { TopBar("", onBack) }
        Spacer(Modifier.weight(1f))

        DuduLogoMark(64.dp, p.accent)
        Spacer(Modifier.height(16.dp))
        // TODO(font-outfit): 字标应为 Outfit 字体，拿到字体文件前用系统默认 + 加宽字距
        DText("dudu", 24.sp, p.text1, weight = FontWeight.SemiBold)
        Spacer(Modifier.height(8.dp))
        DText("大模型语音输入 · 说话即上屏", 14.sp, p.text2)

        Spacer(Modifier.weight(1f))

        NoticeText(error)
        Spacer(Modifier.height(14.dp))

        // 微信绿胶囊按钮（56dp，唯一例外色）
        run {
            val src = remember { MutableInteractionSource() }
            val pressed by src.collectIsPressedAsState()
            Box(
                Modifier
                    .fillMaxWidth()
                    .height(56.dp)
                    .alpha(if (loading) 0.6f else 1f)
                    .clip(RoundedCornerShape(999.dp))
                    .background(if (pressed) p.brandWechatPress else p.brandWechat)
                    .clickable(interactionSource = src, indication = null, enabled = !loading) { doLogin() },
                contentAlignment = Alignment.Center,
            ) {
                DText(if (loading) "登录中" else "微信一键登录", 16.sp, p.textOnAccent, weight = FontWeight.Medium)
            }
        }
        Spacer(Modifier.height(12.dp))
        DText(
            "登录即同意《用户协议》与《隐私政策》", 12.sp, p.text3,
            modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center,
        )

        // 离线 mock 开关：后端不可用时切假登录态联调键盘（仅 debug 包）
        if (BuildConfig.DEBUG) {
            Spacer(Modifier.height(16.dp))
            val src = remember { MutableInteractionSource() }
            DText(
                "离线联调 · 跳过登录", 12.sp, p.text3,
                modifier = Modifier
                    .clickable(interactionSource = src, indication = null) {
                        repo.setMockState(AccountState.TRIAL)
                        onLoggedIn()
                    }
                    .padding(8.dp),
            )
        }
        Spacer(Modifier.height(24.dp))
    }
}
