package ru.vyatsu.qr_access_admin.partner.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.partner.component.PartnerEditor;
import ru.vyatsu.qr_access_admin.partner.entity.PartnerEntity;
import ru.vyatsu.qr_access_admin.partner.entity.PartnerRepository;

import java.util.List;

@Route(value = "partners", layout = MainLayout.class)
@PageTitle("Партнеры")
@PermitAll
public class PartnerView extends VerticalLayout {
    private final PartnerRepository repository;
    private final Grid<PartnerEntity> grid;
    private final PartnerEditor editor;

    public PartnerView(PartnerRepository repository) {
        this.repository = repository;

        var addButton = new Button("Добавить партнера", VaadinIcon.PLUS.create());
        grid = new Grid<>(PartnerEntity.class);
        grid.setColumns("id", "name");
        editor = new PartnerEditor();

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

        this.configureEditor();

        addButton.addClickListener(e -> editPartner(new PartnerEntity()));

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

        refreshPartnerGrid();
    }

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

    private void editPartner(PartnerEntity partner) {
        if (partner == null) {
            editor.setVisible(false);
        } else {
            editor.setVisible(true);
            editor.setCurrentPartner(partner);
        }
    }

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

        editor.setSaveListener(partner -> {
            repository.save(partner);
            refreshPartnerGrid();
            editPartner(null);
        });

        editor.setDeleteListener(partner -> {
            repository.deleteById(partner.getId());
            refreshPartnerGrid();
            editPartner(null);
        });

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