package com.example.defenseapplication.home

import android.content.Intent
import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.defenseapplication.R
import com.example.defenseapplication.databinding.AddDeviceActivityBinding
import com.example.defenseapplication.databinding.ConnectDeviceActivityBinding
import com.gyf.immersionbar.ImmersionBar
//连接设备
class ConnectDeviceActivity : AppCompatActivity() {

    private lateinit var binding: ConnectDeviceActivityBinding
    private val handler = Handler(Looper.getMainLooper())
    // 每一帧对应的步骤文字和提示
    // 用 lazy 延迟初始化
    private val steps: List<StepData> by lazy {
        listOf(
            StepData(getString(R.string.bluetooth_keep_enabled), getString(R.string.transmit_info_to_device), getString(R.string.device_connect_network)),
            StepData(getString(R.string.bluetooth_keep_enabled), getString(R.string.device_connect_near_router), ""),
            StepData(getString(R.string.keep_device_near_router), "", "")
        )
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ConnectDeviceActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .titleBar(binding.topBar)
            .init()
        binding.ivBack.setOnClickListener {
            finish()
        }
        startFrameAnimation()
    }
    private fun startFrameAnimation() {
        // 设置动画资源
        binding.ivAnimation.setImageResource(R.drawable.device_wifi_animation)
        val animDrawable = binding.ivAnimation.drawable as AnimationDrawable

        // 监听每一帧的切换（AnimationDrawable 没有直接的回调，通过 Handler 定时更新文字）
        var frameIndex = 0
        val totalFrames = steps.size

        // 先显示第一帧对应的文字
        updateTextForFrame(0)

        // 开始动画
        animDrawable.start()

        // 每隔对应帧的时长来更新文字（必须与动画中每帧 duration 一致）
        val frameDurations = listOf(1500L, 1500L, 1500L) // 与 xml 中的 duration 对应
        val runnable = object : Runnable {
            override fun run() {
                frameIndex++
                if (frameIndex < totalFrames) {
                    updateTextForFrame(frameIndex)
                    handler.postDelayed(this, frameDurations[frameIndex])
                } else {
                    // 动画播放完毕，进行下一步操作（比如跳转或显示设备列表）
                    onAnimationComplete()
                }
            }
        }
        // 第一帧文字已经显示，所以延迟第一帧时长后再切换到第二帧
        handler.postDelayed(runnable, frameDurations[0])
    }

    private fun updateTextForFrame(index: Int) {
        val step = steps[index]
        binding.tvStepText.text = step.text
        binding.tvHint.text = step.hint
        binding.tvDeviceName.text = step.deviceName
    }

    private fun onAnimationComplete() {
        // 动画结束后的逻辑，显示“扫描完成”并跳转
        // 隐藏原来的动画相关视图
        binding.ivAnimation.visibility = View.GONE
        binding.tvStepText.visibility = View.GONE
        binding.tvHint.visibility = View.GONE
        binding.tvDeviceName.visibility = View.GONE
        // 显示图片 + 文字的布局
        val successLayout = binding.successLayout
        successLayout.visibility = View.VISIBLE

        // 跳转到下一个界面或关闭当前页面
        // 使用 Handler 延迟跳转
        Handler(Looper.getMainLooper()).postDelayed({
            val wifiName = intent.getStringExtra("wifi_name") ?: ""
            val wifiPassword = intent.getStringExtra("wifi_password") ?: ""
            startActivity(Intent(this, SetNameActivity::class.java).apply {
                putExtra("wifi_name", wifiName)
                putExtra("wifi_password", wifiPassword)
            })
            finish()
        }, 1000) // 1秒后跳转
    }

    data class StepData(val text: String, val hint: String, val deviceName: String)

    override fun onPause() {
        super.onPause()
        handler.removeCallbacksAndMessages(null)
        (binding.ivAnimation.drawable as? AnimationDrawable)?.stop()
    }
}