package com.example.pap_findu;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.pap_findu.adapters.ChatAdapter;
import com.example.pap_findu.models.ChatMessage;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class ChatActivity extends AppCompatActivity {

    private RecyclerView recyclerChat;
    private EditText editChatMessage;
    private ImageButton btnSend;
    private ImageButton btnBack;
    private ChatAdapter adapter;
    private List<ChatMessage> messageList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_activity);

        recyclerChat = findViewById(R.id.recycler_chat);
        editChatMessage = findViewById(R.id.edit_chat_message);
        btnSend = findViewById(R.id.btnSend);
        btnBack = findViewById(R.id.btnBack);

        // Initialize Message List with some dummy data
        messageList = new ArrayList<>();
        messageList.add(new ChatMessage("Olá Miguel! Tudo bem?", true, "10:30"));
        messageList.add(new ChatMessage("Cheguei bem à escola.", false, "10:32"));
        messageList.add(new ChatMessage("Ainda bem! Qualquer coisa avisa.", true, "10:33"));

        // Setup Adapter
        adapter = new ChatAdapter(messageList);
        recyclerChat.setLayoutManager(new LinearLayoutManager(this));
        recyclerChat.setAdapter(adapter);

        // Scroll to bottom
        recyclerChat.scrollToPosition(messageList.size() - 1);

        // Send Button Logic
        btnSend.setOnClickListener(v -> {
            String text = editChatMessage.getText().toString().trim();
            if (!TextUtils.isEmpty(text)) {
                sendMessage(text);
            }
        });

        // Back Button Logic
        btnBack.setOnClickListener(v -> finish());
    }

    private void sendMessage(String text) {
        String currentTime = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date());
        ChatMessage newMessage = new ChatMessage(text, true, currentTime);

        messageList.add(newMessage);
        adapter.notifyItemInserted(messageList.size() - 1);
        recyclerChat.scrollToPosition(messageList.size() - 1);

        editChatMessage.setText("");
    }
}
