package com.tencent.qian.webview.demo

import android.app.AlertDialog
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import com.tencent.qian.webview.TencentQianWebView
import com.tencent.qian.webview.TencentQianWebViewPrewarmer
import com.tencent.qian.webview.model.PrewarmConfig
import com.tencent.qian.webview.model.PrewarmEnvironment
import com.tencent.qian.webview.model.PrewarmLevel
import com.tencent.qian.webview.model.SdkEvent
import com.tencent.qian.webview.model.SignAction
import com.tencent.qian.webview.model.SignCallback
import com.tencent.qian.webview.model.SignResult
import com.tencent.qian.webview.model.SignResultStatus
import com.tencent.qian.webview.model.TencentQianWebViewConfig

/**
 * Demo 主页:
 *
 * - 顶部 EditText:粘贴客户后端发起的真实 flowId URL
 * - 三按钮:
 *   1. 容器模式打开签署页
 *   2. 配置模式改造既有 WebView
 *   3. 打开自检页(beta URL)
 * - 底部 TextView:实时打印最近一次 [SignResult] / [SdkEvent]
 */
class MainActivity : AppCompatActivity() {

    private lateinit var urlInput: EditText
    private lateinit var output: TextView
    private lateinit var prewarmBizTypeInput: EditText
    private lateinit var prewarmBizTypeSpinner: Button
    private val bizTypeOptions = mutableListOf("single-sign", "batch-sign", "enterprise-register", "join-enterprise")

