package com.example.pap_teste;

import android.os.Bundle;

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 android.widget.Button;

public class ExplorarRestaurantesActivity extends AppCompatActivity {

    private enum State {
        LIST, DETAILS
    }

    private State currentState = State.LIST;
    private com.example.pap_teste.models.Restaurant selectedRestaurant = null;

    private android.view.View scrollReservaDetails;
    private androidx.recyclerview.widget.RecyclerView rvRestaurants;
    private android.widget.TextView txtTitle;
    private android.widget.ProgressBar progressBar;

    private String selectedDate = null;
    private String selectedTime = null;

    private final androidx.activity.result.ActivityResultLauncher<android.content.Intent> photoPickerLauncher = registerForActivityResult(
            new androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                    android.net.Uri imageUri = result.getData().getData();
                    if (imageUri != null) {
                        uploadRestaurantPhoto(imageUri);
                    }
                }
            });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_explorar_restaurantes);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.explorarRoot), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        rvRestaurants = findViewById(R.id.rvRestaurants);
        scrollReservaDetails = findViewById(R.id.scrollReservaDetails);
        txtTitle = findViewById(R.id.txtTituloExplorar);
        progressBar = findViewById(R.id.progressBar);

        Button back = findViewById(R.id.btnVoltar);
        if (back != null) {
            back.setOnClickListener(v -> handleBackNavigation());
        }

        if (getIntent().hasExtra("restaurant")) {
            selectedRestaurant = (com.example.pap_teste.models.Restaurant) getIntent().getSerializableExtra("restaurant");
            currentState = State.DETAILS;
        }

        setupRestaurantList();
        updateViewState();
    }

    private void handleBackNavigation() {
        if (currentState == State.DETAILS) {
            currentState = State.LIST;
            updateViewState();
        } else {
            finish();
        }
    }

    private void updateViewState() {
        rvRestaurants.setVisibility(currentState == State.LIST ? android.view.View.VISIBLE : android.view.View.GONE);
        scrollReservaDetails
                .setVisibility(currentState == State.DETAILS ? android.view.View.VISIBLE : android.view.View.GONE);

        if (currentState == State.LIST) {
            String filter = getIntent().getStringExtra("category_filter");
            txtTitle.setText(filter != null ? "Explorar: " + filter : "Explorar restaurantes");
        } else {
            txtTitle.setText("Reserva: " + (selectedRestaurant != null ? selectedRestaurant.getName() : ""));
            setupReservationOptions();
            loadRestaurantRating();
            
            boolean isFechado = selectedRestaurant != null && selectedRestaurant.isFechadoWebsite();
            findViewById(R.id.btnSelectDate).setEnabled(!isFechado);
            findViewById(R.id.btnSelectTime).setEnabled(!isFechado);
            android.view.View etPartySize = findViewById(R.id.etPartySize);
            if (etPartySize != null) etPartySize.setEnabled(!isFechado);
            findViewById(R.id.btnConfirmarReserva).setEnabled(!isFechado);
        }
    }

    private void loadRestaurantRating() {
        if (selectedRestaurant == null || selectedRestaurant.getEmail() == null)
            return;
        String encodedEmail = selectedRestaurant.getEmail().replace(".", "_").replace("@", "_at_");

        android.widget.TextView txtAvgRating = findViewById(R.id.txtAvgRating);
        android.widget.TextView txtTotalReviews = findViewById(R.id.txtTotalReviews);

        com.google.firebase.database.FirebaseDatabase.getInstance().getReference("Restaurantes")
                .child(encodedEmail)
                .addValueEventListener(new com.google.firebase.database.ValueEventListener() {
                    @Override
                    public void onDataChange(
                            @androidx.annotation.NonNull com.google.firebase.database.DataSnapshot snapshot) {
                        Double avg = snapshot.child("ratingAvg").getValue(Double.class);
                        Integer count = snapshot.child("ratingCount").getValue(Integer.class);

                        if (avg != null && count != null && count > 0) {
                            txtAvgRating.setText(String.format(java.util.Locale.getDefault(), "%.1f", avg));
                            txtTotalReviews
                                    .setText(String.format(java.util.Locale.getDefault(), "(%d avaliações)", count));
                        } else {
                            txtAvgRating.setText("0.0");
                            txtTotalReviews.setText("(0 avaliações)");
                        }
                    }

                    @Override
                    public void onCancelled(
                            @androidx.annotation.NonNull com.google.firebase.database.DatabaseError error) {
                    }
                });
    }

    private void setupRestaurantList() {
        String filter = getIntent().getStringExtra("category_filter");
        java.util.List<com.example.pap_teste.models.Restaurant> restaurantsList = new java.util.ArrayList<>();
        com.google.firebase.database.DatabaseReference usersRef = com.google.firebase.database.FirebaseDatabase
                .getInstance().getReference("Restaurantes");

        com.google.firebase.database.Query query = usersRef;
        if (filter != null) {
            query = usersRef.orderByChild("category").equalTo(filter);
        }

        if (progressBar != null)
            progressBar.setVisibility(android.view.View.VISIBLE);

        query.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
            @Override
            public void onDataChange(@androidx.annotation.NonNull com.google.firebase.database.DataSnapshot snapshot) {
                if (progressBar != null)
                    progressBar.setVisibility(android.view.View.GONE);
                restaurantsList.clear();
                for (com.google.firebase.database.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);

                        if (name != null && email != null) {
                            com.example.pap_teste.models.Restaurant rest = new com.example.pap_teste.models.Restaurant(name, cat, email, false, logoUrl);
                            Boolean fechadoWebsite = ds.child("fechadoWebsite").getValue(Boolean.class);
                            if (fechadoWebsite != null) rest.setFechadoWebsite(fechadoWebsite);
                            
                            if (ds.hasChild("schedule")) {
                                java.util.Map<String, com.example.pap_teste.models.ScheduleDay> schMap = new java.util.HashMap<>();
                                for (com.google.firebase.database.DataSnapshot schDs : ds.child("schedule").getChildren()) {
                                    com.example.pap_teste.models.ScheduleDay sd = schDs.getValue(com.example.pap_teste.models.ScheduleDay.class);
                                    schMap.put(schDs.getKey(), sd);
                                }
                                rest.setSchedule(schMap);
                            } else if (ds.hasChild("operatingHours")) {
                                java.util.Map<String, com.example.pap_teste.models.ScheduleDay> schMap = new java.util.HashMap<>();
                                for (com.google.firebase.database.DataSnapshot schDs : ds.child("operatingHours").getChildren()) {
                                    com.example.pap_teste.models.ScheduleDay sd = schDs.getValue(com.example.pap_teste.models.ScheduleDay.class);
                                    if (schDs.hasChild("isOpen")) {
                                        Boolean isOpen = schDs.child("isOpen").getValue(Boolean.class);
                                        if (isOpen != null && sd != null) {
                                            sd.setClosed(!isOpen);
                                        }
                                    }
                                    schMap.put(schDs.getKey(), sd);
                                }
                                rest.setSchedule(schMap);
                            }
                            restaurantsList.add(rest);
                        }
                    }
                }

                RestaurantAdapter adapter = new RestaurantAdapter(restaurantsList, restaurant -> {
                    selectedRestaurant = restaurant;
                    currentState = State.DETAILS;
                    updateViewState();
                });
                rvRestaurants.setAdapter(adapter);
            }

            @Override
            public void onCancelled(@androidx.annotation.NonNull com.google.firebase.database.DatabaseError error) {
                if (progressBar != null)
                    progressBar.setVisibility(android.view.View.GONE);
                android.widget.Toast.makeText(ExplorarRestaurantesActivity.this, "Erro ao carregar restaurantes.",
                        android.widget.Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupReservationOptions() {
        android.widget.Button btnDate = findViewById(R.id.btnSelectDate);
        android.widget.Button btnTime = findViewById(R.id.btnSelectTime);
        android.widget.Button btnVerAvaliacoes = findViewById(R.id.btnVerAvaliacoes);
        android.widget.Button btnUploadFoto = findViewById(R.id.btnUploadFoto);

        btnDate.setOnClickListener(v -> {
            java.util.Calendar cal = java.util.Calendar.getInstance();
            android.app.DatePickerDialog dpd = new android.app.DatePickerDialog(this, (view, year, month, dayOfMonth) -> {
                java.util.Calendar selectedCal = java.util.Calendar.getInstance();
                selectedCal.set(year, month, dayOfMonth);
                int dayOfWeek = selectedCal.get(java.util.Calendar.DAY_OF_WEEK);
                
                boolean isClosed = selectedRestaurant.isClosedForDay(dayOfWeek);
                
                if (isClosed) {
                    android.widget.Toast.makeText(this, "O restaurante encontra-se encerrado na data selecionada.", android.widget.Toast.LENGTH_LONG).show();
                    selectedDate = null;
                    btnDate.setText("Selecionar Data");
                    btnTime.setEnabled(false);
                } else {
                    selectedDate = dayOfMonth + "/" + (month + 1) + "/" + year;
                    btnDate.setText(selectedDate);
                    btnTime.setEnabled(true);
                }
            }, cal.get(java.util.Calendar.YEAR), cal.get(java.util.Calendar.MONTH), cal.get(java.util.Calendar.DAY_OF_MONTH));
            dpd.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
            dpd.show();
        });

        btnTime.setOnClickListener(v -> {
            if (selectedDate == null) {
                android.widget.Toast.makeText(this, "Por favor, selecione primeiro a data.", android.widget.Toast.LENGTH_SHORT).show();
                return;
            }
            java.util.Calendar cal = java.util.Calendar.getInstance();
            new android.app.TimePickerDialog(this, (view, hourOfDay, minute) -> {
                String chosenTime = String.format(java.util.Locale.getDefault(), "%02d:%02d", hourOfDay, minute);
                
                boolean isOutOfHours = false;
                if (selectedDate != null && selectedRestaurant.getSchedule() != null) {
                    try {
                        java.util.Date d = new java.text.SimpleDateFormat("d/M/yyyy", java.util.Locale.getDefault()).parse(selectedDate);
                        java.util.Calendar selectedCal = java.util.Calendar.getInstance();
                        if (d != null) selectedCal.setTime(d);
                        int dayOfWeek = selectedCal.get(java.util.Calendar.DAY_OF_WEEK);
                        
                        com.example.pap_teste.models.ScheduleDay sd = selectedRestaurant.getScheduleForDay(dayOfWeek);
                        if (sd != null && !sd.isClosed()) {
                            if (sd.getOpenTime() != null && sd.getCloseTime() != null && !sd.getOpenTime().isEmpty() && !sd.getCloseTime().isEmpty()) {
                                String open = sd.getOpenTime();
                                String close = sd.getCloseTime();
                                if (open.compareTo(close) < 0) {
                                    if (chosenTime.compareTo(open) < 0 || chosenTime.compareTo(close) > 0) {
                                        isOutOfHours = true;
                                    }
                                } else {
                                    if (chosenTime.compareTo(open) < 0 && chosenTime.compareTo(close) > 0) {
                                        isOutOfHours = true;
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {}
                }
                
                if (isOutOfHours) {
                    android.widget.Toast.makeText(this, "Por favor selecione uma hora dentro do horário de funcionamento.", android.widget.Toast.LENGTH_LONG).show();
                    selectedTime = null;
                    btnTime.setText("Selecionar Hora");
                } else {
                    selectedTime = chosenTime;
                    btnTime.setText(selectedTime);
                }
            }, cal.get(java.util.Calendar.HOUR_OF_DAY), cal.get(java.util.Calendar.MINUTE), true).show();
        });

        findViewById(R.id.btnConfirmarReserva).setOnClickListener(v -> saveReservation());

        btnVerAvaliacoes.setOnClickListener(v -> showReviewsDialog());

        btnUploadFoto.setOnClickListener(v -> {
            android.content.Intent intent = new android.content.Intent(android.content.Intent.ACTION_PICK);
            intent.setType("image/*");
            photoPickerLauncher.launch(intent);
        });
    }

    private void uploadRestaurantPhoto(android.net.Uri imageUri) {
        if (selectedRestaurant == null || selectedRestaurant.getEmail() == null)
            return;
        String encodedEmail = selectedRestaurant.getEmail().replace(".", "_").replace("@", "_at_");
        com.google.firebase.storage.StorageReference storageRef = com.google.firebase.storage.FirebaseStorage
                .getInstance().getReference()
                .child("restaurant_photos/" + encodedEmail + "/" + java.util.UUID.randomUUID().toString());

        storageRef.putFile(imageUri).addOnSuccessListener(taskSnapshot -> {
            storageRef.getDownloadUrl().addOnSuccessListener(uri -> {
                String photoUrl = uri.toString();
                com.google.firebase.database.FirebaseDatabase.getInstance().getReference("photos").child(encodedEmail)
                        .push().child("url").setValue(photoUrl).addOnCompleteListener(task -> {
                            if (task.isSuccessful()) {
                                android.widget.Toast.makeText(this, "Foto adicionada com sucesso!",
                                        android.widget.Toast.LENGTH_SHORT).show();
                            }
                        });
            });
        }).addOnFailureListener(e -> {
            android.widget.Toast.makeText(this, "Falha no upload: " + e.getMessage(), android.widget.Toast.LENGTH_LONG)
                    .show();
        });
    }

    private void showReviewsDialog() {
        if (selectedRestaurant == null || selectedRestaurant.getEmail() == null)
            return;
        String encodedEmail = selectedRestaurant.getEmail().replace(".", "_").replace("@", "_at_");

        android.view.View dialogView = getLayoutInflater().inflate(R.layout.dialog_reviews_list, null);
        androidx.recyclerview.widget.RecyclerView rvReviews = dialogView.findViewById(R.id.rvReviewsList);
        android.widget.TextView txtEmpty = dialogView.findViewById(R.id.txtEmptyReviews);
        android.widget.Button btnClose = dialogView.findViewById(R.id.btnCloseReviews);
        android.widget.Button btnAdd = dialogView.findViewById(R.id.btnAddReview);

        rvReviews.setLayoutManager(new androidx.recyclerview.widget.LinearLayoutManager(this));

        androidx.appcompat.app.AlertDialog dialog = new androidx.appcompat.app.AlertDialog.Builder(this)
                .setView(dialogView)
                .create();
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

        btnClose.setOnClickListener(v -> dialog.dismiss());
        btnAdd.setOnClickListener(v -> {
            dialog.dismiss();
            addReviewDialog();
        });

        com.google.firebase.database.DatabaseReference reviewsRef = com.google.firebase.database.FirebaseDatabase
                .getInstance()
                .getReference("reviews").child(encodedEmail);

        String currentUserEmail = com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser() != null
                ? com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser().getEmail()
                : null;

        reviewsRef.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
            @Override
            public void onDataChange(@androidx.annotation.NonNull com.google.firebase.database.DataSnapshot snapshot) {
                java.util.List<com.example.pap_teste.models.Review> reviewsList = new java.util.ArrayList<>();
                for (com.google.firebase.database.DataSnapshot dst : snapshot.getChildren()) {
                    String author = dst.child("author").getValue(String.class);
                    String text = dst.child("text").getValue(String.class);
                    String uEmail = dst.child("userEmail").getValue(String.class);
                    Float rating = dst.child("rating").getValue(Float.class);

                    if (rating == null)
                        rating = 0f;

                    com.example.pap_teste.models.Review rev = new com.example.pap_teste.models.Review(
                            dst.getKey(), author, text, rating, uEmail);
                    reviewsList.add(rev);
                }

                if (reviewsList.isEmpty()) {
                    txtEmpty.setVisibility(android.view.View.VISIBLE);
                    rvReviews.setVisibility(android.view.View.GONE);
                } else {
                    txtEmpty.setVisibility(android.view.View.GONE);
                    rvReviews.setVisibility(android.view.View.VISIBLE);
                }

                ReviewAdapter adapter = new ReviewAdapter(reviewsList, currentUserEmail, review -> {
                    // Confirmação de Apagar
                    new androidx.appcompat.app.AlertDialog.Builder(ExplorarRestaurantesActivity.this)
                            .setTitle("Apagar Avaliação")
                            .setMessage("Tens a certeza que queres apagar esta avaliação?")
                            .setPositiveButton("Sim", (d, w) -> {
                                deleteReview(review.getKey());
                                d.dismiss();
                            })
                            .setNegativeButton("Não", null)
                            .show();
                });
                rvReviews.setAdapter(adapter);
            }

            @Override
            public void onCancelled(@androidx.annotation.NonNull com.google.firebase.database.DatabaseError error) {
                android.widget.Toast.makeText(ExplorarRestaurantesActivity.this, "Erro ao carregar avaliações.",
                        android.widget.Toast.LENGTH_SHORT).show();
            }
        });

        dialog.show();
    }

    private void deleteReview(String reviewKey) {
        if (selectedRestaurant == null || selectedRestaurant.getEmail() == null)
            return;
        String encodedEmail = selectedRestaurant.getEmail().replace(".", "_").replace("@", "_at_");

        com.google.firebase.database.DatabaseReference reviewsRef = com.google.firebase.database.FirebaseDatabase
                .getInstance()
                .getReference("reviews").child(encodedEmail);

        reviewsRef.child(reviewKey).removeValue().addOnSuccessListener(aVoid -> {
            com.google.android.material.snackbar.Snackbar.make(findViewById(R.id.explorarRoot), "Avaliação removida",
                    com.google.android.material.snackbar.Snackbar.LENGTH_SHORT).show();
            recalculateRestaurantAverage(encodedEmail);
        });
    }

    private void recalculateRestaurantAverage(String encodedEmail) {
        com.google.firebase.database.FirebaseDatabase.getInstance().getReference("reviews").child(encodedEmail)
                .addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
                    @Override
                    public void onDataChange(
                            @androidx.annotation.NonNull com.google.firebase.database.DataSnapshot snapshot) {
                        double totalRating = 0;
                        int count = 0;
                        for (com.google.firebase.database.DataSnapshot dst : snapshot.getChildren()) {
                            Float r = dst.child("rating").getValue(Float.class);
                            if (r != null) {
                                totalRating += r;
                                count++;
                            }
                        }

                        double newAvg = count > 0 ? (totalRating / count) : 0.0;

                        java.util.Map<String, Object> updates = new java.util.HashMap<>();
                        updates.put("ratingAvg", newAvg);
                        updates.put("ratingCount", count);

                        com.google.firebase.database.FirebaseDatabase.getInstance().getReference("Restaurantes")
                                .child(encodedEmail).updateChildren(updates);
                    }

                    @Override
                    public void onCancelled(
                            @androidx.annotation.NonNull com.google.firebase.database.DatabaseError error) {
                    }
                });
    }

    private void addReviewDialog() {
        if (selectedRestaurant == null || selectedRestaurant.getEmail() == null)
            return;

        android.view.View dialogView = getLayoutInflater().inflate(R.layout.dialog_leave_review, null);
        com.example.pap_teste.components.InteractiveRatingBar ratingBar = dialogView
                .findViewById(R.id.interactiveRatingBar);
        android.widget.EditText input = dialogView.findViewById(R.id.etReviewComment);
        android.widget.Button btnSubmit = dialogView.findViewById(R.id.btnSubmitReview);
        android.widget.Button btnCancel = dialogView.findViewById(R.id.btnCancelReview);

        btnSubmit.setEnabled(false);
        btnSubmit.setAlpha(0.5f);

        input.addTextChangedListener(new android.text.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) {
                boolean hasText = s != null && s.toString().trim().length() > 0;
                btnSubmit.setEnabled(hasText);
                btnSubmit.setAlpha(hasText ? 1.0f : 0.5f);
            }

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

        androidx.appcompat.app.AlertDialog dialog = new androidx.appcompat.app.AlertDialog.Builder(this)
                .setView(dialogView)
                .create();

        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

        btnCancel.setOnClickListener(v -> dialog.dismiss());
        btnSubmit.setOnClickListener(v -> {
            float rating = (float) ratingBar.getRating();
            String revText = input.getText().toString().trim();

            com.google.firebase.auth.FirebaseUser currentUser = com.google.firebase.auth.FirebaseAuth.getInstance()
                    .getCurrentUser();
            if (currentUser != null && currentUser.getEmail() != null) {
                String userDoc = currentUser.getEmail().replace(".", "_").replace("@", "_at_");
                com.google.firebase.database.FirebaseDatabase.getInstance().getReference("Clientes").child(userDoc).get()
                        .addOnSuccessListener(snapshot -> {
                            String authorName = snapshot.exists()
                                    && snapshot.child("displayName").getValue(String.class) != null
                                            ? snapshot.child("displayName").getValue(String.class)
                                            : "Visitante";
                            submitReviewToFirebase(authorName, revText, rating);
                            dialog.dismiss();
                        }).addOnFailureListener(e -> {
                            submitReviewToFirebase("Visitante", revText, rating);
                            dialog.dismiss();
                        });
            } else {
                submitReviewToFirebase("Visitante", revText, rating);
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    private void submitReviewToFirebase(String authorName, String revText, float newRating) {
        String encodedEmail = selectedRestaurant.getEmail().replace(".", "_").replace("@", "_at_");

        com.google.firebase.auth.FirebaseUser currentUser = com.google.firebase.auth.FirebaseAuth.getInstance()
                .getCurrentUser();
        String uEmail = currentUser != null ? currentUser.getEmail() : null;

        // 1. Guardar a Review
        java.util.Map<String, Object> review = new java.util.HashMap<>();
        review.put("author", authorName);
        review.put("text", revText);
        review.put("rating", newRating);
        review.put("userEmail", uEmail);
        review.put("timestamp", com.google.firebase.database.ServerValue.TIMESTAMP);

        com.google.firebase.database.FirebaseDatabase.getInstance().getReference("reviews")
                .child(encodedEmail).push().setValue(review).addOnCompleteListener(task -> {
                    if (task.isSuccessful()) {
                        com.google.android.material.snackbar.Snackbar
                                .make(findViewById(R.id.explorarRoot), "Obrigado pela tua avaliação!",
                                        com.google.android.material.snackbar.Snackbar.LENGTH_LONG)
                                .show();
                    }
                });

        // 2. Atualizar Média no Restaurante
        com.google.firebase.database.DatabaseReference restRef = com.google.firebase.database.FirebaseDatabase
                .getInstance().getReference("Restaurantes").child(encodedEmail);
        restRef.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
            @Override
            public void onDataChange(@androidx.annotation.NonNull com.google.firebase.database.DataSnapshot snapshot) {
                Double currentAvg = snapshot.child("ratingAvg").getValue(Double.class);
                Integer currentCount = snapshot.child("ratingCount").getValue(Integer.class);

                if (currentAvg == null)
                    currentAvg = 0.0;
                if (currentCount == null)
                    currentCount = 0;

                double newAvg = ((currentAvg * currentCount) + newRating) / (currentCount + 1);

                java.util.Map<String, Object> updates = new java.util.HashMap<>();
                updates.put("ratingAvg", newAvg);
                updates.put("ratingCount", currentCount + 1);

                restRef.updateChildren(updates);
            }

            @Override
            public void onCancelled(@androidx.annotation.NonNull com.google.firebase.database.DatabaseError error) {
            }
        });
    }

    private void saveReservation() {
        android.widget.EditText etPartySize = findViewById(R.id.etPartySize);
        int partySize = 0;
        try {
            partySize = Integer.parseInt(etPartySize.getText().toString());
        } catch (Exception e) {
        }

        if (selectedDate == null || selectedTime == null || partySize == 0) {
            android.widget.Toast.makeText(this, "Por favor, selecione data, hora e número de pessoas.",
                    android.widget.Toast.LENGTH_SHORT).show();
            return;
        }

        String userEmail = com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser() != null
                ? com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser().getEmail()
                : "cliente@teste.com";

        com.google.firebase.database.DatabaseReference ref = com.google.firebase.database.FirebaseDatabase.getInstance()
                .getReference("reservas");
        String id = ref.push().getKey();

        com.example.pap_teste.models.Reserva reserva = new com.example.pap_teste.models.Reserva(
                id,
                userEmail,
                selectedRestaurant.getName(),
                selectedRestaurant.getEmail(),
                selectedDate,
                selectedTime,
                partySize,
                "Pendente");

        if (id != null) {
            ref.child(id).setValue(reserva).addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    android.widget.Toast
                            .makeText(this, "Reserva solicitada com sucesso!", android.widget.Toast.LENGTH_SHORT)
                            .show();
                    finish();
                } else {
                    android.widget.Toast.makeText(this, "Erro ao salvar reserva.", android.widget.Toast.LENGTH_SHORT)
                            .show();
                }
            });
        }
    }
}
