package ru.vyatsu.qr_access_admin.qr.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.common.MainLayout;
import ru.vyatsu.qr_access_admin.door.entity.DoorRepository;
import ru.vyatsu.qr_access_admin.qr.component.QrEditor;
import ru.vyatsu.qr_access_admin.qr.entity.QrEntity;
import ru.vyatsu.qr_access_admin.qr.entity.QrRepository;

import java.util.List;

@Route(value = "qrs", layout = MainLayout.class)
@PageTitle("Коды")
@PermitAll
public class QrView extends VerticalLayout {
    private final QrRepository repository;
    private final Grid<QrEntity> grid;
    private final QrEditor editor;

    public QrView(QrRepository repository, DoorRepository doorRepository) {
        this.repository = repository;

        var addButton = new Button("Добавить код", VaadinIcon.PLUS.create());
        grid = new Grid<>(QrEntity.class);
        editor = new QrEditor(doorRepository);

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

        this.configureEditor();

        addButton.addClickListener(e -> editQr(new QrEntity()));

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

        refreshQrGrid();
    }

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

    private void editQr(QrEntity qr) {
        if (qr == null) {
            editor.setVisible(false);
        } else {
            editor.setVisible(true);
            editor.setCurrentQr(qr);
        }
    }

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

        editor.setSaveListener(qr -> {
            repository.save(qr);
            refreshQrGrid();
            editQr(null);
        });

        editor.setDeleteListener(qr -> {
            repository.deleteById(qr.getKeyCode());
            refreshQrGrid();
            editQr(null);
        });

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