package ru.vyatsu.qr_access_admin.rent.view;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import jakarta.annotation.security.PermitAll;
import ru.vyatsu.qr_access_admin.client.entity.ClientRepository;
import ru.vyatsu.qr_access_admin.common.MainLayout;
import ru.vyatsu.qr_access_admin.door.entity.DoorRepository;
import ru.vyatsu.qr_access_admin.rent.component.RentEditor;
import ru.vyatsu.qr_access_admin.rent.entity.RentEntity;
import ru.vyatsu.qr_access_admin.rent.entity.RentRepository;

import java.util.List;

@Route(value = "rent", layout = MainLayout.class)
@PageTitle("Бронирование")
@PermitAll
public class RentView extends VerticalLayout {
    private final RentRepository repository;
    private final Grid<RentEntity> grid;
    private final RentEditor editor;

    public RentView(RentRepository repository, DoorRepository doorRepository, ClientRepository clientRepository) {
        this.repository = repository;

        var addButton = new Button("Добавить бронирование", VaadinIcon.PLUS.create());
        grid = new Grid<>(RentEntity.class);
        grid.setColumns("clientId", "date", "startTime", "endTime", "payed", "dateCreated");
        editor = new RentEditor(doorRepository, clientRepository);

        var actionsLayout = new HorizontalLayout(addButton);
        add(actionsLayout, grid, editor);

        this.configureEditor();

        addButton.addClickListener(e -> editRent(new RentEntity()));

        grid.setHeight("600px");
        grid.asSingleSelect().addValueChangeListener(e -> editRent(e.getValue()));

        refreshRentGrid();
    }

    private void refreshRentGrid() {
        List<RentEntity> entities = repository.findAll();
        grid.setItems(entities);
    }

    private void editRent(RentEntity rent) {
        if (rent == null) {
            editor.setVisible(false);
        } else {
            editor.setVisible(true);
            editor.setCurrentRent(rent);
        }
    }

    private void configureEditor() {
        editor.setVisible(false);

        editor.setSaveListener(rent -> {
            repository.save(rent);
            refreshRentGrid();
            editRent(null);
        });

        editor.setDeleteListener(rent -> {
            repository.deleteById(rent.getId());
            refreshRentGrid();
            editRent(null);
        });

        editor.setCancelListener(() -> editRent(null));
    }
}
