package com.amz.genie.adapters

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.amz.genie.R
import com.amz.genie.helpers.Utils.formatDateTime
import com.amz.genie.models.GeneralThreadItem
import com.amz.genie.models.OfficeTrnAksiKepada

class GeneralDetailAdapter(
    private val kodePegawai: String,
    private val onItemClick: (GeneralThreadItem) -> Unit,
    private val onDetailClick: (GeneralThreadItem) -> Unit
) : ListAdapter<GeneralThreadItem, GeneralDetailAdapter.UnifiedVH>(DIFF) {

    companion object {
        private val DIFF = object : DiffUtil.ItemCallback<GeneralThreadItem>() {
            override fun areItemsTheSame(oldItem: GeneralThreadItem, newItem: GeneralThreadItem): Boolean {
                val oldKey = if (oldItem.tipe.equals("REAKSI", true))
                    "R_${oldItem.reaksi?.id ?: -1}"
                else
                    "A_${oldItem.aksi.id}"

                val newKey = if (newItem.tipe.equals("REAKSI", true))
                    "R_${newItem.reaksi?.id ?: -1}"
                else
                    "A_${newItem.aksi.id}"

                return oldKey == newKey
            }

            override fun areContentsTheSame(oldItem: GeneralThreadItem, newItem: GeneralThreadItem): Boolean {
                return oldItem == newItem
            }
        }
    }

    fun submitRawTimeline(raw: List<GeneralThreadItem>?) {
        val dedup = raw.orEmpty()
            .distinctBy {
                if (it.tipe.equals("REAKSI", true)) "R_${it.reaksi?.id}" else "A_${it.aksi.id}"
            }
        submitList(dedup)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UnifiedVH {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.item_inbox_detail, parent, false)
        return UnifiedVH(v, kodePegawai, onItemClick, onDetailClick)
    }

    override fun onBindViewHolder(holder: UnifiedVH, position: Int) {
        holder.bind(getItem(position))
    }

    class UnifiedVH(
        itemView: View,
        private val kodePegawai: String,
        private val onItemClick: (GeneralThreadItem) -> Unit,
        private val onDetailClick: (GeneralThreadItem) -> Unit
    ) : RecyclerView.ViewHolder(itemView) {

        private val tvTitle: TextView = itemView.findViewById(R.id.tv_title_item_inbox_detail)
        private val tvTime: TextView = itemView.findViewById(R.id.tv_time_item_inbox_detail)
        private val tvMessage: TextView = itemView.findViewById(R.id.tv_message_item_inbox_detail) // ✅ baru

        private val rvPenerima: RecyclerView = itemView.findViewById(R.id.rv_penerima_item_inbox_detail)
        private val rvSubject: RecyclerView = itemView.findViewById(R.id.rv_subject_item_inbox_detail)
        private val llContainer: View = itemView.findViewById(R.id.ll_container_item_inbox_detail)
        private val ibDetail: View = itemView.findViewById(R.id.ib_detail_item_inbox_detail)

        private var currentItem: GeneralThreadItem? = null

        private val penerimaAdapter = GeneralDetailPenerimaAdapter()
        private val subjectAdapter = SubjectAdapter()

        private val glm = GridLayoutManager(itemView.context, 3)

        init {
            // ✅ 1 chip = full row, multi = 3 kolom
            glm.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int {
                    return if (penerimaAdapter.itemCount == 1) 3 else 1
                }
            }

            rvPenerima.layoutManager = glm
            rvPenerima.adapter = penerimaAdapter
            rvPenerima.isNestedScrollingEnabled = false

            rvSubject.layoutManager = LinearLayoutManager(itemView.context, LinearLayoutManager.HORIZONTAL, false)
            rvSubject.adapter = subjectAdapter
            rvSubject.setHasFixedSize(true)
            rvSubject.isNestedScrollingEnabled = false

            ibDetail.setOnClickListener { currentItem?.let { onDetailClick(it) } }
            itemView.setOnClickListener { currentItem?.let { onItemClick(it) } }
        }

        fun bind(item: GeneralThreadItem) {
            currentItem = item

            val isReaksi = item.tipe.equals("REAKSI", true)
            val aksi = item.aksi

            // ✅ WARNA berdasar is_aktif untuk saya
            val inactiveForMe = aksi.kepada.orEmpty().any {
                it.kode_kepada == kodePegawai && it.is_aktif == 0
            }
            llContainer.setBackgroundResource(
                if (inactiveForMe) R.color.colorGreenVeryLight else R.color.colorWhitePure
            )

            // ✅ Title selalu judul/uraian AKSI
            tvTitle.text = aksi.uraian

            if (!isReaksi) {
                // AKSI
                tvTime.text = formatDateTime(aksi.waktu_buat)

                penerimaAdapter.submitList(aksi.kepada.orEmpty())

                val listString = arrayListOf(
                    aksi.tipe_komunikasi?.tipe_komunikasi.toString(),
                    aksi.tentang.tentang
                )
                subjectAdapter.submitList(listString)

                // ✅ tidak ada pesan reaksi
                tvMessage.visibility = View.GONE
                tvMessage.text = ""

                ibDetail.visibility = View.VISIBLE

            } else {
                // REAKSI
                val rx = item.reaksi

                tvTitle.text = aksi.uraian
                tvTime.text = formatDateTime(rx?.waktu_buat ?: aksi.waktu_buat)

                val pembuat = rx?.pembuat
                val chip: List<OfficeTrnAksiKepada> = pembuat?.let { peg ->
                    listOf(
                        OfficeTrnAksiKepada(
                            id = -(rx?.id ?: 1),
                            aksi_id = aksi.id,
                            kode_kepada = peg.kode,
                            kepada = peg,
                            is_aktif = 1,
                            waktu_buat = rx?.waktu_buat ?: aksi.waktu_buat,
                            waktu_ubah = rx?.waktu_buat ?: aksi.waktu_buat
                        )
                    )
                } ?: emptyList()

                penerimaAdapter.submitList(chip)
                subjectAdapter.submitList(arrayListOf("REAKSI"))
                tvMessage.visibility = View.VISIBLE
                tvMessage.text = rx?.uraian?.takeIf { it.isNotBlank() } ?: "(Reaksi)"
                ibDetail.visibility = View.VISIBLE
            }
        }
    }
}