package com.example.pap_findu.ui.profile;

import android.content.Intent;
import android.os.Bundle;
import android.util.Base64;
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.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 mUserRef;
    private ValueEventListener mUserListener;

    @Override
    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) {
            return root;
        }

        setupListeners();

        // Verifica se é o Filho (Anónimo)
        if (currentUser.isAnonymous()) {
            binding.profileName.setText("Conta de Criança");
            binding.profileEmail.setText("Modo de Monitorização Ativo");
            binding.profileImage.setImageResource(R.drawable.logo);

            // Oculta opções que não fazem sentido para o Filho
            binding.layoutEditProfile.setVisibility(View.GONE);

        } else {
            // É O PAI: Carrega os dados reais do Firebase
            mUserRef = FirebaseDatabase.getInstance().getReference("users").child(currentUser.getUid());

            mUserListener = new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    if (getContext() == null || binding == null) return;

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

                            // MAGIA: LER A FOTO EM FORMATO DE TEXTO (BASE64)
                            if (user.getProfileImageUrl() != null && !user.getProfileImageUrl().isEmpty()) {
                                try {
                                    byte[] decodedString = Base64.decode(user.getProfileImageUrl(), Base64.DEFAULT);
                                    Glide.with(ProfileFragment.this)
                                            .load(decodedString)
                                            .placeholder(R.drawable.logo)
                                            .into(binding.profileImage);
                                } catch (Exception e) {
                                    // Fallback caso a imagem seja um link antigo e não Base64
                                    try {
                                        Glide.with(ProfileFragment.this)
                                                .load(user.getProfileImageUrl())
                                                .placeholder(R.drawable.logo)
                                                .into(binding.profileImage);
                                    } catch (Exception ex) {
                                        binding.profileImage.setImageResource(R.drawable.logo);
                                    }
                                }
                            } else {
                                binding.profileImage.setImageResource(R.drawable.logo);
                            }
                        }
                    }
                }

                @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.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;
    }
}