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 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;
import androidx.annotation.NonNull;

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;

    private java.util.Set<String> favoriteClubs = new java.util.HashSet<>();
    private DatabaseReference favoritesRef;
    private ValueEventListener favoritesListener;
    private DatabaseReference senioresRef;
    private ValueEventListener senioresListener;
    private DatabaseReference junioresRef;
    private ValueEventListener junioresListener;

    @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();

        // Inicializar o sistema de notificações para favoritos
        setupNotificationSystem();
    }

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

        // 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();
    }

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

        createNotificationChannel();

        // Listen to favorites
        favoritesRef = FirebaseDatabase.getInstance().getReference("users")
                .child(user.getUid())
                .child("favorites");

        favoritesListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                favoriteClubs.clear();
                for (DataSnapshot favSnap : snapshot.getChildren()) {
                    if (Boolean.TRUE.equals(favSnap.getValue(Boolean.class))) {
                        favoriteClubs.add(favSnap.getKey());
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {}
        };
        favoritesRef.addValueEventListener(favoritesListener);

        // Listen to seniores matches
        senioresRef = FirebaseDatabase.getInstance().getReference("jornadas").child("seniores");
        senioresListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                checkMatchesAndNotify(snapshot);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {}
        };
        senioresRef.addValueEventListener(senioresListener);

        // Listen to juniores matches
        junioresRef = FirebaseDatabase.getInstance().getReference("jornadas").child("juniores");
        junioresListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                checkMatchesAndNotify(snapshot);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {}
        };
        junioresRef.addValueEventListener(junioresListener);
    }

    private void checkMatchesAndNotify(DataSnapshot categorySnapshot) {
        if (favoriteClubs.isEmpty()) return;

        android.content.SharedPreferences prefs = getSharedPreferences("NotifiedMatchesPrefs", android.content.Context.MODE_PRIVATE);
        android.content.SharedPreferences.Editor editor = prefs.edit();

        for (DataSnapshot jornadaSnap : categorySnapshot.getChildren()) {
            for (DataSnapshot matchSnap : jornadaSnap.getChildren()) {
                com.example.vdcscore.ui.gallery.Match match = matchSnap.getValue(com.example.vdcscore.ui.gallery.Match.class);
                if (match != null) {
                    match.setId(matchSnap.getKey());
                    
                    if (match.isPlayed() && match.getId() != null) {
                        boolean involvesFavorite = false;
                        String favoriteName = "";
                        
                        String homeSanitized = com.example.vdcscore.utils.FirebaseErrorUtils.sanitizeKey(match.getHomeName());
                        String awaySanitized = com.example.vdcscore.utils.FirebaseErrorUtils.sanitizeKey(match.getAwayName());

                        if (homeSanitized != null && favoriteClubs.contains(homeSanitized)) {
                            involvesFavorite = true;
                            favoriteName = match.getHomeName();
                        } else if (awaySanitized != null && favoriteClubs.contains(awaySanitized)) {
                            involvesFavorite = true;
                            favoriteName = match.getAwayName();
                        }

                        if (involvesFavorite) {
                            String matchPrefKey = "notified_" + match.getId();
                            if (!prefs.getBoolean(matchPrefKey, false)) {
                                // Trigger notification!
                                triggerLocalNotification(match, favoriteName);
                                // Mark as notified
                                editor.putBoolean(matchPrefKey, true);
                            }
                        }
                    }
                }
            }
        }
        editor.apply();
    }

    private void triggerLocalNotification(com.example.vdcscore.ui.gallery.Match match, String favoriteClub) {
        String homeScoreStr = match.getHomeScore() != null ? String.valueOf(match.getHomeScore()) : "0";
        String awayScoreStr = match.getAwayScore() != null ? String.valueOf(match.getAwayScore()) : "0";
        
        String title = "Fim de Jogo - " + favoriteClub;
        String message = match.getHomeName() + " " + homeScoreStr + " - " + awayScoreStr + " " + match.getAwayName();

        androidx.core.app.NotificationCompat.Builder builder = new androidx.core.app.NotificationCompat.Builder(this, "vdcscore_notifications")
                .setSmallIcon(R.drawable.ic_soccer)
                .setContentTitle(title)
                .setContentText(message)
                .setPriority(androidx.core.app.NotificationCompat.PRIORITY_DEFAULT)
                .setAutoCancel(true);

        // Click action: open MainActivity
        android.content.Intent intent = new android.content.Intent(this, MainActivity.class);
        intent.setFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK | android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK);
        android.app.PendingIntent pendingIntent = android.app.PendingIntent.getActivity(
                this, 0, intent, android.app.PendingIntent.FLAG_UPDATE_CURRENT | android.app.PendingIntent.FLAG_IMMUTABLE);
        builder.setContentIntent(pendingIntent);

        android.app.NotificationManager notificationManager = (android.app.NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            int notificationId = match.getId().hashCode();
            notificationManager.notify(notificationId, builder.build());
        }
    }

    private void createNotificationChannel() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            CharSequence name = "Resultados dos Jogos";
            String description = "Notificações de resultados dos jogos dos seus clubes favoritos";
            int importance = android.app.NotificationManager.IMPORTANCE_DEFAULT;
            android.app.NotificationChannel channel = new android.app.NotificationChannel("vdcscore_notifications", name, importance);
            channel.setDescription(description);
            android.app.NotificationManager notificationManager = getSystemService(android.app.NotificationManager.class);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (favoritesRef != null && favoritesListener != null) {
            favoritesRef.removeEventListener(favoritesListener);
        }
        if (senioresRef != null && senioresListener != null) {
            senioresRef.removeEventListener(senioresListener);
        }
        if (junioresRef != null && junioresListener != null) {
            junioresRef.removeEventListener(junioresListener);
        }
    }
}