    private val callback = object : SignCallback {
        override fun onSignResult(result: SignResult) {
            log("⮞ SignResult action=${result.action} result=${result.result} flowId=${result.flowId} extras=${result.extras}")

            // 演示客户读取 action 的推荐写法:用常量比对,else 分支兜底未来值
            val human = when (result.action) {
                SignAction.SIGN -> "签署"
                SignAction.FILL -> "填写"
                SignAction.REJECT_SIGN -> "拒签"
                SignAction.REJECT_FILL -> "拒填"
                SignAction.VIEW -> "查看"
                "" -> "无 action"
                else -> "未知 action(${result.action})"
            }
            val ok = result.result == SignResultStatus.SUCCESS
            Toast.makeText(this@MainActivity, "$human ${if (ok) "成功" else "未成功"}", Toast.LENGTH_LONG).show()
        }

        override fun onEvent(event: SdkEvent) {
            log("• ${event.javaClass.simpleName}: $event")

            // 演示:客户可在 onEvent 中根据事件类型做 UI 反馈
            when (event) {
                is SdkEvent.DownloadStart ->
                    Toast.makeText(this@MainActivity, "开始下载: ${event.url.substringAfterLast('/')}", Toast.LENGTH_SHORT).show()
                is SdkEvent.DownloadFailed ->
                    Toast.makeText(this@MainActivity, "下载失败: ${event.reason}", Toast.LENGTH_SHORT).show()
                is SdkEvent.RenderProcessGone ->
                    Toast.makeText(this@MainActivity, "页面异常,正在恢复…", Toast.LENGTH_SHORT).show()
                else -> Unit
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        WindowCompat.setDecorFitsSystemWindows(window, true)
        setContentView(R.layout.activity_main)

        urlInput = findViewById(R.id.url_input)
        output = findViewById(R.id.output)
        output.movementMethod = ScrollingMovementMethod()

        findViewById<Button>(R.id.btn_open_container).setOnClickListener { openContainer() }
        findViewById<Button>(R.id.btn_open_configurator).setOnClickListener { openConfigurator() }
        findViewById<Button>(R.id.btn_open_compatibility).setOnClickListener { openCompatibility() }

        prewarmBizTypeInput = findViewById(R.id.prewarm_biztype)
        findViewById<Button>(R.id.btn_prewarm_minimal).setOnClickListener { triggerPrewarm(PrewarmLevel.MINIMAL) }
        findViewById<Button>(R.id.btn_prewarm_light).setOnClickListener { triggerPrewarm(PrewarmLevel.LIGHT) }
        findViewById<Button>(R.id.btn_prewarm_heavy).setOnClickListener { triggerPrewarm(PrewarmLevel.HEAVY) }
        findViewById<Button>(R.id.btn_release_pool).setOnClickListener { handleReleasePool() }

        prewarmBizTypeSpinner = findViewById(R.id.prewarm_biztype_spinner)
        prewarmBizTypeSpinner.setOnClickListener {
            AlertDialog.Builder(this)
                .setTitle("选择 bizType")
                .setItems(bizTypeOptions.toTypedArray()) { _, which ->
                    prewarmBizTypeInput.setText(bizTypeOptions[which])
                }
                .show()
        }
        // 配置预热（UA 与 buildConfig 对齐，池实例才能复用）
        TencentQianWebViewPrewarmer.configure(
            PrewarmConfig(
                environment = PrewarmEnvironment.BETA,
                userAgentExtra = "qianwv-demo/1.0.0",
                preferredLanguage = "zh-CN"
            )
        )

        TencentQianWebViewPrewarmer.getMenuBizTypes { bizTypes ->
            runOnUiThread {
                bizTypeOptions.clear()
                bizTypeOptions.addAll(bizTypes)
            }
        }

        findViewById<View>(R.id.btn_clear_log).setOnClickListener { output.text = "" }
    }

    // ────────── 三按钮 ──────────

    private fun openContainer() {
        val url = urlInput.text.toString().trim()
        if (url.isEmpty()) {
            Toast.makeText(this, "请先粘贴 flowId URL", Toast.LENGTH_SHORT).show()
            return
        }
        TencentQianWebView.open(
            activity = this,
            url = url,
            config = TencentQianWebViewConfig(
                topBarTitle = "电子签署(容器模式)",
                userAgentExtra = "qianwv-demo/1.0.0",
                confirmBeforeClose = true
            ),
            callback = callback
        )
    }

    private fun openConfigurator() {
        val url = urlInput.text.toString().trim()
        if (url.isEmpty()) {
            Toast.makeText(this, "请先粘贴 flowId URL", Toast.LENGTH_SHORT).show()
            return
        }
        // 通过 IntentBridgeForDemo 把 URL + callback 传给 ConfiguratorDemoActivity
        ConfiguratorDemoActivity.start(this, url, callback)
    }

    private fun openCompatibility() {
        TencentQianWebView.openCompatibilityTest(
            activity = this,
            customUrl = null,            // 走 SDK 默认 beta URL
            callback = callback
        )
    }

    // ────────── 预热（真机验证） ──────────

    private fun triggerPrewarm(level: PrewarmLevel) {
        val bizType = prewarmBizTypeInput.text.toString().trim().ifEmpty { "single-sign" }
        try {
            when (level) {
                PrewarmLevel.MINIMAL -> {
                    TencentQianWebViewPrewarmer.prewarm(PrewarmLevel.MINIMAL)
                    log("[prewarm] MINIMAL (DNS) triggered")
                }
                PrewarmLevel.LIGHT -> {
                    TencentQianWebViewPrewarmer.prewarm(PrewarmLevel.LIGHT, bizType, this)
                    log("[prewarm] LIGHT (kernel init) bizType=$bizType triggered")
                }
                PrewarmLevel.HEAVY -> {
                    TencentQianWebViewPrewarmer.prewarm(PrewarmLevel.HEAVY, bizType, this)
                    log("[prewarm] HEAVY (off-screen pool) bizType=$bizType triggered")
                }
            }
            Toast.makeText(this, "已触发预热", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            log("[prewarm] failed: ${e.message}")
        }
    }

    private fun handleReleasePool() {
        TencentQianWebViewPrewarmer.releaseAll()
        log("[prewarm] pool released (releaseAll)")
        Toast.makeText(this, "已释放预热池", Toast.LENGTH_SHORT).show()
    }

    /**
     * 【接入方示范】业务入口页销毁 == 业务流程结束 → 释放预热池。
     *
     * 建议在承载签署流程的业务入口页/会话终点（如本 Activity 的 onDestroy）调用 releaseAll：
     * 它会销毁预热 WebView 实例 并重置去重状态，使预热系统回到初始态——
     * 这样用户下次再进入同一业务流程时，prewarm 能重新生效。
     * 若只想临时回收内存、仍保留“本会话已预热过”的去重记账，则改用 release()。
     */
    override fun onDestroy() {
        super.onDestroy()
        TencentQianWebViewPrewarmer.releaseAll()
    }

    private fun log(line: String) {
        runOnUiThread {
            output.append(line)
            output.append("\n")
        }
    }
}
