package com.example.cuida.ui.profile;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.example.cuida.R;
import com.example.cuida.databinding.FragmentProfileBinding;
import com.example.cuida.data.model.User;
import com.example.cuida.ui.auth.LoginActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;

import java.util.HashMap;
import java.util.Map;

public class ProfileFragment extends Fragment {

    private FragmentProfileBinding binding;
    private FirebaseAuth auth;
    private FirebaseFirestore db;
    private FirebaseStorage storage;
    private User currentUser;
    private String userId;
    
    private ImageView dialogImageView;
    private Uri tempProfileUri;

    private final ActivityResultLauncher<String> pickMedia = registerForActivityResult(
            new ActivityResultContracts.GetContent(), uri -> {
                if (uri != null && dialogImageView != null) {
                    tempProfileUri = uri;
                    if (getContext() != null) {
                        Glide.with(getContext()).load(uri).circleCrop().into(dialogImageView);
                    }
                }
            });

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

        auth = FirebaseAuth.getInstance();
        db = FirebaseFirestore.getInstance();
        storage = FirebaseStorage.getInstance();
        
        if (auth.getCurrentUser() != null) {
            userId = auth.getCurrentUser().getUid();
            
            // Pré-inicializar com dados do Auth para evitar ecrã vazio
            currentUser = new User();
            currentUser.id = userId;
            currentUser.email = auth.getCurrentUser().getEmail();
            currentUser.name = auth.getCurrentUser().getDisplayName();
            
            Log.d("ProfileFragment", "User ID: " + userId + " Email: " + currentUser.email);
            
            // Atualizar UI inicial com o que temos do Auth
            if (currentUser.email != null) binding.profileEmail.setText(currentUser.email);
            if (currentUser.name != null && !currentUser.name.isEmpty()) binding.profileName.setText(currentUser.name);
            
            loadUserData();
        }

        binding.buttonEditProfile.setOnClickListener(v -> showEditDialog());

        // --- Dark Mode Logic ---
        android.content.SharedPreferences themePrefs = requireContext().getSharedPreferences("theme_prefs", Context.MODE_PRIVATE);
        boolean isDarkMode = themePrefs.getBoolean("dark_mode", false);
        
        // Desativar listener temporariamente para evitar loop de recriação
        binding.switchDarkMode.setOnCheckedChangeListener(null);
        binding.switchDarkMode.setChecked(isDarkMode);

