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");
                });
            }
        });
    }

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

        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);
        EditText editPassword = dialogView.findViewById(R.id.edit_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);
        editPassword.setText(currentUser.password);

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

            if (newName.isEmpty() || ageStr.isEmpty() || newUtente.isEmpty() || newEmail.isEmpty()
                    || newPassword.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;
            currentUser.password = newPassword;

            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
            binding.profileName.setText(newName);
            binding.profileEmail.setText(newEmail);
            binding.profileAge.setText(String.valueOf(newAge));
            binding.profileUtente.setText(newUtente);

            Toast.makeText(getContext(), "Dados atualizados com sucesso!", Toast.LENGTH_SHORT).show();
            dialog.dismiss();
        });

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

        dialog.show();
    }

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