package com.example.pap_findu.ui.profile;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

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

import com.bumptech.glide.Glide;
import com.example.pap_findu.EditProfileActivity;
import com.example.pap_findu.R;
import com.example.pap_findu.SecurityActivity;
import com.example.pap_findu.databinding.FragmentProfileBinding;
import com.example.pap_findu.models.User;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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;

public class ProfileFragment extends Fragment {

    private FragmentProfileBinding binding;
    private FirebaseAuth mAuth;
    private DatabaseReference mDatabase;
    private ValueEventListener mUserListener;
    private DatabaseReference mUserRef;

    public View onCreateView(@NonNull LayoutInflater inflater,
            ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentProfileBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        mAuth = FirebaseAuth.getInstance();
        FirebaseUser currentUser = mAuth.getCurrentUser();

        if (currentUser == null) {
            // Should prompt login or handle error
            return root;
        }

        mDatabase = FirebaseDatabase.getInstance().getReference("users");
        mUserRef = mDatabase.child(currentUser.getUid());

        setupListeners();

        // Listen for user data changes
        mUserListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (getContext() == null)
                    return;

                User user = snapshot.getValue(User.class);
                if (user != null) {
                    binding.profileName.setText(user.getName());
                    binding.profileEmail.setText(user.getEmail());

                    if (user.getProfileImageUrl() != null && !user.getProfileImageUrl().isEmpty()) {
                        Glide.with(ProfileFragment.this)
                                .load(user.getProfileImageUrl())
                                .placeholder(R.drawable.logo) // Make sure logo exists or use R.mipmap.ic_launcher
                                .into(binding.profileImage);
                    } else {
                        binding.profileImage.setImageResource(R.drawable.logo);
                    }
                } else {
                    // Fallback to Auth data if DB is empty
                    binding.profileName.setText(
                            currentUser.getDisplayName() != null ? currentUser.getDisplayName() : "Utilizador");
                    binding.profileEmail.setText(currentUser.getEmail());
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                if (getContext() != null)
                    Toast.makeText(getContext(), "Erro ao carregar perfil", Toast.LENGTH_SHORT).show();
            }
        };

        return root;
    }

    private void setupListeners() {
        binding.layoutEditProfile.setOnClickListener(v -> {
            startActivity(new Intent(getActivity(), EditProfileActivity.class));
        });

        binding.layoutSecurity.setOnClickListener(v -> {
            startActivity(new Intent(getActivity(), SecurityActivity.class));
        });

        binding.btnLogout.setOnClickListener(v -> {
            mAuth.signOut();
            Intent intent = new Intent(getActivity(), com.example.pap_findu.login_activity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        if (mUserRef != null && mUserListener != null) {
            mUserRef.addValueEventListener(mUserListener);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mUserRef != null && mUserListener != null) {
            mUserRef.removeEventListener(mUserListener);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}
