package ru.vyatsu.qr_access_admin.slot.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 ru.vyatsu.qr_access_admin.common.MainLayout;
import ru.vyatsu.qr_access_admin.slot.component.SlotEditor;
import ru.vyatsu.qr_access_admin.slot.entity.SlotEntity;
import ru.vyatsu.qr_access_admin.slot.entity.SlotRepository;

import java.util.List;

@Route(value = "slots", layout = MainLayout.class)
@PageTitle("Слоты")
public class SlotView extends VerticalLayout {
    private final SlotRepository repository;
    private final Grid<SlotEntity> grid;
    private final SlotEditor editor;

    public SlotView(SlotRepository repository) {
        this.repository = repository;

        var addButton = new Button("Добавить слот", VaadinIcon.PLUS.create());
        grid = new Grid<>(SlotEntity.class);
        grid.setColumns("id", "startTime", "endTime");
        editor = new SlotEditor();

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

        this.configureEditor();

        addButton.addClickListener(e -> editSlot(new SlotEntity()));

        grid.setHeight("200px");
        grid.asSingleSelect().addValueChangeListener(e -> editSlot(e.getValue()));

        refreshSlotGrid();
    }

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

    private void editSlot(SlotEntity slot) {
        if (slot == null) {
            editor.setVisible(false);
        } else {
            editor.setVisible(true);
            editor.setCurrentSlot(slot);
        }
    }

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

        editor.setSaveListener(slot -> {
            repository.save(slot);
            refreshSlotGrid();
            editSlot(null);
        });

        editor.setDeleteListener(slot -> {
            repository.deleteById(slot.getId());
            refreshSlotGrid();
            editSlot(null);
        });

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