package com.nurulwafa.nufakuproject;

import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

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

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

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

import java.util.ArrayList;
import java.util.List;

public class DetailKegiatanActivity extends AppCompatActivity {

    private TextView tvHari;
    private RecyclerView rvKegiatanSantri;
    private List<KegiatanSantri> kegiatanList;
    private KegiatanSantriAdapter adapter;

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

        tvHari = findViewById(R.id.homeTitle);
        rvKegiatanSantri = findViewById(R.id.rvKegiatanSantri);

        String hari = getIntent().getStringExtra("hari");
        tvHari.setText("Kegiatan Hari " + hari);

        kegiatanList = new ArrayList<>();
        adapter = new KegiatanSantriAdapter(this, kegiatanList);
        rvKegiatanSantri.setLayoutManager(new LinearLayoutManager(this));
        rvKegiatanSantri.setAdapter(adapter);

        getDetailKegiatan(hari);
    }

    private void getDetailKegiatan(String hari) {
        String url = ApiHelper.getBaseUrl() + "getKegiatan?hari=" + hari;

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                response -> {
                    try {
                        if (response.getBoolean("status")) {
                            JSONArray dataArray = response.getJSONArray("data");
                            kegiatanList.clear();

                            for (int i = 0; i < dataArray.length(); i++) {
                                JSONObject item = dataArray.getJSONObject(i);
                                String namaKegiatan = item.getString("nama_kegiatan");
                                String waktu = item.getString("waktu");

                                kegiatanList.add(new KegiatanSantri(namaKegiatan, waktu));
                            }

                            adapter.notifyDataSetChanged();
                        } else {
                            Toast.makeText(this, "Data tidak tersedia", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        Toast.makeText(this, "Gagal parsing data", Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                },
                error -> Toast.makeText(this, "Gagal mengambil data: " + error.getMessage(), Toast.LENGTH_SHORT).show()
        );

        Volley.newRequestQueue(this).add(request);
    }
}
