package com.example.pap_teste;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.pap_teste.models.LocalReservation;
import com.example.pap_teste.viewmodels.ReservationViewModel;
import java.util.ArrayList;
import java.util.List;

public class MyReservationsFragment extends Fragment {

    private RecyclerView rvReservations;
    private LocalReservaAdapter adapter;
    private List<LocalReservation> reservationList = new ArrayList<>();
    private ProgressBar progressBar;
    private View emptyState;
    private ReservationViewModel viewModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_reservations, container, false);

        rvReservations = view.findViewById(R.id.rvReservations);
        progressBar = view.findViewById(R.id.progressBar);
        emptyState = view.findViewById(R.id.emptyState);

        viewModel = new ViewModelProvider(this).get(ReservationViewModel.class);

        setupAdapter();
        observeReservations();

        return view;
    }

    private void setupAdapter() {
        adapter = new LocalReservaAdapter(reservationList, new LocalReservaAdapter.OnActionListener() {
            @Override
            public void onCancel(LocalReservation reservation) {
                reservation.setStatus("CANCELADA");
                viewModel.update(reservation);
                Toast.makeText(getContext(), "Reserva cancelada.", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onEdit(LocalReservation reservation) {
                // Show details or edit
                Toast.makeText(getContext(), "Detalhes: " + reservation.getNotes(), Toast.LENGTH_LONG).show();
            }
        });
        rvReservations.setLayoutManager(new LinearLayoutManager(getContext()));
        rvReservations.setAdapter(adapter);
    }

    private void observeReservations() {
        progressBar.setVisibility(View.VISIBLE);
        viewModel.getAllReservations().observe(getViewLifecycleOwner(), reservations -> {
            progressBar.setVisibility(View.GONE);
            reservationList.clear();
            reservationList.addAll(reservations);
            adapter.notifyDataSetChanged();
            emptyState.setVisibility(reservationList.isEmpty() ? View.VISIBLE : View.GONE);
        });
    }
}