        binding.switchDarkMode.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isAdded() && buttonView.isPressed()) {
                themePrefs.edit().putBoolean("dark_mode", isChecked).apply();
                if (isChecked) {
                    androidx.appcompat.app.AppCompatDelegate.setDefaultNightMode(androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES);
                } else {
                    androidx.appcompat.app.AppCompatDelegate.setDefaultNightMode(androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_NO);
                }
            }
        });

        binding.buttonLogout.setOnClickListener(v -> {
            auth.signOut();
            if (getContext() != null) {
                requireContext().getSharedPreferences("prefs", Context.MODE_PRIVATE).edit().clear().apply();
            }
            startActivity(new Intent(getContext(), LoginActivity.class));
            requireActivity().finish();
        });

            return root;
        } catch (Exception e) {
            Log.e("ProfileFragment", "Erro ao inflar perfil", e);
            return inflater.inflate(R.layout.fragment_profile, container, false);
        }
    }

    private void loadUserData() {
        try {
            if (userId == null || !isAdded()) return;

            Log.d("ProfileFragment", "Starting loadUserData for " + userId);
            // Primeiro tenta na coleção geral 'utilizadores'
            db.collection("utilizadores").document(userId).addSnapshotListener((doc, error) -> {
                if (error != null) {
                    Log.e("ProfileFragment", "Error in utilizadores listener", error);
                }
                try {
                    if (doc != null && doc.exists()) {
                        Log.d("ProfileFragment", "Found in utilizadores: " + doc.getData());
                        updateUIFromDocument(doc);
                    } else {
                        Log.d("ProfileFragment", "Not found in utilizadores");
                    }
                    
                    // Tenta TAMBÉM em 'Pacientes' para completar dados (ex: vindos da App Médica)
                    db.collection("Pacientes").document(userId).get().addOnSuccessListener(docP -> {
                        if (docP != null && docP.exists()) {
                            Log.d("ProfileFragment", "Found in Pacientes: " + docP.getData());
                            updateUIFromDocument(docP);
                        } else {
                            Log.d("ProfileFragment", "Not found in Pacientes");
                        }
                    }).addOnFailureListener(e -> Log.e("ProfileFragment", "Error in Pacientes get", e));
                } catch (Exception e) {
                    Log.e("ProfileFragment", "Erro no processamento de documentos", e);
                }
            });
        } catch (Exception e) {
            Log.e("ProfileFragment", "Erro ao iniciar", e);
        }
    }

    private void updateUIFromDocument(com.google.firebase.firestore.DocumentSnapshot doc) {
        if (!isAdded() || binding == null) return;
        
        // Nome
        String n = doc.getString("nome_completo");
        if (n == null) n = doc.getString("name");
        if (n == null) n = doc.getString("nome");
        if (n != null && !n.isEmpty()) binding.profileName.setText(n);
        
        // Email
        String e = doc.getString("email");
        if (e != null && !e.isEmpty()) binding.profileEmail.setText(e);
        
        // Idade
        Object idadeObj = doc.get("idade");
        Integer idadeVal = null;
        if (idadeObj instanceof Long) {
            idadeVal = ((Long) idadeObj).intValue();
        } else if (idadeObj instanceof String) {
            try { idadeVal = Integer.parseInt((String) idadeObj); } catch (Exception ignored) {}
        }
        if (idadeVal != null) binding.profileAge.setText(String.valueOf(idadeVal));
        
        // Nº Utente
        String u = doc.getString("numero_utente");
        if (u == null) u = doc.getString("utenteNumber");
        if (u != null && !u.isEmpty()) binding.profileUtente.setText(u);
        
        // Foto
        String p = doc.getString("profilePictureUri");
        if (p != null && !p.isEmpty()) {
            loadSafeImage(binding.profileImage, p);
        }

        // Atualiza objeto local para o EditDialog
        if (currentUser == null) currentUser = new User();
        if (n != null) currentUser.name = n;
        if (e != null) currentUser.email = e;
        if (idadeVal != null) currentUser.age = idadeVal;
        if (u != null) currentUser.utenteNumber = u;
        if (p != null) currentUser.profilePictureUri = p;
        currentUser.id = doc.getId();
    }

    private void loadSafeImage(ImageView view, String url) {
        try {
            if (!isAdded() || view == null || getContext() == null) return;
            Glide.with(getContext())
                .load(url)
                .placeholder(R.drawable.ic_user)
                .circleCrop()
                .into(view);
        } catch (Exception e) {
            Log.e("ProfileFragment", "Erro ao carregar imagem", e);
        }
    }

    private void showEditDialog() {
        if (!isAdded()) return;
        if (currentUser == null) currentUser = new User();

        try {
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext(), R.style.CustomDialogTheme);
            View dialogView = requireActivity().getLayoutInflater().inflate(R.layout.dialog_edit_profile, null);
            builder.setView(dialogView);
            AlertDialog dialog = builder.create();
            if (dialog.getWindow() != null) dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

            EditText editName = dialogView.findViewById(R.id.edit_name);
            EditText editAge = dialogView.findViewById(R.id.edit_age);
            EditText editUtente = dialogView.findViewById(R.id.edit_utente);
            EditText editEmail = dialogView.findViewById(R.id.edit_email);
            dialogImageView = dialogView.findViewById(R.id.edit_profile_image);

            // Preenchimento Seguro e Infalível
            if (currentUser == null) {
                currentUser = new User();
                currentUser.id = userId;
            }
            if (currentUser.email == null || currentUser.email.isEmpty()) {
                if (auth.getCurrentUser() != null) currentUser.email = auth.getCurrentUser().getEmail();
            }
            
            Log.d("ProfileFragment", "Opening EditDialog. Email to show: " + currentUser.email);

            if (editName != null) editName.setText(currentUser.name);
            if (editAge != null) editAge.setText(currentUser.age > 0 ? String.valueOf(currentUser.age) : "");
            if (editUtente != null) editUtente.setText(currentUser.utenteNumber);
            if (editEmail != null) {
                editEmail.setText(currentUser.email);
                Log.d("ProfileFragment", "editEmail set to: " + editEmail.getText().toString());
            }
            if (dialogImageView != null && currentUser.profilePictureUri != null && !currentUser.profilePictureUri.isEmpty()) {
                loadSafeImage(dialogImageView, currentUser.profilePictureUri);
            }

            // Listeners
            View btnPhoto = dialogView.findViewById(R.id.button_change_photo);
            if (btnPhoto != null) btnPhoto.setOnClickListener(v -> pickMedia.launch("image/*"));
            if (dialogImageView != null) dialogImageView.setOnClickListener(v -> pickMedia.launch("image/*"));
            
            View btnPass = dialogView.findViewById(R.id.button_change_password);
            if (btnPass != null) btnPass.setOnClickListener(v -> showChangePasswordDialog());

            View btnCancel = dialogView.findViewById(R.id.button_cancel);
            if (btnCancel != null) btnCancel.setOnClickListener(v -> dialog.dismiss());

            View btnSave = dialogView.findViewById(R.id.button_save);
            if (btnSave != null) {
                btnSave.setOnClickListener(v -> {
                    String nameStr = editName != null ? editName.getText().toString().trim() : "";
                    String ageStr = editAge != null ? editAge.getText().toString().trim() : "";
                    String utenteStr = editUtente != null ? editUtente.getText().toString().trim() : "";
                    String emailStr = editEmail != null ? editEmail.getText().toString().trim() : "";

                    if (nameStr.isEmpty() || ageStr.isEmpty() || emailStr.isEmpty() || utenteStr.isEmpty()) {
                        Toast.makeText(getContext(), "Preencha os campos.", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (utenteStr.length() != 9) {
                        Toast.makeText(getContext(), "Utente deve ter 9 dígitos.", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    btnSave.setEnabled(false);
                    if (tempProfileUri != null) {
                        uploadPhotoAndSave(nameStr, ageStr, utenteStr, emailStr, dialog);
                    } else {
                        saveDataToFirestore(nameStr, ageStr, utenteStr, emailStr, currentUser.profilePictureUri, dialog);
                    }
                });
            }

            dialog.show();
        } catch (Throwable t) {
            Toast.makeText(getContext(), "Erro: " + t.toString(), Toast.LENGTH_LONG).show();
        }
    }

    private void uploadPhotoAndSave(String n, String a, String u, String e, AlertDialog d) {
        StorageReference ref = storage.getReference().child("perfil_pacientes/" + userId + ".jpg");
        ref.putFile(tempProfileUri).addOnSuccessListener(task -> {
            ref.getDownloadUrl().addOnSuccessListener(uri -> saveDataToFirestore(n, a, u, e, uri.toString(), d));
        }).addOnFailureListener(err -> {
            Toast.makeText(getContext(), "Erro foto", Toast.LENGTH_SHORT).show();
            saveDataToFirestore(n, a, u, e, currentUser.profilePictureUri, d);
        });
    }

    private void saveDataToFirestore(String name, String age, String utente, String email, String photo, AlertDialog d) {
        Map<String, Object> map = new HashMap<>();
        map.put("nome_completo", name);
        map.put("email", email);
        try { map.put("idade", Integer.parseInt(age)); } catch (Exception ignored) {
            map.put("idade", 0);
        }
        map.put("numero_utente", utente);
        map.put("tipo", "paciente");
        if (photo != null) map.put("profilePictureUri", photo);

        com.google.firebase.firestore.WriteBatch batch = db.batch();
        batch.set(db.collection("utilizadores").document(userId), map, com.google.firebase.firestore.SetOptions.merge());
        batch.set(db.collection("Pacientes").document(userId), map, com.google.firebase.firestore.SetOptions.merge());

        batch.commit().addOnSuccessListener(aVoid -> {
            if (isAdded()) {
                Toast.makeText(getContext(), "Perfil Atualizado com Sucesso!", Toast.LENGTH_SHORT).show();
                loadUserData();
                d.dismiss();
                tempProfileUri = null;
            }
        }).addOnFailureListener(e -> {
            if (isAdded()) {
                Toast.makeText(getContext(), "Erro ao guardar no Firebase", Toast.LENGTH_SHORT).show();
                d.dismiss();
            }
        });
    }

    private void showChangePasswordDialog() {
        Toast.makeText(getContext(), "Funcionalidade de Password em breve.", Toast.LENGTH_SHORT).show();
    }

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