package com.example.vdcscore;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;

import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;

import com.example.vdcscore.databinding.ActivityMainBinding;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

import java.io.InputStream;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.text.InputType;
import android.widget.EditText;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.google.firebase.auth.UserProfileChangeRequest;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;
    private ActivityMainBinding binding;
    private ActivityResultLauncher<String> mGetContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Carregar preferência do Dark Mode
        android.content.SharedPreferences prefs = getSharedPreferences("SettingsPrefs",
                android.content.Context.MODE_PRIVATE);
        boolean isDarkMode = prefs.getBoolean("dark_mode", false);
        if (isDarkMode) {
            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 = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.appBarMain.toolbar);

        DrawerLayout drawer = binding.drawerLayout;
        NavigationView navigationView = binding.navView;
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_cup, R.id.nav_definicoes,
                R.id.nav_live_games, R.id.nav_clubs, R.id.nav_top_scorers, R.id.nav_news)
                .setOpenableLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

        // Initialize Gallery Launcher
        mGetContent = registerForActivityResult(new ActivityResultContracts.GetContent(),
                uri -> {
                    if (uri != null) {
                        uploadImageToStorage(uri);
                    }
                });

        // Carregar dados do utilizador no menu lateral
        loadUserDataInNavHeader();
    }

    private void loadUserDataInNavHeader() {
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user == null)
            return;

        View headerView = binding.navView.getHeaderView(0);
        TextView textViewName = headerView.findViewById(R.id.textViewName);
        ImageView imageView = headerView.findViewById(R.id.imageView);

        // Carregar nome
        if (textViewName != null) {
            if (user.getDisplayName() != null && !user.getDisplayName().isEmpty()) {
                textViewName.setText(user.getDisplayName());
            } else {
                textViewName.setText("Utilizador");
            }
        }

        // Carregar foto de perfil
        if (imageView != null) {
            imageView.setOnClickListener(v -> showChangeProfilePhotoDialog());
            if (user.getPhotoUrl() != null) {
                loadProfileImageInNavHeader(user.getPhotoUrl().toString(), imageView);
            } else {
                // Tentar carregar do Storage
                loadProfileImageFromStorage(imageView);
            }
        }
    }

    private void loadProfileImageInNavHeader(String imageUrl, ImageView imageView) {
        if (imageUrl == null || imageView == null) return;
        Glide.with(this)
             .load(imageUrl)
             .placeholder(R.mipmap.ic_launcher_round)
             .error(R.mipmap.ic_launcher)
             .circleCrop()
             .into(imageView);
    }

    private void loadProfileImageFromStorage(ImageView imageView) {
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user == null || imageView == null)
            return;

        com.google.firebase.storage.FirebaseStorage.getInstance()
                .getReference()
                .child("profile_images/" + user.getUid() + ".jpg")
                .getDownloadUrl()
                .addOnSuccessListener(uri -> {
                    loadProfileImageInNavHeader(uri.toString(), imageView);
                })
                .addOnFailureListener(e -> {
                    // Manter imagem padrão
                });
    }

    private void showChangeProfilePhotoDialog() {
        mGetContent.launch("image/*");
    }

    private void uploadImageToStorage(Uri imageUri) {
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user == null)
            return;

        StorageReference storageRef = com.google.firebase.storage.FirebaseStorage.getInstance().getReference();
        StorageReference profileRef = storageRef.child("profile_images/" + user.getUid() + ".jpg");

        Toast.makeText(this, "A carregar imagem...", Toast.LENGTH_SHORT).show();

        profileRef.putFile(imageUri)
                .addOnSuccessListener(taskSnapshot -> {
                    profileRef.getDownloadUrl().addOnSuccessListener(uri -> {
                        updateUserProfile(uri);
                    });
                })
                .addOnFailureListener(e -> {
                    Toast.makeText(MainActivity.this, "Erro ao carregar imagem: " + e.getMessage(), Toast.LENGTH_SHORT)
                            .show();
                });
    }

    private void updateUserProfile(Uri photoUri) {
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user == null)
            return;

        UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                .setPhotoUri(photoUri)
                .build();

        user.updateProfile(profileUpdates)
                .addOnCompleteListener(task -> {
                    if (task.isSuccessful()) {
                        Toast.makeText(MainActivity.this, "Foto de perfil atualizada!", Toast.LENGTH_SHORT).show();
                        loadUserDataInNavHeader(); // Refresh UI
                    } else {
                        Toast.makeText(MainActivity.this, "Erro ao atualizar perfil.", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        // getMenuInflater().inflate(R.menu.main, menu);
        return false;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // Atualizar dados do utilizador quando voltar à activity
        loadUserDataInNavHeader();
    }
}
