package com.example.pap_teste;

import android.os.Bundle;
import androidx.recyclerview.widget.RecyclerView;

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 NovaReservaActivity extends AppCompatActivity {

    private enum State {
        CATEGORIES, RESTAURANTS, DETAILS
    }

    private State currentState = State.CATEGORIES;
    private String selectedCategory = null;
    private com.example.pap_teste.models.Restaurant selectedRestaurant = null;

    private androidx.recyclerview.widget.RecyclerView rvCategories, rvRestaurants;
    private android.view.View scrollNovaReserva;
    private android.widget.TextView txtTitle;

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

        rvCategories = findViewById(R.id.rvCategories);
        rvRestaurants = findViewById(R.id.rvRestaurants);
        scrollNovaReserva = findViewById(R.id.scrollNovaReserva);
        txtTitle = findViewById(R.id.txtTituloNovaReserva);

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

        setupCategories();
        updateViewState();
    }

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

    private void updateViewState() {
        rvCategories
                .setVisibility(currentState == State.CATEGORIES ? android.view.View.VISIBLE : android.view.View.GONE);
        rvRestaurants
                .setVisibility(currentState == State.RESTAURANTS ? android.view.View.VISIBLE : android.view.View.GONE);
        scrollNovaReserva
                .setVisibility(currentState == State.DETAILS ? android.view.View.VISIBLE : android.view.View.GONE);

        if (currentState == State.CATEGORIES) {
            txtTitle.setText("Escolha o tema");
        } else if (currentState == State.RESTAURANTS) {
            txtTitle.setText("Restaurantes: " + selectedCategory);
        } else {
            txtTitle.setText("Reserva: " + (selectedRestaurant != null ? selectedRestaurant.getName() : ""));
            setupReservationOptions();
        }
    }

    private void setupCategories() {
        java.util.List<com.example.pap_teste.models.FoodCategory> cats = new java.util.ArrayList<>();
        cats.add(new com.example.pap_teste.models.FoodCategory("Carnes", R.drawable.cat_carnes));
        cats.add(new com.example.pap_teste.models.FoodCategory("Massas", R.drawable.cat_massas));
        cats.add(new com.example.pap_teste.models.FoodCategory("Sushi", R.drawable.cat_sushi));
        cats.add(new com.example.pap_teste.models.FoodCategory("Pizzas", R.drawable.cat_pizzas));
        cats.add(new com.example.pap_teste.models.FoodCategory("Sobremesas", R.drawable.cat_sobremesas));

        rvCategories.setLayoutManager(new androidx.recyclerview.widget.LinearLayoutManager(this));
        rvCategories.setAdapter(new FoodCategoryAdapter(cats, category -> {
            selectedCategory = category.getName();
            currentState = State.RESTAURANTS;
            setupRestaurants();
            updateViewState();
        }));
    }

    private void setupRestaurants() {
        java.util.List<com.example.pap_teste.models.Restaurant> filteredList = new java.util.ArrayList<>();
        com.google.firebase.database.DatabaseReference usersRef = com.google.firebase.database.FirebaseDatabase.getInstance().getReference("users");
        
        usersRef.orderByChild("category").equalTo(selectedCategory).addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
            @Override
            public void onDataChange(@androidx.annotation.NonNull com.google.firebase.database.DataSnapshot snapshot) {
                filteredList.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 (name != null && email != null) {
                            filteredList.add(new com.example.pap_teste.models.Restaurant(name, cat, email, false));
                        }
                    }
                }
                
                rvRestaurants.setLayoutManager(new androidx.recyclerview.widget.LinearLayoutManager(NovaReservaActivity.this));
                rvRestaurants.setAdapter(new RestaurantAdapter(filteredList, restaurant -> {
                    selectedRestaurant = restaurant;
                    currentState = State.DETAILS;
                    updateViewState();
                }));
            }

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

    private String selectedDate = null;
    private String selectedTime = null;
    private int selectedPartySize = 0;

    private void setupReservationOptions() {
        // Dates
        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
        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
        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();
                }
            });
        }
    }
}
