package com.example.defenseapplication.liveVideo

import android.Manifest
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.net.wifi.ScanResult
import android.net.wifi.WifiManager
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.defenseapplication.R
import com.example.defenseapplication.adapter.WifiListAdapter
import com.example.defenseapplication.bean.DeviceBean
import com.example.defenseapplication.databinding.DialogWifiListBinding
import com.example.defenseapplication.databinding.WifiManagementActivityBinding
import com.example.defenseapplication.utils.DeviceIdEvent
import com.example.defenseapplication.utils.RetrofitNetwork
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

//WiFi管理
class WiFiManagementActivity : AppCompatActivity() {

    private lateinit var binding: WifiManagementActivityBinding
    private lateinit var wifiManager: WifiManager
    private lateinit var wifiScanReceiver: BroadcastReceiver
    private var popupWindow: PopupWindow? = null
    private var currentWifiName: String? = null

    companion object {
        const val EXTRA_WIFI_NAME = "wifi_name"
    }

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

        // 获取传递过来的WiFi名称
        currentWifiName = intent.getStringExtra(EXTRA_WIFI_NAME)
        if (!currentWifiName.isNullOrEmpty() && currentWifiName != getString(R.string.not_set)) {
            binding.etWifiName.setText(currentWifiName)
        }

        binding.ivBack.setOnClickListener {
            finish()
        }

        binding.btnSelectWifi.setOnClickListener {
            showWifiListDialog()
        }

        binding.etWifiName.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}

            override fun afterTextChanged(s: Editable?) {
                updateBottomButtonVisibility()
            }
        })

        binding.etWifiPassword.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}

            override fun afterTextChanged(s: Editable?) {
                updateBottomButtonVisibility()
            }
        })

        wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

        wifiScanReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                val success = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false)
                if (success) {
                    updateWifiList()
                }
            }
        }

        // 点击确定按钮，修改WiFi信息
        binding.btnConfirm.setOnClickListener {
            updateWifiInfo()
        }

        updateBottomButtonVisibility()
    }

    private fun updateWifiInfo() {
        val wifiName = binding.etWifiName.text.toString().trim()
        val wifiPassword = binding.etWifiPassword.text.toString().trim()

        if (wifiName.isEmpty()) {
            ToastUtils.showError(this, getString(R.string.enter_wifi_name))
            return
        }

        if (wifiPassword.isEmpty()) {
            ToastUtils.showError(this, getString(R.string.enter_wifi_password))
            return
        }

        val deviceId = DeviceIdEvent.getDeviceId()
        if (deviceId.isNullOrEmpty()) {
            ToastUtils.showError(this, getString(R.string.device_id_empty))
            return
        }

        binding.btnConfirm.isEnabled = false

        CoroutineScope(Dispatchers.IO).launch {
            try {
                val deviceBean = DeviceBean(
                    id = deviceId,
                    wifiName = wifiName,
                    wifiPassword = wifiPassword
                )
                val response = RetrofitNetwork.getNetworkService().updateDeviceInfo(deviceBean)
                withContext(Dispatchers.Main) {
                    binding.btnConfirm.isEnabled = true
                    if (response.code == 200) {
                        ToastUtils.showSuccess(this@WiFiManagementActivity, getString(R.string.modify_success))
                        finish()
                    } else {
                        ToastUtils.showError(this@WiFiManagementActivity, response.msg ?: getString(R.string.modify_failed))
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    binding.btnConfirm.isEnabled = true
                    ToastUtils.showError(this@WiFiManagementActivity, getString(R.string.network_request_failed))
                }
            }
        }
    }

    private fun showWifiListDialog() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED ||
            ActivityCompat.checkSelfPermission(this, Manifest.permission.CHANGE_WIFI_STATE)
            != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CHANGE_WIFI_STATE),
                1001)
            return
        }

        if (!wifiManager.isWifiEnabled) {
            wifiManager.isWifiEnabled = true
        }

        wifiManager.startScan()

        val dialogBinding = DialogWifiListBinding.inflate(LayoutInflater.from(this))

        // 设置弹窗高度为屏幕的2/3
        val screenHeight = resources.displayMetrics.heightPixels
        val popupHeight = (screenHeight * 2 / 3)

        popupWindow = PopupWindow(
            dialogBinding.root,
            ViewGroup.LayoutParams.MATCH_PARENT,
            popupHeight
        ).apply {
            isFocusable = true
            setBackgroundDrawable(null)
            setOnDismissListener {
                binding.maskView.visibility = android.view.View.GONE
            }
            showAtLocation(window.decorView, Gravity.BOTTOM, 0, 0)
        }

        binding.maskView.visibility = android.view.View.VISIBLE

        dialogBinding.rvWifiList.layoutManager = LinearLayoutManager(this@WiFiManagementActivity)

        val wifiList = getWifiList()
        val adapter = WifiListAdapter(wifiList) { wifiName ->
            binding.etWifiName.setText(wifiName)
            popupWindow?.dismiss()
        }
        dialogBinding.rvWifiList.adapter = adapter

        // 添加下拉刷新功能
        dialogBinding.swipeRefreshLayout.setOnRefreshListener {
            wifiManager.startScan()
            // 延迟1秒后停止刷新动画
            android.os.Handler().postDelayed({
                dialogBinding.swipeRefreshLayout.isRefreshing = false
            }, 1000)
        }
    }

    private fun updateBottomButtonVisibility() {
        val wifiName = binding.etWifiName.text.toString().trim()
        val wifiPassword = binding.etWifiPassword.text.toString().trim()
        binding.bottomButtonLayout.visibility =
            if (wifiName.isNotEmpty() && wifiPassword.isNotEmpty()) android.view.View.VISIBLE else android.view.View.GONE
    }

    private fun getWifiList(): List<String> {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
            return emptyList()
        }
        val results: List<ScanResult> = wifiManager.scanResults
        return results.map { it.SSID }.distinct()
    }

    private fun updateWifiList() {
        popupWindow?.contentView?.findViewById<androidx.swiperefreshlayout.widget.SwipeRefreshLayout>(R.id.swipeRefreshLayout)?.let { swipeRefreshLayout ->
            swipeRefreshLayout.isRefreshing = false
        }
        popupWindow?.contentView?.findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.rvWifiList)?.let { recyclerView ->
            val wifiList = getWifiList()
            recyclerView.adapter = WifiListAdapter(wifiList) { wifiName ->
                binding.etWifiName.setText(wifiName)
                popupWindow?.dismiss()
            }
        }
    }

    override fun onStart() {
        super.onStart()
        val intentFilter = IntentFilter()
        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
        registerReceiver(wifiScanReceiver, intentFilter)
    }

    override fun onStop() {
        super.onStop()
        unregisterReceiver(wifiScanReceiver)
        popupWindow?.dismiss()
    }
}
