package com.nurulwafa.nufakuproject;

import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

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

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChatActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private EditText inputMessage;
    private List<ChatModel> chatList;
    private ChatAdapter chatAdapter;
    private String sender = "wali"; // Ganti jika admin
    String idWaliSantri;

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

        recyclerView = findViewById(R.id.recyclerChat);
        inputMessage = findViewById(R.id.inputMessage);
        ImageButton btnSend = findViewById(R.id.btnSend);

        chatList = new ArrayList<>();
        chatAdapter = new ChatAdapter(chatList, sender);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(chatAdapter);
        idWaliSantri = getIntent().getStringExtra("id_wali_santri");
        Log.d("CheckID", "idWaliSantri: " + idWaliSantri);

        Log.d("ChatActivity", "ID dari Intent: " + idWaliSantri);

        // ✅ Cek sebelum loadChat
        Log.d("Sender", "Before loadChat: " + sender);

        loadChat();

        // ✅ Cek sesudah loadChat (optional, tapi bagus untuk jaga-jaga)
        Log.d("Sender", "After loadChat: " + sender);

        btnSend.setOnClickListener(v -> {
            String msg = inputMessage.getText().toString().trim();
            if (!msg.isEmpty()) {
                if (idWaliSantri == null || idWaliSantri.isEmpty()) {
                    Toast.makeText(ChatActivity.this, "ID Wali Santri tidak ditemukan", Toast.LENGTH_SHORT).show();
                    return;
                }
                sendMessage(msg);
                inputMessage.setText("");
            }
        });
    }

    private void loadChat() {
        String baseUrl = ApiHelper.getBaseUrl();
        String requestUrl = baseUrl + "getChatByWali/" + idWaliSantri;

        RequestQueue queue = Volley.newRequestQueue(this);
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, requestUrl, null,
                response -> {
                    try {
                        JSONArray chatArray = response.getJSONArray("data");
                        chatList.clear();
                        for (int i = 0; i < chatArray.length(); i++) {
                            JSONObject obj = chatArray.getJSONObject(i);
                            String messageSender = obj.getString("sender");
                            String message = obj.getString("message");
                            String timestamp = obj.getString("timestamp");

                            Log.d("ChatDebug", "sender = " + messageSender + ", message = " + message + ", timestamp = " + timestamp);

                            // ⬇️ ChatModel sudah parse timestamp ke Date di dalam konstruktor
                            chatList.add(new ChatModel(messageSender, message, timestamp));
                        }

                        chatList.sort(Comparator.comparing(ChatModel::getParsedTimestamp));
                        chatAdapter.notifyDataSetChanged();
                        recyclerView.scrollToPosition(chatList.size() - 1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                },
                error -> error.printStackTrace()
        );
        queue.add(request);
    }


    private void sendMessage(String message) {
        String baseUrl = ApiHelper.getBaseUrl();
        String requestUrl = baseUrl + "sendChat";

        StringRequest request = new StringRequest(Request.Method.POST, requestUrl,
                response -> loadChat(),
                error -> error.printStackTrace()
        ) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("sender", sender);
                params.put("id_wali_santri", idWaliSantri); // Ambil ID sesuai login
                params.put("message", message);
                return params;
            }
        };
        RequestQueue queue = Volley.newRequestQueue(this);
        queue.add(request);
    }
}

