package app.dudu.app

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.view.inputmethod.InputMethodManager
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
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.design.DText
import app.dudu.design.IconCheck
import app.dudu.design.IconUser
import app.dudu.design.LocalDuduPalette
import app.dudu.net.ApiException
import app.dudu.net.DuduApi
import kotlinx.coroutines.launch

/**
 * 我的页（13B）：账户卡 / 试用进度 / 权限自检 / 入口（购买、反馈、退出）。
 * 未登录 = 游客态：试用剩余 + 登录引导。
 */
@Composable
fun MineScreen(
    refreshKey: Int,
    onLogin: () -> Unit,
    onBuy: () -> Unit,
    onFeedback: () -> Unit,
) {
    val p = LocalDuduPalette.current
    val context = LocalContext.current
    val repo = remember { AccountRepository.get(context) }
    val account by repo.snapshot.collectAsState()
    val scope = rememberCoroutineScope()

    val imeEnabled = remember(refreshKey) { isImeEnabled(context) }
    val imeSelected = remember(refreshKey) { isImeSelected(context) }
    val micGranted = remember(refreshKey) { hasMicPermission(context) }

    // 进入页面 / 回前台时刷新 /v1/me（登录态下；离线 mock 会话不发请求）
    LaunchedEffect(refreshKey, account.token) {
        val token = account.token ?: return@LaunchedEffect
        if (repo.offlineMock) return@LaunchedEffect
        try {
            val me = DuduApi.me(token)
            repo.applyMe(
                userId = me.userId,
                nicknameMasked = me.nicknameMasked,
                balanceSeconds = me.balanceSeconds,
                trialDailyLimit = me.trialDailyLimit,
                trialUsedToday = me.trialUsedToday,
            )
        } catch (e: ApiException) {
            if (e.code == "UNAUTHORIZED") repo.markUnauthorized()
            // 网络失败静默：展示本地缓存
        }
    }

    Column(
        Modifier
            .fillMaxSize()
            .background(p.bgApp)
            .systemBarsPadding()
            .verticalScroll(rememberScrollState())
            .padding(horizontal = 24.dp),
    ) {
        TopBar("我的", onBack = null)
        VSpace(8)

        if (account.state == AccountState.GUEST) {
            // ── 游客态 ──
            DCard {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    AvatarCircle()
                    HSpace(12)
                    Column {
                        DText("未登录", 16.sp, p.text1, weight = FontWeight.Medium)
                        VSpace(4)
                        DText("登录后购买时长，余额不过期", 13.sp, p.text3)
                    }
                }
                VSpace(16)
                PrimaryButton("微信登录", onClick = onLogin)
            }
            VSpace(12)
            TrialCard(account.trialUsedTodaySeconds, account.trialDailyLimitSeconds)
        } else {
            // ── 登录态：账户卡 ──
            DCard {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    AvatarCircle()
                    HSpace(12)
                    Column(Modifier.weight(1f)) {
                        DText(account.nicknameMasked ?: "dudu 用户", 16.sp, p.text1, weight = FontWeight.Medium)
                        VSpace(4)
                        DText("时长余额 ${account.balanceSeconds / 60} 分钟 · 不过期", 13.sp, p.text2)
                    }
                    when (account.state) {
                        AccountState.OK -> Badge("余额充足", BadgeKind.POSITIVE)
                        AccountState.TRIAL -> Badge("试用中", BadgeKind.NEUTRAL)
                        else -> Badge("余额不足", BadgeKind.WARNING)
                    }
                }
            }
            VSpace(12)
            TrialCard(account.trialUsedTodaySeconds, account.trialDailyLimitSeconds)
        }

        VSpace(12)

        // ── 权限自检 ──
        DCard {
            DText("权限自检", 13.sp, p.text3)
            VSpace(6)
            CheckRow("输入法已启用", imeEnabled) {
                context.startActivity(Intent(Settings.ACTION_INPUT_METHOD_SETTINGS))
            }
            Divider1()
            CheckRow("已选为当前输入法", imeSelected) {
                val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.showInputMethodPicker()
            }
            Divider1()
            CheckRow("麦克风权限", micGranted) {
                context.startActivity(
                    Intent(
                        Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                        Uri.fromParts("package", context.packageName, null),
                    ),
                )
            }
        }

        VSpace(12)

        // ── 入口 ──
        DCard {
            ListRow("购买时长") { if (account.state == AccountState.GUEST) onLogin() else onBuy() }
            Divider1()
            ListRow("反馈问题") { if (account.state == AccountState.GUEST) onLogin() else onFeedback() }
            if (account.state != AccountState.GUEST) {
                Divider1()
                ListRow("退出登录", danger = true) {
                    val token = account.token
                    repo.logout()
                    if (token != null) scope.launch { DuduApi.logout(token) }
                }
            }
        }

        // ── 离线 mock 开关（debug 包）：无后端时手动切四态联调键盘 ──
        if (BuildConfig.DEBUG) {
            VSpace(28)
            DText("账户状态 · 离线联调", 13.sp, p.text3)
            VSpace(8)
            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                StateChip("ok", account.state == AccountState.OK) { repo.setMockState(AccountState.OK) }
                StateChip("trial", account.state == AccountState.TRIAL) { repo.setMockState(AccountState.TRIAL) }
                StateChip("guest", account.state == AccountState.GUEST) { repo.setMockState(AccountState.GUEST) }
                StateChip("quota", account.state == AccountState.QUOTA) { repo.setMockState(AccountState.QUOTA) }
            }
        }
        VSpace(40)
    }
}

@Composable
private fun AvatarCircle() {
    val p = LocalDuduPalette.current
    Box(
        Modifier
            .size(44.dp)
            .clip(CircleShape)
            .background(p.accentSoft),
        contentAlignment = Alignment.Center,
    ) {
        IconUser(22.dp, p.accentText)
    }
}

/** 今日免费试用卡：用量 mono + 进度条。 */
@Composable
private fun TrialCard(usedSeconds: Int, limitSeconds: Int) {
    val p = LocalDuduPalette.current
    val limit = if (limitSeconds > 0) limitSeconds else 180
    DCard {
        Row(verticalAlignment = Alignment.CenterVertically) {
            DText("今日免费试用", 14.sp, p.text1)
            Spacer(Modifier.weight(1f))
            DText("${usedSeconds / 60} / ${limit / 60} 分钟", 13.sp, p.text2, mono = true)
        }
        VSpace(10)
        DProgressBar(usedSeconds.toFloat() / limit)
    }
}

/** 权限自检行：正常绿对勾，异常红色"去开启 ›"。 */
@Composable
private fun CheckRow(title: String, ok: Boolean, onFix: () -> Unit) {
    val p = LocalDuduPalette.current
    val src = remember { MutableInteractionSource() }
    Row(
        Modifier
            .fillMaxWidth()
            .clickable(interactionSource = src, indication = null, enabled = !ok, onClick = onFix)
            .padding(vertical = 13.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        DText(title, 14.sp, p.text1)
        Spacer(Modifier.weight(1f))
        if (ok) {
            IconCheck(15.dp, p.positive)
        } else {
            DText("去开启 ›", 13.sp, p.danger)
        }
    }
}
