package app.dudu.app

import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import app.dudu.data.AccountRepository
import app.dudu.data.AccountState
import app.dudu.design.DuduDesign

/** 主 App 路由（简单状态路由，页面少且层级浅，不引 Navigation 依赖）。 */
enum class Route { ONBOARDING, LOGIN, MINE, BUY, FEEDBACK }

/**
 * 主 App（13B/13C/13F）：
 *  - 启用引导三步（输入法 / 麦克风 / 切换试用），完成进我的页
 *  - 微信登录（mock OpenSDK，见 wechat/WechatAuth.kt）
 *  - 我的页（账户卡 / 试用进度 / 权限自检 / 入口）
 *  - 购买时长（packs / 订单 / mock 微信支付，见 pay/PayClient.kt）
 *  - 反馈问题（multipart 提交）
 * 键盘经 EXTRA_DEST 深链进入对应页（login / buy / permission / home）。
 */
class MainActivity : ComponentActivity() {

    private var resumeTick by mutableIntStateOf(0)
    private var route by mutableStateOf(Route.MINE)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        route = routeFor(intent.getStringExtra(EXTRA_DEST))
        setContent {
            DuduDesign {
                Root(
                    route = route,
                    dest = intent.getStringExtra(EXTRA_DEST),
                    refreshKey = resumeTick,
                    onNavigate = { route = it },
                )
            }
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        route = routeFor(intent.getStringExtra(EXTRA_DEST))
    }

    override fun onResume() {
        super.onResume()
        resumeTick++ // 从系统设置返回后触发重查启用/权限状态
    }

    /** 键盘深链 → 落地页；冷启动按引导完成度决定。 */
    private fun routeFor(dest: String?): Route {
        val guest = AccountRepository.get(this).snapshot.value.state == AccountState.GUEST
        return when (dest) {
            "login" -> Route.LOGIN
            "buy" -> if (guest) Route.LOGIN else Route.BUY
            "permission" -> Route.ONBOARDING
            else -> if (setupComplete(this)) Route.MINE else Route.ONBOARDING
        }
    }

    companion object {
        const val EXTRA_DEST = "dest" // login | buy | permission | home
    }
}

@Composable
private fun Root(
    route: Route,
    dest: String?,
    refreshKey: Int,
    onNavigate: (Route) -> Unit,
) {
    // 二级页返回我的页（我的/引导页交给系统默认返回 = 退出）
    if (route == Route.LOGIN || route == Route.BUY || route == Route.FEEDBACK) {
        BackHandler { onNavigate(Route.MINE) }
    }

    when (route) {
        Route.ONBOARDING -> OnboardingScreen(
            dest = dest,
            refreshKey = refreshKey,
            onDone = { onNavigate(Route.MINE) },
        )
        Route.LOGIN -> LoginScreen(
            onLoggedIn = { onNavigate(if (dest == "buy") Route.BUY else Route.MINE) },
            onBack = { onNavigate(Route.MINE) },
        )
        Route.MINE -> MineScreen(
            refreshKey = refreshKey,
            onLogin = { onNavigate(Route.LOGIN) },
            onBuy = { onNavigate(Route.BUY) },
            onFeedback = { onNavigate(Route.FEEDBACK) },
        )
        Route.BUY -> BuyScreen(
            refreshKey = refreshKey,
            onBack = { onNavigate(Route.MINE) },
        )
        Route.FEEDBACK -> FeedbackScreen(
            onBack = { onNavigate(Route.MINE) },
        )
    }
}
