package com.example.pap_teste;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.pap_teste.models.Restaurant;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;
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 java.util.ArrayList;
import java.util.List;

public class ClientDashboardActivity extends AppCompatActivity {

    private String email, displayName;
    private TextView txtGreeting;
    private ImageView imgProfile;
    private EditText etSearch;
    private RecyclerView rvFeatured;
    private ProgressBar progressBar;
    private View layoutFeatured;
    private android.widget.LinearLayout categoriesContainer;

    private List<Restaurant> allRestaurants = new ArrayList<>();
    private List<Restaurant> filteredRestaurants = new ArrayList<>();

    private FeaturedRestaurantAdapter featuredAdapter;

    private final String[] CATEGORIES = { "Carnes", "Massas", "Sushi", "Pizzas", "Sobremesas" };
    private String currentSearchFilter = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_client_dashboard);

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.clientRoot), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        email = getIntent().getStringExtra(MainActivity.EXTRA_EMAIL);
        displayName = getIntent().getStringExtra(MainActivity.EXTRA_DISPLAY_NAME);

        initViews();
        setupBottomNavigation();
        setupSearch();

        updateGreeting();
        fetchProfilePicture();
        fetchRestaurants();
        
        // Iniciar serviço de notificações se for Android O ou superior
        Intent serviceIntent = new Intent(this, ReservationNotificationService.class);
        startService(serviceIntent);
    }

    private RestaurantAdapter.OnRestaurantClickListener clickListener;

    private void initViews() {
        txtGreeting = findViewById(R.id.txtClientGreeting);
        imgProfile = findViewById(R.id.imgProfile);
        etSearch = findViewById(R.id.etSearch);
        rvFeatured = findViewById(R.id.rvFeatured);
        progressBar = findViewById(R.id.progressBar);
        layoutFeatured = findViewById(R.id.layoutFeatured);
        categoriesContainer = findViewById(R.id.categoriesContainer);

        rvFeatured.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));

        // Click listener for restaurants to open booking flow
        clickListener = restaurant -> {
            Intent intent = new Intent(this, ExplorarRestaurantesActivity.class);
            intent.putExtra("restaurant", restaurant);
            startActivity(intent);
        };

        featuredAdapter = new FeaturedRestaurantAdapter(new ArrayList<>(), clickListener);
        rvFeatured.setAdapter(featuredAdapter);

        // Click listener for profile picture in the header
        findViewById(R.id.cardProfile).setOnClickListener(v -> {
            Intent intent = new Intent(this, ProfileDashboardActivity.class);
            intent.putExtra(MainActivity.EXTRA_EMAIL, email);
            intent.putExtra(MainActivity.EXTRA_DISPLAY_NAME, displayName);
            startActivity(intent);
        });
    }

    private void setupBottomNavigation() {
        BottomNavigationView bottomNav = findViewById(R.id.bottomNavigation);
        bottomNav.setOnItemSelectedListener(item -> {
            int id = item.getItemId();
            if (id == R.id.nav_home) {
                return true;
            } else if (id == R.id.nav_reservations) {
                Intent intent = new Intent(this, MinhasReservasActivity.class);
                intent.putExtra(MainActivity.EXTRA_EMAIL, email);
                startActivity(intent);
                return false; // Don't highlight if we open new activity
            } else if (id == R.id.nav_profile) {
                Intent intent = new Intent(this, ProfileDashboardActivity.class);
                intent.putExtra(MainActivity.EXTRA_EMAIL, email);
                intent.putExtra(MainActivity.EXTRA_DISPLAY_NAME, displayName);
                startActivity(intent);
                return false;
            }
            return false;
        });
    }

    private void updateGreeting() {
        if (displayName != null && !displayName.isEmpty()) {
            txtGreeting.setText("Olá, " + displayName.split(" ")[0] + "!");
        } else {
            txtGreeting.setText("Olá, Visitante!");
        }
    }

    private void fetchProfilePicture() {
        if (email == null)
            return;
        String documentId = email.replace(".", "_").replace("@", "_at_");
        FirebaseDatabase.getInstance().getReference().child("Clientes").child(documentId).child("photoUrl")
                .get().addOnSuccessListener(snapshot -> {
                    if (!isDestroyed() && snapshot.exists() && snapshot.getValue(String.class) != null) {
                        com.bumptech.glide.Glide.with(this).load(snapshot.getValue(String.class)).circleCrop()
                                .into(imgProfile);
                    }
                });
    }

    private void fetchRestaurants() {
        progressBar.setVisibility(View.VISIBLE);
        layoutFeatured.setVisibility(View.GONE);
        categoriesContainer.removeAllViews();

        DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("Restaurantes");
        usersRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@androidx.annotation.NonNull DataSnapshot snapshot) {
                progressBar.setVisibility(View.GONE);
                allRestaurants.clear();

                for (DataSnapshot ds : snapshot.getChildren()) {
                    String role = ds.child("role").getValue(String.class);
                    String accountType = ds.child("accountType").getValue(String.class);

                    // Aceitar todos os registos na coleção Restaurantes
                    if (true) {
                        String name = ds.child("establishmentName").getValue(String.class);
                        if (name == null)
                            name = ds.child("displayName").getValue(String.class);
                        String email = ds.child("email").getValue(String.class);
                        String cat = ds.child("category").getValue(String.class);
                        String logoUrl = ds.child("logoUrl").getValue(String.class);
                        Double ratingAvg = ds.child("ratingAvg").getValue(Double.class);
                        Integer ratingCount = ds.child("ratingCount").getValue(Integer.class);

                        if (name != null && email != null) {
                            Restaurant r = new Restaurant(name, cat != null ? cat : "Vário", email, false, logoUrl);
                            if (ratingAvg != null)
                                r.setRatingAvg(ratingAvg);
                            if (ratingCount != null)
                                r.setRatingCount(ratingCount);
                            allRestaurants.add(r);
                        }
                    }
                }
                applyFilters();
            }

            @Override
            public void onCancelled(@androidx.annotation.NonNull DatabaseError error) {
                progressBar.setVisibility(View.GONE);
            }
        });
    }

    private void setupSearch() {
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                currentSearchFilter = s.toString().toLowerCase().trim();
                applyFilters();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    private void applyFilters() {
        filteredRestaurants.clear();
        String normalizedSearch = normalizeString(currentSearchFilter);

        for (Restaurant r : allRestaurants) {
            String normalizedName = normalizeString(r.getName());
            boolean matchesSearch = currentSearchFilter.isEmpty() || normalizedName.contains(normalizedSearch);

            if (matchesSearch) {
                filteredRestaurants.add(r);
            }
        }

        // Update featured carousel with top restaurants
        List<Restaurant> featuredList = new ArrayList<>();
        for (int i = 0; i < Math.min(3, filteredRestaurants.size()); i++) {
            featuredList.add(filteredRestaurants.get(i));
        }

        featuredAdapter = new FeaturedRestaurantAdapter(featuredList, clickListener);
        rvFeatured.setAdapter(featuredAdapter);
        layoutFeatured.setVisibility(featuredList.isEmpty() ? View.GONE : View.VISIBLE);

        // Update category rows
        categoriesContainer.removeAllViews();
        for (String category : CATEGORIES) {
            List<Restaurant> catList = new ArrayList<>();
            for (Restaurant r : filteredRestaurants) {
                if (category.equals(r.getCategory())) {
                    catList.add(r);
                }
            }

            if (!catList.isEmpty()) {
                View rowView = android.view.LayoutInflater.from(this).inflate(R.layout.item_category_row, categoriesContainer, false);
                TextView txtTitle = rowView.findViewById(R.id.txtCategoryTitle);
                RecyclerView rvCategory = rowView.findViewById(R.id.rvCategoryRestaurants);

                txtTitle.setText(category);
                rvCategory.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
                rvCategory.setAdapter(new FeaturedRestaurantAdapter(catList, clickListener));

                categoriesContainer.addView(rowView);
            }
        }
    }

    private String normalizeString(String str) {
        if (str == null)
            return "";
        // Remove accents and special marks, and convert to lowercase
        String normalized = java.text.Normalizer.normalize(str, java.text.Normalizer.Form.NFD);
        normalized = normalized.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
        return normalized.toLowerCase().trim();
    }
}
