package com.example.defenseapplication.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.defenseapplication.databinding.ItemMessageGroupTitleBinding
import com.example.defenseapplication.databinding.ItemMessageNoticeBinding

sealed class MessageListItem {
    data class Header(val title: String) : MessageListItem()
    data class Message(
        val time: String,
        val title: String,
        val dateTime: String,
        val unread: Boolean
    ) : MessageListItem()
}

class MessageListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private val items = mutableListOf<MessageListItem>()

    fun submitList(list: List<MessageListItem>) {
        items.clear()
        items.addAll(list)
        notifyDataSetChanged()
    }

    override fun getItemViewType(position: Int): Int {
        return when (items[position]) {
            is MessageListItem.Header -> TYPE_HEADER
            is MessageListItem.Message -> TYPE_MESSAGE
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == TYPE_HEADER) {
            val binding = ItemMessageGroupTitleBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
            HeaderViewHolder(binding)
        } else {
            val binding = ItemMessageNoticeBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
            MessageViewHolder(binding)
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is HeaderViewHolder -> holder.bind(items[position] as MessageListItem.Header)
            is MessageViewHolder -> holder.bind(items[position] as MessageListItem.Message)
        }
    }

    override fun getItemCount(): Int = items.size

    private class HeaderViewHolder(private val binding: ItemMessageGroupTitleBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(item: MessageListItem.Header) {
            binding.tvGroupTitle.text = item.title
        }
    }

    private class MessageViewHolder(private val binding: ItemMessageNoticeBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(item: MessageListItem.Message) {
            binding.tvTime.text = item.time
            binding.tvTitle.text = item.title
            binding.tvDateTime.text = item.dateTime
            binding.unreadDot.visibility = if (item.unread) View.VISIBLE else View.INVISIBLE
        }
    }

    companion object {
        private const val TYPE_HEADER = 0
        private const val TYPE_MESSAGE = 1
    }
}
