package com.example.smart119

import android.graphics.Color
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.JsonObject

class SpreadsheetAdapter(
    private var items: List<ListItem>,
    private val onButtonClick: (ListItem.Row, Int) -> Unit, // button click 이벤트
    private val onRowClick: (ListItem.Row) -> Unit// Row click 이벤트
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    companion object {
        const val VIEW_TYPE_HEADER = 0
        const val VIEW_TYPE_ROW = 1
    }

    override fun getItemViewType(position: Int): Int {
        return when (items[position]) {
            is ListItem.Header -> VIEW_TYPE_HEADER
            is ListItem.Row -> VIEW_TYPE_ROW
            else -> throw IllegalArgumentException("Unknown view type at position $position")
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        return if (viewType == VIEW_TYPE_HEADER) {
            val view = inflater.inflate(R.layout.header_row, parent, false)
            HeaderViewHolder(view)
        } else {
            val view = inflater.inflate(R.layout.data_row, parent, false)
            RowViewHolder(view, onButtonClick, onRowClick)
        }
    }

    private var _columnCount = 0
    private var selectedPosition: Int = RecyclerView.NO_POSITION
    private var headerList: List<ListItem>? = null
    private var _IndexMap:MutableMap<String, Int> = mutableMapOf()

    fun setColumnCount(count:Int) {
        _columnCount = count
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (val item = items[position]) {
            is ListItem.Header -> (holder as HeaderViewHolder).bind(item)
            is ListItem.Row -> (holder as RowViewHolder).bind(item, position)
            else -> throw IllegalArgumentException("Unsupported item type at position $position")
        }

        /*
        holder.itemView.setOnClickListener {
            val previousPosition = selectedPosition
            selectedPosition = position

            // 이전 선택 항목과 현재 선택 항목 갱신
            notifyItemChanged(previousPosition)
            notifyItemChanged(selectedPosition)
        }
        */
    }

    override fun getItemCount(): Int = items.size

    fun setSelectedHospitalPos(selPos:Int) {
        selectedPosition = selPos
    }

    fun getSelectedHospital() : ListItem? {
        //return this.items[selectedPosition]
        return if(selectedPosition in 0 until items.size) {
            this.items[selectedPosition]
        } else {
            null
        }
    }
    fun getSelectedPosition():Int {
        var valid = selectedPosition - _columnCount;
        if(valid < 0) valid = 0
        return valid
    }

    fun getSelectedHospital_JSON() : JsonObject? {
        //return this.items[selectedPosition]
        var returnValue = JsonObject()
        if(selectedPosition in 0 until items.size) {
            var _row = (this.items[selectedPosition] as ListItem.Row);
            returnValue = JsonObject().apply {
                addProperty("name", "${_row.values[0]}")
                addProperty("address", "${_row.values[1]}")
                addProperty("tell","${_row.values[2]}")
                addProperty("lidar","${_row.values[3]}")
                addProperty("distance","${_row.values[4]}")
            }
        }
        return returnValue
    }

    private fun default_list_headers() {
        this.items = listOf(
            ListItem.Header(listOf("병원이름")), // 헤더 열 정의
            ListItem.Header(listOf("주소")),
            ListItem.Header(listOf("전화번호")),
            ListItem.Header(listOf("라이다 혼잡도")),
            ListItem.Header(listOf("거리")),
            ListItem.Header(listOf("병원별 이송 시작")),
        )
    }

    fun hospitalListUpdate(searchResult:List<List<String>>, idList: List<String>) {
        //기본 헤더 설정
        default_list_headers()

        //추가 검색된 결과 설정
//        var loop_count = 0;
//        for (addItem in searchResult) {
//            this.items = this.items + ListItem.Row(addItem)
//            println(addItem[0])
//            loop_count++;
//        }

        searchResult.forEachIndexed { index, addItem ->
            this.items = this.items + ListItem.Row(addItem)
            if (idList.size > index) {
                _IndexMap[idList[index]] = this.items.size - 1 // ID와 리스트 인덱스 매핑
            }
        }

        notifyDataSetChanged()
    }

    fun getHospitalById(id: String): ListItem.Row? {
        val position = _IndexMap[id] ?: return null
        return if (position in 0 until items.size) {
            items[position] as? ListItem.Row
        } else {
            null
        }
    }

    fun clearHospitalList() {
        if(this.items.size == 6) return;

        if (selectedPosition != RecyclerView.NO_POSITION) selectedPosition = RecyclerView.NO_POSITION

        if (_IndexMap != null) _IndexMap.clear()

        default_list_headers()
        notifyDataSetChanged()
    }

//    fun getSelectedHospitalName(): String {
//        return selRowHospName
//    }

    // 헤더 ViewHolder
    class HeaderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val columns: List<TextView> = listOf(
            itemView.findViewById(R.id.column1) // 추가 열에 따라 확장 가능
        )

        fun bind(header: ListItem.Header) {
            header.columns.forEachIndexed { index, column ->
                columns[index].text = column
            }
        }
    }

    // 데이터 행 ViewHolder
    class RowViewHolder(
        itemView: View,
        private val onButtonClick: (ListItem.Row, Int) -> Unit,
        private val onRowClick: (ListItem.Row) -> Unit
    ) : RecyclerView.ViewHolder(itemView) {
        private val cells: List<TextView> = listOf(
            itemView.findViewById(R.id.cell1),
            itemView.findViewById(R.id.cell2),
            itemView.findViewById(R.id.cell3), // 추가 열에 따라 확장 가능
            itemView.findViewById(R.id.cell4),
            itemView.findViewById(R.id.cell5)
        )

        private val lContainer: LinearLayout = itemView.findViewById(R.id.cell6_container)
        private val lContButton: Button = itemView.findViewById(R.id.cell6_button)
        private val lLidarView : View = itemView.findViewById(R.id.cell4_lidar_color)

        fun bind(row: ListItem.Row, pos:Int) {
            row.values.take(cells.size).forEachIndexed { index, value ->
                cells[index].text = value

                if (index == 3) lLidarView.setBackgroundColor(
                    Color.parseColor(API_Helper.lidar_levelState_Color(value))
                )
            }

            /*
            // 선택된 항목 하이라이트 적용
            if (isSelected) {
                itemView.setBackgroundColor(Color.parseColor("#DCDCDC")) // 선택된 배경색
                onRowClick(row)
            } else {
                itemView.setBackgroundColor(Color.WHITE) // 기본 배경색
            }
            */

            lContButton.setOnClickListener {
                onButtonClick(row, pos) // 버튼 클릭 시 Row의 position 전달
            }

        }
    }
}
