package com.example.pap_teste;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.pap_teste.models.Reserva;
import com.example.pap_teste.models.Restaurant;
import com.google.firebase.Timestamp;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class ReservationActivity extends AppCompatActivity {

    private String restaurantId, restaurantName;
    private int guestCount = 2;
    private Calendar selectedDate = Calendar.getInstance();
    private String selectedTimeSlot = null;

    private TextView txtGuestCount, txtSelectedDate;
    private RecyclerView rvTimeSlots;
    private TimeSlotAdapter adapter;
    private List<String> timeSlots = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reservation);

        restaurantId = getIntent().getStringExtra(RestaurantDetailActivity.EXTRA_RESTAURANT_ID);
        restaurantName = getIntent().getStringExtra(RestaurantDetailActivity.EXTRA_RESTAURANT_NAME);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("Reservar: " + restaurantName);
        }

        txtGuestCount = findViewById(R.id.txtGuestCount);
        txtSelectedDate = findViewById(R.id.txtSelectedDate);
        rvTimeSlots = findViewById(R.id.rvTimeSlots);
        EditText etSpecialRequests = findViewById(R.id.etSpecialRequests);

        findViewById(R.id.btnDecreaseGuests).setOnClickListener(v -> {
            if (guestCount > 1) {
                guestCount--;
                txtGuestCount.setText(String.valueOf(guestCount));
            }
        });

        findViewById(R.id.btnIncreaseGuests).setOnClickListener(v -> {
            guestCount++;
            txtGuestCount.setText(String.valueOf(guestCount));
        });

        findViewById(R.id.cardDatePicker).setOnClickListener(v -> showDatePicker());

        setupTimeSlots();
        loadRestaurantSlots();

        findViewById(R.id.btnConfirmReservation).setOnClickListener(v -> {
            if (selectedTimeSlot == null) {
                Toast.makeText(this, "Por favor, selecione um horário.", Toast.LENGTH_SHORT).show();
                return;
            }
            confirmReservation(etSpecialRequests.getText().toString());
        });

        toolbar.setNavigationOnClickListener(v -> onBackPressed());
    }

    private void showDatePicker() {
        new DatePickerDialog(this, (view, year, month, dayOfMonth) -> {
            selectedDate.set(year, month, dayOfMonth);
            txtSelectedDate.setText(String.format("%02d/%02d/%d", dayOfMonth, month + 1, year));
        }, selectedDate.get(Calendar.YEAR), selectedDate.get(Calendar.MONTH), selectedDate.get(Calendar.DAY_OF_MONTH)).show();
    }

    private void setupTimeSlots() {
        adapter = new TimeSlotAdapter(timeSlots, slot -> selectedTimeSlot = slot);
        rvTimeSlots.setAdapter(adapter);
        rvTimeSlots.setLayoutManager(new GridLayoutManager(this, 3));
    }

    private void loadRestaurantSlots() {
        // In a real app, we would fetch from Firestore based on the selected date
        // For now, let's use the static slots from the restaurant model
        FirebaseFirestore.getInstance().collection("restaurants").document(restaurantId).get()
                .addOnSuccessListener(documentSnapshot -> {
                    Restaurant r = documentSnapshot.toObject(Restaurant.class);
                    if (r != null && r.getAvailableSlots() != null) {
                        timeSlots.clear();
                        timeSlots.addAll(r.getAvailableSlots());
                        adapter.notifyDataSetChanged();
                    }
                });
    }

    private void confirmReservation(String specialRequests) {
        String userId = FirebaseAuth.getInstance().getUid();
        if (userId == null) {
            Toast.makeText(this, "Erro de autenticação.", Toast.LENGTH_SHORT).show();
            return;
        }

        Reserva reserva = new Reserva();
        reserva.setUserId(userId);
        reserva.setRestaurantId(restaurantId);
        reserva.setRestaurantName(restaurantName);
        reserva.setGuests(guestCount);
        reserva.setDate(new Timestamp(selectedDate.getTime()));
        reserva.setTimeSlot(selectedTimeSlot);
        reserva.setSpecialRequests(specialRequests);
        reserva.setStatus("confirmed");
        reserva.setCreatedAt(new Timestamp(new Date()));

        FirebaseFirestore.getInstance().collection("reservations").add(reserva)
                .addOnSuccessListener(documentReference -> {
                    Toast.makeText(this, "Reserva confirmada com sucesso!", Toast.LENGTH_LONG).show();
                    finish();
                })
                .addOnFailureListener(e -> Toast.makeText(this, "Erro ao confirmar reserva.", Toast.LENGTH_SHORT).show());
    }
}
