package com.example.defenseapplication.view

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.Gravity
import android.view.WindowManager
import android.widget.LinearLayout
import com.example.defenseapplication.R
import com.example.defenseapplication.databinding.DialogRecognitionModeBinding

class RecognitionModeDialog(context: Context) : Dialog(context) {

    private lateinit var binding: DialogRecognitionModeBinding
    private var selectedMode: String = ""
    private var onConfirmListener: ((String) -> Unit)? = null

    fun setOnConfirmListener(listener: (String) -> Unit) {
        this.onConfirmListener = listener
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DialogRecognitionModeBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val window = window
        window?.let {
            val params = it.attributes
            params.gravity = Gravity.BOTTOM
            params.width = WindowManager.LayoutParams.MATCH_PARENT
            params.height = WindowManager.LayoutParams.WRAP_CONTENT
            it.attributes = params
            it.setBackgroundDrawableResource(R.drawable.round_bg)
        }

        binding.tvCancel.setOnClickListener {
            dismiss()
        }

        binding.itemBluetooth.setOnClickListener {
            selectedMode = context.getString(R.string.bluetooth_recognition)
            updateSelectedBackground(binding.itemBluetooth)
        }

        binding.itemBluetoothFace.setOnClickListener {
            selectedMode = context.getString(R.string.bluetooth_face_recognition)
            updateSelectedBackground(binding.itemBluetoothFace)
        }

        binding.tvConfirm.setOnClickListener {
            if (selectedMode.isNotEmpty()) {
                onConfirmListener?.invoke(selectedMode)
            }
            dismiss()
        }
    }

    private fun updateSelectedBackground(selectedItem: LinearLayout) {
        binding.itemBluetooth.setBackgroundColor(
            if (selectedItem == binding.itemBluetooth) {
                context.resources.getColor(R.color.bg_gray)
            } else {
                context.resources.getColor(R.color.white)
            }
        )
        binding.itemBluetoothFace.setBackgroundColor(
            if (selectedItem == binding.itemBluetoothFace) {
                context.resources.getColor(R.color.bg_gray)
            } else {
                context.resources.getColor(R.color.white)
            }
        )
    }
}