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 String selectedDate = null;
    private String selectedTime = null;
    private int selectedPartySize = 0;

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

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

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

    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("users");
        
        com.google.firebase.database.Query query = usersRef;
        if (filter != null) {
            query = usersRef.orderByChild("category").equalTo(filter);
        }

        query.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
            @Override
            public void onDataChange(@androidx.annotation.NonNull com.google.firebase.database.DataSnapshot snapshot) {
                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);
                    
                    if ("ADMIN".equalsIgnoreCase(role) || "ESTABELECIMENTO".equalsIgnoreCase(accountType)) {
                        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);
                        
                        // If no category filter in query, we might need a client-side filter if the index isn't used
                        // but here we use the query. Actually if filter is null we get all, but we need to ensure they are ESTAB
                        if (name != null && email != null) {
                            restaurantsList.add(new com.example.pap_teste.models.Restaurant(name, cat, email, false));
                        }
                    }
                }
                
                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) {
                android.widget.Toast.makeText(ExplorarRestaurantesActivity.this, "Erro ao carregar restaurantes.", android.widget.Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupReservationOptions() {
        // Dates
        androidx.recyclerview.widget.RecyclerView rvDates = findViewById(R.id.rvDates);
        java.util.List<String> dates = new java.util.ArrayList<>();
        dates.add("Hoje");
        dates.add("Amanhã");
        dates.add("Quarta, 12 Mar");
        dates.add("Quinta, 13 Mar");
        dates.add("Sexta, 14 Mar");
        rvDates.setAdapter(new ReservationOptionAdapter(dates, date -> selectedDate = date));

        // Times
        androidx.recyclerview.widget.RecyclerView rvTimes = findViewById(R.id.rvTimes);
        java.util.List<String> times = new java.util.ArrayList<>();
        times.add("12:00");
        times.add("13:00");
        times.add("19:00");
        times.add("20:00");
        times.add("21:00");
        times.add("22:00");
        rvTimes.setAdapter(new ReservationOptionAdapter(times, time -> selectedTime = time));

        // Party Size
        androidx.recyclerview.widget.RecyclerView rvParty = findViewById(R.id.rvPartySize);
        java.util.List<String> party = new java.util.ArrayList<>();
        party.add("1 pessoa");
        party.add("2 pessoas");
        party.add("3 pessoas");
        party.add("4 pessoas");
        party.add("5 pessoas");
        party.add("6+ pessoas");
        rvParty.setAdapter(new ReservationOptionAdapter(party, size -> {
            try {
                selectedPartySize = Integer.parseInt(size.split(" ")[0].replace("+", ""));
            } catch (Exception e) {
                selectedPartySize = 6;
            }
        }));

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

    private void saveReservation() {
        if (selectedDate == null || selectedTime == null || selectedPartySize == 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,
                selectedPartySize,
                "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();
                }
            });
        }
    }
}
