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;
    private android.widget.ProgressBar progressBar;
    private android.view.View emptyState;

    @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);
        progressBar = findViewById(R.id.progressBar);
        emptyState = findViewById(R.id.emptyState);
        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");
        if (progressBar != null) progressBar.setVisibility(android.view.View.VISIBLE);
        if (emptyState != null) emptyState.setVisibility(android.view.View.GONE);
        
        databaseReference.orderByChild("clienteEmail").equalTo(clientEmail)
                .addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        if (progressBar != null) progressBar.setVisibility(android.view.View.GONE);
                        reservaList.clear();
                        for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                            Reserva reserva = dataSnapshot.getValue(Reserva.class);
                            if (reserva != null) {
                                reservaList.add(reserva);
                            }
                        }
                        // Order reservations (newest first based on ID or we can just reverse the list)
                        java.util.Collections.reverse(reservaList);
                        adapter.notifyDataSetChanged();
                        
                        if (emptyState != null) {
                            emptyState.setVisibility(reservaList.isEmpty() ? android.view.View.VISIBLE : android.view.View.GONE);
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {
                        if (progressBar != null) progressBar.setVisibility(android.view.View.GONE);
                        Toast.makeText(MinhasReservasActivity.this, "Erro ao carregar reservas.", Toast.LENGTH_SHORT)
                                .show();
                    }
                });
    }

    private void cancelReservation(Reserva reserva) {
        android.widget.EditText input = new android.widget.EditText(this);
        input.setHint("Motivo do cancelamento (opcional)");
        new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("Cancelar Reserva")
                .setMessage("Deseja indicar o motivo do cancelamento?")
                .setView(input)
                .setPositiveButton("Confirmar", (dialog, which) -> {
                    String motivo = input.getText().toString();
                    java.util.Map<String, Object> updates = new java.util.HashMap<>();
                    updates.put("estado", "Cancelada");
                    if (!motivo.isEmpty()) {
                        updates.put("motivo", motivo);
                    }
                    databaseReference.child(reserva.getId()).updateChildren(updates)
                            .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();
                                }
                            });
                })
                .setNegativeButton("Voltar", null)
                .show();
    }
}
