package com.example.cuida.ui.profile;

import android.app.AlertDialog;
import android.content.Context;
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.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.cuida.data.AppDatabase;
import com.example.cuida.data.dao.UserDao;
import com.example.cuida.data.model.User;
import com.example.cuida.R;
import com.example.cuida.databinding.FragmentProfileBinding;
import com.example.cuida.ui.auth.LoginActivity;

public class ProfileFragment extends Fragment {

    private FragmentProfileBinding binding;
    private User currentUser;
    private UserDao userDao;

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

        userDao = AppDatabase.getDatabase(requireContext()).userDao();
        loadUserData();

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

        binding.buttonLogout.setOnClickListener(v -> {
            getContext().getSharedPreferences("prefs", Context.MODE_PRIVATE).edit().clear().apply();
            Intent intent = new Intent(getContext(), LoginActivity.class);
            startActivity(intent);
            getActivity().finish();
        });

        return binding.getRoot();
    }

    private void loadUserData() {
        SharedPreferences prefs = requireContext().getSharedPreferences("prefs", Context.MODE_PRIVATE);
        String email = prefs.getString("user_email", "");

        AppDatabase.databaseWriteExecutor.execute(() -> {
            currentUser = userDao.checkUser(email);
            if (currentUser != null) {
                getActivity().runOnUiThread(() -> {
                    binding.profileName.setText(currentUser.name);
                    binding.profileEmail.setText(currentUser.email);
                    binding.profileAge.setText(String.valueOf(currentUser.age));
                    binding.profileUtente.setText(currentUser.utenteNumber != null ? currentUser.utenteNumber : "N/A");
                    if (currentUser.profilePictureUri != null) {
                        android.widget.ImageView profileImage = binding.getRoot().findViewById(R.id.profile_image);
                        if (profileImage != null) {
                            try {
                                profileImage.setImageURI(android.net.Uri.parse(currentUser.profilePictureUri));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
            }
        });
    }

    private android.net.Uri tempProfileUri;
    private android.widget.ImageView dialogImageView;

    private final androidx.activity.result.ActivityResultLauncher<String> pickMedia = registerForActivityResult(
            new androidx.activity.result.contract.ActivityResultContracts.GetContent(), uri -> {
                if (uri != null) {
                    tempProfileUri = uri;
                    try {
                        requireContext().getContentResolver().takePersistableUriPermission(uri,
                                Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (dialogImageView != null) {
                        dialogImageView.setImageURI(uri);
                    }
                }
            });

    private void showEditDialog() {
        if (currentUser == null) {
            Toast.makeText(getContext(), "Erro: Utilizador não carregado.", Toast.LENGTH_SHORT).show();
            return;
        }

        // Reset temp uri
        tempProfileUri = null;

        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());

        // Inflate custom layout
        LayoutInflater inflater = requireActivity().getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_edit_profile, null);
        builder.setView(dialogView);

        AlertDialog dialog = builder.create();

        // Bind Views
        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);
        View btnChangePassword = dialogView.findViewById(R.id.button_change_password);
        View btnSave = dialogView.findViewById(R.id.button_save);
        View btnCancel = dialogView.findViewById(R.id.button_cancel);

        // Pre-fill data
        editName.setText(currentUser.name);
        editAge.setText(String.valueOf(currentUser.age));
        editUtente.setText(currentUser.utenteNumber);
        editEmail.setText(currentUser.email);

        if (currentUser.profilePictureUri != null) {
            dialogImageView.setImageURI(android.net.Uri.parse(currentUser.profilePictureUri));
        }

        dialogImageView.setOnClickListener(v -> pickMedia.launch("image/*"));

        btnChangePassword.setOnClickListener(v -> {
            showChangePasswordDialog();
        });

        btnSave.setOnClickListener(v -> {
            String newName = editName.getText().toString();
            String ageStr = editAge.getText().toString();
            String newUtente = editUtente.getText().toString();
            String newEmail = editEmail.getText().toString();

            if (newName.isEmpty() || ageStr.isEmpty() || newUtente.isEmpty() || newEmail.isEmpty()) {
                Toast.makeText(getContext(), "Preencha todos os campos", Toast.LENGTH_SHORT).show();
                return;
            }

            int newAge = Integer.parseInt(ageStr);
            boolean emailChanged = !newEmail.equals(currentUser.email);

            currentUser.name = newName;
            currentUser.age = newAge;
            currentUser.utenteNumber = newUtente;
            currentUser.email = newEmail;
            // Password not updated here
            if (tempProfileUri != null) {
                currentUser.profilePictureUri = tempProfileUri.toString();
            }

            AppDatabase.databaseWriteExecutor.execute(() -> {
                userDao.insert(currentUser);
            });

            // Update SharedPreferences if email changed (key for login persistence)
            if (emailChanged) {
                getContext().getSharedPreferences("prefs", Context.MODE_PRIVATE)
                        .edit()
                        .putString("user_email", newEmail)
                        .apply();
            }

            // UI update
            loadUserData(); // Reload to show new image and data

            Toast.makeText(getContext(), "Dados atualizados com sucesso!", Toast.LENGTH_SHORT).show();
            dialog.dismiss();
            dialogImageView = null; // Clear reference
        });

        btnCancel.setOnClickListener(v -> {
            dialog.dismiss();
            dialogImageView = null;
        });

        dialog.show();
    }

    private void showChangePasswordDialog() {
        if (currentUser == null)
            return;

        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        LayoutInflater inflater = requireActivity().getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_change_password, null);
        builder.setView(dialogView);
        AlertDialog dialog = builder.create();

        EditText editNewPassword = dialogView.findViewById(R.id.new_password);
        View btnSave = dialogView.findViewById(R.id.button_save_password);
        View btnCancel = dialogView.findViewById(R.id.button_cancel_password);

        btnSave.setOnClickListener(v -> {
            String newPass = editNewPassword.getText().toString();
            if (newPass.isEmpty()) {
                Toast.makeText(getContext(), "Insira a nova palavra-passe", Toast.LENGTH_SHORT).show();
                return;
            }

            currentUser.password = newPass;
            AppDatabase.databaseWriteExecutor.execute(() -> {
                userDao.insert(currentUser);
            });

            Toast.makeText(getContext(), "Palavra-passe alterada!", Toast.LENGTH_SHORT).show();
            dialog.dismiss();
        });

        btnCancel.setOnClickListener(v -> dialog.dismiss());
        dialog.show();
    }

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