package com.example.smart119.views

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.view.Gravity
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.LinearLayout
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 DepartmentAddress_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.department_address, null)
        dialog?.setContentView(dialogView)

        dialog?.window?.setLayout(1000, 800) // width, height (픽셀 단위)


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

        // 그리드에 표시할 데이터
//        var options = MedicalInfo.get_prt_list()
//        options.add(0, "진료과목선택")

        val itemClickListener: (String) -> Unit = { item ->
            HospitalSearch.set_selectPrtAddress(item)
            var addrView = FragmentHandler.getView("AddressSearchFragment")
            if (addrView != null) {
                val prtTV = addrView.findViewById<TextView>(R.id.prtText)
                prtTV.text = item;
            }
            Toast.makeText(context, "선택된 항목: $item", Toast.LENGTH_SHORT).show()

            triggerEvent(item)
        }

        val getGroups = MedicalInfo.get_prt_group_map();
        if (getGroups.size > 0) {
            getGroups.forEach { key, value ->
                val group_name = key;
                val group_list = value;
                addGroup(
                    dialogView, context,
                    group_name, group_list,
                    itemClickListener
                )
            }
        }



//        val adapter = ArrayAdapter(context, android.R.layout.simple_list_item_1, options)
//        gridView.adapter = adapter
//
//        // 아이템 클릭 이벤트 (선택 시 다이얼로그 닫기)
//        gridView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
//            try {
//                val selectedOption = options[position]
//                HospitalSearch.set_selectPrtAddress(selectedOption)
//                var addrView = FragmentHandler.getView("AddressSearchFragment")
//                if (addrView != null) {
//                    val prtTV = addrView.findViewById<TextView>(R.id.prtText)
//                    prtTV.text = selectedOption;
//                }
//                Toast.makeText(context, "선택된 항목: $selectedOption", Toast.LENGTH_SHORT).show()
//
//                triggerEvent(selectedOption)
//            } catch (e: Exception) {
//                println(e.message)
//            }
//            dismiss() // 아이템 선택 즉시 다이얼로그 닫기
//        }

        dialog?.setOnCancelListener {
            //진료과 선택
            var addrView = FragmentHandler.getView("AddressSearchFragment")
            if (addrView != null) {
                val prtTV = addrView.findViewById<TextView>(R.id.prtText)
                prtTV.text = "진료과목선택";
            }
        }

        dialog?.show()
    }
    private fun addGroup(
        view: View, context: Context, groupName: String, items: List<String>, callback: (String) -> Unit
    ) {
        val container = view.findViewById<LinearLayout>(R.id.departGroupContainer)

        // 그룹 레이아웃 생성 (LinearLayout)
        val groupLayout = LinearLayout(context).apply {
            layoutParams = LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            orientation = LinearLayout.VERTICAL
            setPadding(0, 4, 0, 4)
        }

        // 그룹명 (TextView)
        val textView = TextView(context).apply {
            text = groupName
            textSize = 25f
            setTypeface(null, Typeface.BOLD)
            setPadding(0, 0, 0, 4)
        }

        // 구분선 (View)
        val divider = View(context).apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                2 // 두께
            )
            setBackgroundColor(Color.GRAY)
        }

        // GridView 생성
        val gridView = GridView(context).apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            stretchMode = GridView.STRETCH_COLUMN_WIDTH
            gravity = Gravity.CENTER
            this.numColumns = GridView.AUTO_FIT
            verticalSpacing = 8
            horizontalSpacing = 8
        }

        // GridView 어댑터 설정
//        val adapter = ArrayAdapter(context, android.R.layout.simple_list_item_1, items)
        val adapter = object : ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, items) {
            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 { parent, view, position, id ->
            val selectedItem = parent.getItemAtPosition(position) as String
            callback(selectedItem)
            dismiss()
        }

        // GridView 높이 자동 조절 함수
        fun setGridViewHeight(gridView: GridView) {
            val listAdapter = gridView.adapter ?: return
            val totalItems = listAdapter.count
            val numColumns = gridView.numColumns
            val rows = Math.ceil(totalItems / numColumns.toDouble()).toInt()

            val itemHeight = 80 // px 단위 (아이템 하나의 높이)
            val params = gridView.layoutParams
            params.height = rows * itemHeight
            gridView.layoutParams = params
        }

        // 그룹 레이아웃에 추가
        groupLayout.addView(textView)
        groupLayout.addView(divider)
        groupLayout.addView(gridView)
        container.addView(groupLayout)

        // GridView 높이 조정
        gridView.post { setGridViewHeight(gridView) }
    }

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

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

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