package com.example.defenseapplication.home

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.example.defenseapplication.R
import com.example.defenseapplication.adapter.AddDeviceAdapter
import com.example.defenseapplication.adapter.Device
import com.example.defenseapplication.databinding.AddDeviceActivityBinding
import com.gyf.immersionbar.ImmersionBar
import com.maning.mlkitscanner.scan.MNScanManager
import com.maning.mlkitscanner.scan.callback.act.MNScanCallback

//添加设备页面
class AddDeviceActivity : AppCompatActivity() {

    private lateinit var binding: AddDeviceActivityBinding
    private lateinit var adapter: AddDeviceAdapter
    private val mainHandler = Handler(Looper.getMainLooper())

    private val requestPermissionsLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val cameraGranted = permissions[Manifest.permission.CAMERA] ?: false

        val storageGranted = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions[Manifest.permission.READ_MEDIA_IMAGES] ?: false
        } else {
            permissions[Manifest.permission.READ_EXTERNAL_STORAGE] ?: false
        }

        if (cameraGranted && storageGranted) {
            startScan()
        } else {
            Toast.makeText(this, R.string.permission_denied, Toast.LENGTH_SHORT).show()
        }
    }

    private fun checkPermissionsAndScan() {
        val cameraPermission = ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.CAMERA
        )

        val storagePermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_MEDIA_IMAGES
            )
        } else {
            ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        }

        if (cameraPermission == PackageManager.PERMISSION_GRANTED &&
            storagePermission == PackageManager.PERMISSION_GRANTED) {
            startScan()
        } else {
            val permissionsToRequest = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                arrayOf(
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_MEDIA_IMAGES
                )
            } else {
                arrayOf(
                    Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
            }
            requestPermissionsLauncher.launch(permissionsToRequest)
        }
    }

    private fun startScan() {
        MNScanManager.startScan(this, object: MNScanCallback {
            override fun onActivityResult(resultCode: Int, data: Intent?) {
                when (resultCode) {
                    MNScanManager.RESULT_SUCCESS -> {
                        val result = data?.getStringArrayListExtra(MNScanManager.INTENT_KEY_RESULT_SUCCESS)
                        if (!result.isNullOrEmpty()) {
                            ToastUtils.showToast(this@AddDeviceActivity, "扫码成功: $result")
                        } else {
                            ToastUtils.showToast(this@AddDeviceActivity, "扫码结果为空")
                        }
                    }
                    MNScanManager.RESULT_FAIL -> {
                        val error = data?.getStringExtra(MNScanManager.INTENT_KEY_RESULT_ERROR)
                        ToastUtils.showToast(this@AddDeviceActivity, "扫码失败: $error")
                    }
                    MNScanManager.RESULT_CANCLE -> {
                        ToastUtils.showToast(this@AddDeviceActivity, "扫码取消")
                    }
                }
            }
        })
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = AddDeviceActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .titleBar(binding.topBar)
            .init()
        binding.ivBack.setOnClickListener {
            finish()
        }

        binding.btnScanAdd.setOnClickListener {
            checkPermissionsAndScan()
        }

        // 开始播放扫描动画，动画结束后再显示设备列表
        startScanAnimationThenShowList()
    }

    private fun startScanAnimationThenShowList() {
        // 显示动画层
        binding.animationContainer.visibility = View.VISIBLE
        binding.rvDevices.visibility = View.GONE

        // 设置帧动画并启动
        binding.ivScanAnimation.setImageResource(R.drawable.device_frame_animation)
        val scanDrawable = binding.ivScanAnimation.drawable
        if (scanDrawable is android.graphics.drawable.AnimationDrawable) {
            scanDrawable.start()
        }

        // 模拟扫描过程
        mainHandler.postDelayed({
            // 停止动画
            (binding.ivScanAnimation.drawable as? android.graphics.drawable.AnimationDrawable)?.stop()
            // 隐藏动画层，显示列表
            binding.animationContainer.visibility = View.GONE
            binding.rvDevices.visibility = View.VISIBLE
            setupDeviceList() // 加载设备列表
        }, 3000) // 动画播放时长，可根据实际帧动画总时长调整
    }

    private fun setupDeviceList() {
        val devices = listOf(
            Device(getString(R.string.smart_hanging_defense), "device1"),
            Device(getString(R.string.smart_defense_device), "device2")
        )

        if (devices.isEmpty()) {

            binding.rvDevices.visibility = View.GONE
        } else {

            binding.rvDevices.visibility = View.VISIBLE

            binding.rvDevices.layoutManager = GridLayoutManager(this, 2)
            adapter = AddDeviceAdapter(devices) { device ->
                val intent = Intent(this, AddFamilyActivity::class.java)
                intent.putExtra("device_name", device.name)
                startActivity(intent)
            }
            binding.rvDevices.adapter = adapter
        }
    }
    override fun onPause() {
        super.onPause()
        // 停止所有可见 item 的动画
        for (i in 0 until binding.rvDevices.childCount) {
            val child = binding.rvDevices.getChildAt(i)
            val holder = binding.rvDevices.getChildViewHolder(child) as? AddDeviceAdapter.ViewHolder
            holder?.stopAnimation()
        }
    }

    override fun onResume() {
        super.onResume()
        // 重新启动所有可见 item 的动画
        for (i in 0 until binding.rvDevices.childCount) {
            val child = binding.rvDevices.getChildAt(i)
            val holder = binding.rvDevices.getChildViewHolder(child) as? AddDeviceAdapter.ViewHolder
            holder?.startAnimation()
        }
    }
}