package com.example.defenseapplication.home

import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.defenseapplication.adapter.MessageListAdapter
import com.example.defenseapplication.adapter.MessageListItem
import com.example.defenseapplication.bean.MessageGroup
import com.example.defenseapplication.bean.MessageItem
import com.example.defenseapplication.databinding.MessageActivityBinding
import com.example.defenseapplication.utils.MessageStatusManager
import com.example.defenseapplication.utils.RetrofitNetwork
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
//消息通知页面
class MessageActivity : AppCompatActivity() {
    private lateinit var binding: MessageActivityBinding
    private val messageAdapter by lazy { MessageListAdapter() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = MessageActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .titleBar(binding.topBar)
            .init()
        initView()
        MessageStatusManager.clearUnreadCount()
        loadMessageList()
    }

    private fun initView() {
        binding.ivBack.setOnClickListener { finish() }
        binding.rvMessageList.layoutManager = LinearLayoutManager(this)
        binding.rvMessageList.adapter = messageAdapter
    }

    private fun loadMessageList() {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val response = RetrofitNetwork.getNetworkService().getMessage()
                if (response.code == 0 && response.data != null) {
                    val messageGroups = response.data as List<MessageGroup>
                    val items = convertToMessageListItems(messageGroups)
                    withContext(Dispatchers.Main) {
                        if (items.isEmpty()) {
                            showEmptyState()
                        } else {
                            hideEmptyState()
                            messageAdapter.submitList(items)
                        }
                    }
                } else {
                    withContext(Dispatchers.Main) {
                        showEmptyState()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    showEmptyState()
                }
            }
        }
    }

    private fun showEmptyState() {
        binding.contentLayout.visibility = View.GONE
        binding.emptyLayout.visibility = View.VISIBLE
    }

    private fun hideEmptyState() {
        binding.contentLayout.visibility = View.VISIBLE
        binding.emptyLayout.visibility = View.GONE
    }

    private fun convertToMessageListItems(groups: List<MessageGroup>): List<MessageListItem> {
        val items = mutableListOf<MessageListItem>()
        groups.forEach { group ->
            val headerTitle = formatDate(group.time)
            items.add(MessageListItem.Header(headerTitle))
            group.list.forEach { message ->
                items.add(
                    MessageListItem.Message(
                        time = extractTime(message.createTime),
                        title = message.categoryName,
                        dateTime = message.createTime,
                        unread = false
                    )
                )
            }
        }
        return items
    }

    private fun formatDate(dateStr: String): String {
        return if (dateStr == "今天" || dateStr.contains("今天")) {
            "今天"
        } else {
            dateStr
        }
    }

    private fun extractTime(dateTime: String): String {
        return if (dateTime.contains(" ")) {
            dateTime.split(" ")[1].substring(0, 5)
        } else {
            dateTime
        }
    }
}