package com.kaixed.kchat.ui.activity

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.kaixed.kchat.databinding.ActivityContactRequestListBinding
import com.kaixed.kchat.model.friend.FriendRequestItem
import com.kaixed.kchat.ui.adapter.ContactRequestListAdapter
import com.kaixed.kchat.ui.base.BaseActivity
import com.kaixed.kchat.utils.ConstantsUtil.getUsername
import com.kaixed.kchat.viewmodel.ContactViewModel

class ContactRequestListActivity : BaseActivity<ActivityContactRequestListBinding>() {


    private var items = mutableListOf<FriendRequestItem>()

    private val contactViewModel: ContactViewModel by viewModels()

    private lateinit var contactRequestListAdapter: ContactRequestListAdapter

    override fun inflateBinding(): ActivityContactRequestListBinding {
        return ActivityContactRequestListBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        getItems()

        contactRequestListAdapter = ContactRequestListAdapter(items, this)

        binding.recycleFriendRequestList.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)

        binding.recycleFriendRequestList.adapter = contactRequestListAdapter
    }

    private fun getItems() {
        contactViewModel.contactRequestListResult
            .observe(this) { result ->
                result.onSuccess {
                    items.addAll(result.getOrNull()?.toMutableList() ?: emptyList())
                    contactRequestListAdapter.notifyDataSetChanged()
                }

                result.onFailure {
                    toast(it.message.toString())
                }
            }

        contactViewModel.getContactRequestList(getUsername())
    }
}