package com.example.defenseapplication.home

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.graphics.Rect
import android.net.wifi.ScanResult
import android.net.wifi.WifiManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
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 android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.defenseapplication.R
import com.example.defenseapplication.adapter.WifiListAdapter
import com.example.defenseapplication.databinding.AddFamilyActivityBinding
import com.example.defenseapplication.databinding.DialogWifiListBinding
import com.gyf.immersionbar.ImmersionBar

class AddFamilyActivity : AppCompatActivity() {

    private lateinit var binding: AddFamilyActivityBinding
    private lateinit var wifiManager: WifiManager
    private lateinit var wifiScanReceiver: BroadcastReceiver
    private var popupWindow: PopupWindow? = null
    private val handler = Handler(Looper.getMainLooper())
    private var wifiListAdapter: WifiListAdapter? = null
    private var isLoadingMore = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = AddFamilyActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .titleBar(binding.topBar)
            .init()
        
        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()
            }
        })
        
        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()
                }
            }
        }
        
        binding.btnConfirm.setOnClickListener {
            val wifiName = binding.etWifiName.text.toString().trim()
            val wifiPassword = binding.etWifiPassword.text.toString()

            if (wifiName.isEmpty()) {
                Toast.makeText(this, R.string.enter_wifi_name, Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (wifiPassword.isEmpty()) {
                Toast.makeText(this, R.string.enter_wifi_password, Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            val intent = Intent(this@AddFamilyActivity, ConnectDeviceActivity::class.java)
            intent.putExtra("wifi_name", wifiName)
            intent.putExtra("wifi_password", wifiPassword)
            startActivity(intent)
        }
    }

    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))
        
        val screenHeight = getScreenHeight()
        val popupHeight = (screenHeight * 2 / 3).toInt()
        
        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@AddFamilyActivity)
        
        val wifiList = getWifiList()
        wifiListAdapter = WifiListAdapter(wifiList) { wifiName ->
            binding.etWifiName.setText(wifiName)
            popupWindow?.dismiss()
        }
        dialogBinding.rvWifiList.adapter = wifiListAdapter
        
        dialogBinding.swipeRefreshLayout.setOnRefreshListener {
            refreshWifiList(dialogBinding)
        }
        
        dialogBinding.rvWifiList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
                val totalItemCount = layoutManager.itemCount
                
                if (lastVisibleItemPosition == totalItemCount - 1 && dy > 0 && !isLoadingMore && totalItemCount > 0) {
                    loadMoreWifiList()
                }
            }
        })
    }
    
    private fun getScreenHeight(): Int {
        val rect = Rect()
        window.decorView.getWindowVisibleDisplayFrame(rect)
        return rect.height()
    }
    
    private fun refreshWifiList(dialogBinding: DialogWifiListBinding) {
        dialogBinding.swipeRefreshLayout.isRefreshing = true
        handler.postDelayed({
            wifiManager.startScan()
            val newWifiList = getWifiList()
            wifiListAdapter?.updateData(newWifiList)
            dialogBinding.swipeRefreshLayout.isRefreshing = false
        }, 1000)
    }
    
    private fun loadMoreWifiList() {
        isLoadingMore = true
        handler.postDelayed({
            wifiManager.startScan()
            val newWifiList = getWifiList()
            wifiListAdapter?.addData(newWifiList)
            isLoadingMore = false
        }, 1000)
    }

    private fun updateBottomButtonVisibility() {
        val wifiName = binding.etWifiName.text.toString().trim()
        binding.bottomButtonLayout.visibility = 
            if (wifiName.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.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()
        handler.removeCallbacksAndMessages(null)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            1001 -> {
                if (grantResults.isNotEmpty() && 
                    grantResults.size >= 2 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED &&
                    grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    showWifiListDialog()
                } else {
                    Toast.makeText(this, R.string.permission_denied, Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}