package app.dudu.app

import android.Manifest
import android.content.Context
import android.content.Intent
import android.provider.Settings
import android.view.inputmethod.InputMethodManager
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
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.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.unit.dp
import androidx.compose.ui.unit.sp
import app.dudu.data.MetricsQueue
import app.dudu.design.DText
import app.dudu.design.DuduLogoMark
import app.dudu.design.IconCheck
import app.dudu.design.LocalDuduPalette

/**
 * 启用引导三步（13B）：启用输入法 → 麦克风权限 → 切到 dudu 试一试。
 * 每步完成自动勾选（onResume 重查系统状态），全部完成后主按钮转"完成"进我的页。
 */
@Composable
fun OnboardingScreen(
    dest: String?,
    refreshKey: Int,
    onDone: () -> Unit,
) {
    val p = LocalDuduPalette.current
    val context = LocalContext.current
    val metrics = remember { MetricsQueue.get(context) }

    // refreshKey 变化（onResume）时重查系统状态
    val imeEnabled = remember(refreshKey) { isImeEnabled(context) }
    val imeSelected = remember(refreshKey) { isImeSelected(context) }
    var micGranted by remember(refreshKey) { mutableStateOf(hasMicPermission(context)) }

    val permissionLauncher = rememberLauncherForActivityResult(
        ActivityResultContracts.RequestPermission(),
    ) { granted -> micGranted = granted }

    val step = when {
        !imeEnabled -> 0
        !micGranted -> 1
        !imeSelected -> 2
        else -> 3 // 全部完成
    }

    // 漏斗埋点：步骤推进 + 键盘启用（一次性）
    LaunchedEffect(step) { metrics.track("onboarding.step", mapOf("step" to step)) }
    LaunchedEffect(imeEnabled) {
        if (imeEnabled) metrics.trackOnce("kb_enabled", "kb.enabled")
    }

    Column(
        Modifier
            .fillMaxSize()
            .background(p.bgApp)
            .systemBarsPadding()
            .verticalScroll(rememberScrollState())
            .padding(horizontal = 24.dp),
    ) {
        Spacer(Modifier.height(40.dp))
        DuduLogoMark(44.dp, p.accent)
        Spacer(Modifier.height(16.dp))
        DText("三步开启 dudu", 20.sp, p.text1, weight = FontWeight.SemiBold)
        Spacer(Modifier.height(6.dp))
        DText("按住说话，松开上屏", 14.sp, p.text2)
        Spacer(Modifier.height(24.dp))

        // 从键盘跳来的场景提示
        when (dest) {
            "permission" -> { ContextBanner("键盘请求开启麦克风权限"); Spacer(Modifier.height(20.dp)) }
            else -> Unit
        }

        StepCard(
            index = 1, title = "启用输入法", desc = "在系统设置中开启 dudu 语音输入",
            done = imeEnabled, active = step == 0,
        )
        Spacer(Modifier.height(12.dp))
        StepCard(
            index = 2, title = "开启麦克风权限", desc = "语音识别需要使用麦克风",
            done = micGranted, active = step == 1,
        )
        Spacer(Modifier.height(12.dp))
        StepCard(
            index = 3, title = "试一试", desc = "切到 dudu 键盘，按住说话",
            done = imeSelected, active = step == 2,
        )

        Spacer(Modifier.height(28.dp))

        // 每屏唯一蓝色主按钮，文案随步骤
        when (step) {
            0 -> PrimaryButton("去设置") {
                context.startActivity(Intent(Settings.ACTION_INPUT_METHOD_SETTINGS))
            }
            1 -> PrimaryButton("开启麦克风权限") {
                permissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
            }
            2 -> PrimaryButton("切换到 dudu 键盘") {
                val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.showInputMethodPicker()
            }
            else -> PrimaryButton("完成", onClick = onDone)
        }

        if (step in 1..2) {
            Spacer(Modifier.height(12.dp))
            GhostButton("先跳过，去我的页", onClick = onDone)
        }
        Spacer(Modifier.height(40.dp))
    }
}

/** 三步卡片：done（绿对勾 + positive-soft 图标底）/ active（1.5px accent 边）/ todo（opacity .62）。 */
@Composable
private fun StepCard(index: Int, title: String, desc: String, done: Boolean, active: Boolean) {
    val p = LocalDuduPalette.current
    Row(
        Modifier
            .fillMaxWidth()
            .alpha(if (!done && !active) 0.62f else 1f)
            .clip(RoundedCornerShape(14.dp))
            .background(p.surfaceCard)
            .border(
                width = if (active) 1.5.dp else 1.dp,
                color = if (active) p.accent else p.border1,
                shape = RoundedCornerShape(14.dp),
            )
            .padding(16.dp),
        horizontalArrangement = Arrangement.spacedBy(12.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Box(
            Modifier
                .size(28.dp)
                .clip(CircleShape)
                .background(if (done) p.positiveSoft else p.surface2),
            contentAlignment = Alignment.Center,
        ) {
            if (done) {
                IconCheck(14.dp, p.positive)
            } else {
                DText("$index", 13.sp, if (active) p.accentText else p.text3, weight = FontWeight.Medium)
            }
        }
        Column {
            DText(title, 15.sp, p.text1, weight = FontWeight.Medium)
            Spacer(Modifier.height(2.dp))
            DText(desc, 12.sp, p.text3)
        }
    }
}
