package com.example.punyaria;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
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.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.res.ResourcesCompat;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
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.ValueEventListener;

import jp.wasabeef.glide.transformations.CropCircleTransformation;

public class AkunFragment extends Fragment {

    private ListView menuListView;
    private Button logoutButton;
    private TextView textUsername;
    private SharedPreferences sharedPreferences;

    public AkunFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_akun, container, false);

        // Set judul ActionBar
        ((AppCompatActivity) requireActivity()).getSupportActionBar().setTitle("Akun");

        // Inisialisasi elemen UI
        ImageView imageProfile = view.findViewById(R.id.image_profile);
        textUsername = view.findViewById(R.id.text_username);
        menuListView = view.findViewById(R.id.menu_list);
        logoutButton = view.findViewById(R.id.btn_logout);

        // Inisialisasi shared preferences
        sharedPreferences = requireActivity().getSharedPreferences("loginPrefs", AppCompatActivity.MODE_PRIVATE);

        // Ambil username dari shared preferences
        String username = sharedPreferences.getString("username", "Guest");
        // Tampilkan username pada textUsername
        textUsername.setText(username);

        // Set foto profil dari Firebase Storage jika tersedia
        setProfileImageFromFirebase(imageProfile, username);

        // Daftar menu
        String[] menuItems = {"Data Diri", "Ganti Password", "Frequently Asked Questions", "Tentang Kami"};

        // Buat ArrayAdapter untuk ListView
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(requireContext(),
                R.layout.list_item_menu, R.id.menu_text, menuItems) {
            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                View view = super.getView(position, convertView, parent);

                ImageView icon = view.findViewById(R.id.image_icon);
                // Set icon dynamically based on position or any other condition
                switch (position) {
                    case 0:
                        icon.setImageResource(R.drawable.ic_akun);
                        break;
                    case 1:
                        icon.setImageResource(R.drawable.ic_setting);
                        break;
                    case 2:
                        icon.setImageResource(R.drawable.ic_faq);
                        break;
                    case 3:
                        icon.setImageResource(R.drawable.ic_info);
                        break;
                }

                return view;
            }
        };

        // Set adapter ke ListView
        menuListView.setAdapter(adapter);

        // Tangani klik item di ListView
        menuListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // Aksi yang akan dilakukan sesuai dengan item yang diklik
                switch (position) {
                    case 0:
                        // Data Diri
                        Intent dataDiriIntent = new Intent(requireContext(), DataDiriActivity.class);
                        dataDiriIntent.putExtra("username", username); // Meneruskan username ke DataDiriActivity
                        startActivity(dataDiriIntent);
                        break;
                    case 1:
                        // Ganti Password
                        Intent gantiPasswordIntent = new Intent(requireContext(), GantiPasswordActivity.class);
                        gantiPasswordIntent.putExtra("username", username); // Meneruskan username ke GantiPasswordActivity
                        startActivity(gantiPasswordIntent);
                        break;
                    case 2:
                        // FAQ
                        startActivity(new Intent(requireContext(), FaqActivity.class));
                        break;
                    case 3:
                        // Tentang Kami
                        startActivity(new Intent(requireContext(), TentangActivity.class));
                        break;
                }
            }
        });

        // Tangani klik tombol logout
        logoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Tampilkan dialog konfirmasi logout
                showLogoutConfirmationDialog();
            }
        });

        // Periksa apakah profil telah diperbarui dari DataDiriActivity
        if (getActivity() != null) {
            Intent intent = getActivity().getIntent();
            if (intent != null && intent.getBooleanExtra("profileUpdated", false)) {
                // Panggil kembali setProfileImageFromFirebase untuk memperbarui gambar profil
                setProfileImageFromFirebase(imageProfile, username);
            }
        }

        return view;
    }

    // Method untuk menampilkan dialog konfirmasi logout
    private void showLogoutConfirmationDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());

        // Inflate layout custom dialog
        View view = getLayoutInflater().inflate(R.layout.dialog_logout_confirmation, null);
        TextView titleTextView = view.findViewById(R.id.dialog_title);
        TextView messageTextView = view.findViewById(R.id.dialog_message);

        titleTextView.setTextColor(getResources().getColor(R.color.grey)); // Warna judul
        messageTextView.setTextColor(getResources().getColor(R.color.grey)); // Warna teks pesan
        messageTextView.setTypeface(ResourcesCompat.getFont(requireContext(), R.font.poppins_regular)); // Gaya font

        builder.setView(view);

        builder.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Logout
                performLogout();
            }
        });

        builder.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Batalkan operasi logout
                dialog.dismiss();
            }
        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }

    // Method untuk melakukan logout
    private void performLogout() {
        // Hapus data login dari SharedPreferences
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove("isLoggedIn");
        editor.remove("username");
        editor.apply();

        // Kembali ke LoginActivity
        Intent intent = new Intent(requireContext(), LoginActivity.class);
        startActivity(intent);
        requireActivity().finish();
    }

    // Method untuk menampilkan gambar profil dari Firebase Storage
    // Method untuk menampilkan gambar profil dari Firebase Storage
    private void setProfileImageFromFirebase(ImageView imageView, String username) {
        DatabaseReference userRef = FirebaseDatabase.getInstance().getReference().child("users").child(username);

        userRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    User user = dataSnapshot.getValue(User.class);
                    if (user != null) {
                        String imageUrl = user.getProfileImageUrl();
                        if (imageUrl != null && !imageUrl.isEmpty()) {
                            // Tampilkan gambar menggunakan Glide
                            Glide.with(requireContext()) // Ganti getApplicationContext() dengan requireContext()
                                    .load(imageUrl)
                                    .transform(new CircleCrop())
                                    .placeholder(R.drawable.ic_profil)
                                    .error(R.drawable.ic_profil)
                                    .into(imageView);
                        } else {
                            // Jika tidak ada gambar profil yang tersedia, tampilkan gambar default di sini
                            // Misalnya:
                            imageView.setImageResource(R.drawable.ic_profile);
                        }
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                // Tangani kesalahan saat mengambil data dari Firebase Database
                Toast.makeText(requireContext(), "Gagal memuat foto profil: " + databaseError.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}
