package com.example.defenseapplication.view

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.Gravity
import android.view.Window
import android.view.WindowManager
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.defenseapplication.R
import com.example.defenseapplication.adapter.FamilySwitchAdapter
import com.example.defenseapplication.bean.FamilyBean
import com.example.defenseapplication.bean.SwitchFamilyRequest
import com.example.defenseapplication.model.FamilyItem
import com.example.defenseapplication.utils.FamilySwitchEvent
import com.example.defenseapplication.utils.RetrofitNetwork
import com.example.defenseapplication.utils.UserinfoUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class FamilySwitchDialog(
    context: Context,
    private val onFamilySelected: (String) -> Unit
) : Dialog(context, R.style.BottomDialogStyle) {

    private lateinit var adapter: FamilySwitchAdapter
    private var familyBeanList: List<FamilyBean> = emptyList()
    private var currentFamilyName: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(R.layout.dialog_family_switch)

        val window = window
        val params = window?.attributes
        params?.width = WindowManager.LayoutParams.MATCH_PARENT
        params?.height = WindowManager.LayoutParams.WRAP_CONTENT
        params?.gravity = Gravity.BOTTOM
        window?.attributes = params
        window?.setBackgroundDrawableResource(android.R.color.transparent)
        window?.setDimAmount(0.5f)

        initViews()
        fetchFamilyList()
    }

    private fun initViews() {
        val tvCancel = findViewById<TextView>(R.id.tvCancel)
        val tvConfirm = findViewById<TextView>(R.id.tvConfirm)
        val rvMessageList = findViewById<RecyclerView>(R.id.rvMessageList)

        adapter = FamilySwitchAdapter(emptyList()) { familyItem ->
        }

        rvMessageList.layoutManager = LinearLayoutManager(context)
        rvMessageList.adapter = adapter

        tvCancel.setOnClickListener {
            dismiss()
        }

        tvConfirm.setOnClickListener {
            val selectedItem = adapter.getSelectedItem()
            val selectedFamily = familyBeanList.find { it.parentName == selectedItem.name }
            selectedFamily?.let {
                switchToFamily(it)
            }
        }
    }

    private fun fetchFamilyList() {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val response = RetrofitNetwork.getNetworkService().getFamilyList()
                withContext(Dispatchers.Main) {
                    if (response.code == 200 && response.data != null) {
                        familyBeanList = response.data.reversed()
                        val familyItems = familyBeanList.map { FamilyItem(it.id, it.parentName, it.role) }
                        adapter.updateList(familyItems)

                        familyBeanList.firstOrNull()?.let {
                            currentFamilyName = it.parentName
                        }
                    } else {
                        Toast.makeText(context, response.msg, Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    Toast.makeText(context, R.string.network_error, Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun switchToFamily(familyBean: FamilyBean) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val userInfo = UserinfoUtil.getUserInfo()
                val request = SwitchFamilyRequest(
                    clientId = "428a8310cd442757ae699df5d894f051",
                    grantType = "switch",
                    id = familyBean.id,
                    userType = "app_user",
                    role = userInfo?.role ?: ""
                )
                val response = RetrofitNetwork.getNetworkService().switchFamily(request)
                withContext(Dispatchers.Main) {
                    if (response.code == 200) {
                        onFamilySelected(familyBean.parentName)
                        FamilySwitchEvent.notifyFamilySwitched(familyBean.parentName)
                        dismiss()
                    } else {
                        Toast.makeText(context, response.msg, Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    Toast.makeText(context, R.string.network_error, Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}