package com.example.punyaria;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.Collections;

public class RiwayatFragment extends Fragment {

    private SharedPreferences sharedPreferences;
    private ListView listViewKonseling;
    private ArrayAdapter<String> adapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_riwayat, container, false);
        listViewKonseling = view.findViewById(R.id.listViewKonseling);
        sharedPreferences = getActivity().getSharedPreferences("loginPrefs", getActivity().MODE_PRIVATE);
        loadData();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData(); // Muat ulang data setiap kali fragment menjadi aktif
    }

    private void loadData() {
        String username = getUsername();
        DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReference("konseling");
        Query query = databaseRef.orderByChild("username").equalTo(username);
        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                ArrayList<String> konselingList = new ArrayList<>();
                final ArrayList<String> konselingIDs = new ArrayList<>();
                final ArrayList<String> konselingStatuses = new ArrayList<>(); // Tambahkan list untuk menyimpan status

                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    Konseling konseling = snapshot.getValue(Konseling.class);
                    if (konseling != null) {
                        String konselingInfo = "Topik: " + konseling.getTopik() + "\n"
                                + "Keluhan: " + konseling.getKeluhan() + "\n"
                                + "Tanggal: " + konseling.getDate();
                        konselingList.add(konselingInfo);
                        konselingIDs.add(snapshot.getKey());
                        konselingStatuses.add(konseling.getStatus()); // Simpan status
                    }
                }

                Collections.reverse(konselingList);
                Collections.reverse(konselingIDs);
                Collections.reverse(konselingStatuses); // Balik urutan status

                adapter = new ArrayAdapter<String>(getContext(), R.layout.list_riwayat, konselingList) {
                    @Override
                    public View getView(int position, View convertView, ViewGroup parent) {
                        View view = super.getView(position, convertView, parent);
                        TextView textView = view.findViewById(R.id.textViewListItemRiwayat);

                        // Ubah drawable berdasarkan status
                        String status = konselingStatuses.get(position);
                        if ("ended".equals(status)) {
                            textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.message_off, 0, 0, 0);
                        } else {
                            textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.message, 0, 0, 0);
                        }

                        return view;
                    }
                };
                listViewKonseling.setAdapter(adapter);

                listViewKonseling.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        String konselingID = konselingIDs.get(position);
                        String konselingStatus = konselingStatuses.get(position);

                        if ("ended".equals(konselingStatus)) {
                            Toast.makeText(getContext(), "Sesi konseling telah berakhir", Toast.LENGTH_SHORT).show();
                        } else {
                            openChatActivity(konselingID);
                        }
                    }
                });
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(getContext(), "Gagal mengambil data konseling: " + databaseError.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private String getUsername() {
        return sharedPreferences.getString("username", null);
    }

    private void openChatActivity(String konselingID) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("KONSELING_ID", konselingID);
        editor.apply();

        Intent intent = new Intent(getActivity(), ChatActivity.class);
        startActivity(intent);
    }
}
