package com.example.chatapp.activities

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.chatapp.R
import com.example.chatapp.adapters.ChatRecyclerAdapter
import com.example.chatapp.models.Message
import com.google.android.material.floatingactionbutton.FloatingActionButton

class ChatActivity : AppCompatActivity() {

    lateinit var fabSendMessage: FloatingActionButton
    lateinit var editMessage: EditText
    lateinit var rvChatList: RecyclerView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_chat)

        rvChatList = findViewById(R.id.rvChatList)
        editMessage = findViewById(R.id.editMessage)
        fabSendMessage = findViewById(R.id.fabSendMsg)

        val name = intent.getStringExtra("conv")
        supportActionBar?.title = name ?: "Chat ESIEE"

        val chatRecyclerAdapter = ChatRecyclerAdapter()

        val messages = mutableListOf<Message>(
            Message("Dalh", "Hyperion", "Hey", 1695738248, true, false),
            Message("Hyperion", "Dalh", "Ping", 1695745448, false, false),
            Message("Atlas", "Dalh", "Pong", 1695745448, true, false),
        )

        fabSendMessage.setOnClickListener {
            // TODO Envoi message
            val message = editMessage.text.toString()
            if (message.isNotEmpty()) {
                messages.add(Message("Hyperion", "General", message,1695745848, false, false))
                chatRecyclerAdapter.notifyDataSetChanged()
                editMessage.setText("")

                // hide keyboard
                val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                inputMethodManager.hideSoftInputFromWindow(editMessage.windowToken, 0)
            }
        }

        rvChatList.apply {
            layoutManager = LinearLayoutManager(this@ChatActivity)
            adapter = chatRecyclerAdapter
        }

        chatRecyclerAdapter.items = messages
    }

}