package com.example.smart119.views

import android.app.Dialog
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.GridView
import android.widget.TextView
import android.widget.Toast
import com.example.smart119.MedicalInfo
import com.example.smart119.R
import com.example.smart119.datas.HospitalSearch

object HospitalCategoryAddress_Dialog {
    private var dialog: Dialog? = null
    private var selectCallback: ((String) -> Unit)? = null

    fun show(context: Context) {
        dialog?.dismiss() // 기존 다이얼로그가 있으면 닫기 (중복 방지)
        dialog = Dialog(context)

        val dialogView = LayoutInflater.from(context).inflate(R.layout.hospital_category_address, null)
        dialog?.setContentView(dialogView)

        val gridView: GridView = dialogView.findViewById(R.id.gridViewOptions)
//        val closeButton: Button = dialogView.findViewById(R.id.dialogCloseButton)

        // 그리드에 표시할 데이터
        var options = MedicalInfo.get_addressQZ_list()
        options.add(0, "병원분류명선택")
        val adapter = object : ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, options) {
            override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
                val view = super.getView(position, convertView, parent) as TextView
                view.textSize = 20f // 텍스트 크기 조정
                return view
            }
        }
        gridView.adapter = adapter

        // 아이템 클릭 이벤트 (선택 시 다이얼로그 닫기)
        gridView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
            try {
                val selectedOption = options[position]
                HospitalSearch.set_selectHospCatAddress(selectedOption)
                var addrView = FragmentHandler.getView("AddressSearchFragment")
                if (addrView != null) {
                    val hospCatTV = addrView.findViewById<TextView>(R.id.hospCatText)
                    hospCatTV.text = selectedOption;
                }
                Toast.makeText(context, "선택된 항목: $selectedOption", Toast.LENGTH_SHORT).show()

                triggerEvent(selectedOption)
            } catch (e: Exception) {
                println(e.message)
            }
            dismiss() // 아이템 선택 즉시 다이얼로그 닫기
        }

        // 닫기 버튼 클릭 이벤트
//        closeButton.setOnClickListener {
//            dismiss()
//        }

        dialog?.show()
    }

    fun registerCallback(callback: (String) -> Unit) {
        this.selectCallback = callback
    }

    fun triggerEvent(data: String) {
        selectCallback?.invoke(data)
    }

    fun dismiss() {
        dialog?.dismiss()
        dialog = null
    }
}