package com.example.pap_teste;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;

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

import com.example.pap_teste.models.Reserva;
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 MinhasReservasActivity extends AppCompatActivity {

    private RecyclerView rvMinhasReservas;
    private ReservaAdapter adapter;
    private final List<Reserva> reservaList = new ArrayList<>();
    private DatabaseReference databaseReference;
    private String clientEmail;

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

        clientEmail = getIntent().getStringExtra(MainActivity.EXTRA_EMAIL);
        if (clientEmail == null) {
            com.google.firebase.auth.FirebaseUser user = com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser();
            if (user != null) {
                clientEmail = user.getEmail();
            }
        }
        
        // Fallback for testing if still null
        if (clientEmail == null) {
            clientEmail = "cliente@teste.com";
        }

        rvMinhasReservas = findViewById(R.id.rvMinhasReservas);
        Button btnVoltar = findViewById(R.id.btnVoltar);
        btnVoltar.setOnClickListener(v -> finish());

        setupAdapter();
        loadReservations();
    }

    private void setupAdapter() {
        adapter = new ReservaAdapter(reservaList, new ReservaAdapter.OnReservaActionListener() {
            @Override
            public void onCheckIn(Reserva reserva) {
                Intent intent = new Intent(MinhasReservasActivity.this, CheckInAntecipadoActivity.class);
                intent.putExtra("restaurant_email", reserva.getRestauranteEmail());
                startActivity(intent);
            }

            @Override
            public void onCancel(Reserva reserva) {
                cancelReservation(reserva);
            }
        });
        rvMinhasReservas.setAdapter(adapter);
    }

    private void loadReservations() {
        databaseReference = FirebaseDatabase.getInstance().getReference("reservas");
        databaseReference.orderByChild("clienteEmail").equalTo(clientEmail)
                .addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        reservaList.clear();
                        for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                            Reserva reserva = dataSnapshot.getValue(Reserva.class);
                            if (reserva != null) {
                                reservaList.add(reserva);
                            }
                        }
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {
                        Toast.makeText(MinhasReservasActivity.this, "Erro ao carregar reservas.", Toast.LENGTH_SHORT)
                                .show();
                    }
                });
    }

    private void cancelReservation(Reserva reserva) {
        databaseReference.child(reserva.getId()).child("estado").setValue("Cancelada")
                .addOnCompleteListener(task -> {
                    if (task.isSuccessful()) {
                        Toast.makeText(this, "Reserva cancelada.", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "Erro ao cancelar reserva.", Toast.LENGTH_SHORT).show();
                    }
                });
    }
}
