package ru.vyatsu.qr_access_admin.partner.component;

import com.vaadin.flow.component.Composite;
import com.vaadin.flow.component.Key;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
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.component.textfield.TextField;
import com.vaadin.flow.data.binder.BeanValidationBinder;
import com.vaadin.flow.data.binder.Binder;
import lombok.Getter;
import lombok.Setter;
import ru.vyatsu.qr_access_admin.partner.entity.PartnerEntity;

public class PartnerEditor extends Composite<VerticalLayout> {

    public interface SaveListener {
        void onSave(PartnerEntity qr);
    }

    public interface DeleteListener {
        void onDelete(PartnerEntity qr);
    }

    public interface CancelListener {
        void onCancel();
    }

    private volatile PartnerEntity currentPartner;

    @Getter
    @Setter
    private SaveListener saveListener;
    @Getter
    @Setter
    private DeleteListener deleteListener;
    @Getter
    @Setter
    private CancelListener cancelListener;

    private final Binder<PartnerEntity> binder = new BeanValidationBinder<>(PartnerEntity.class);

    public void setCurrentPartner(PartnerEntity partner) {
        this.currentPartner = partner;
        binder.setBean(partner);
    }

    public PartnerEditor() {
        var name = new TextField("Наименование");

        var save = new Button("Сохранить", VaadinIcon.CHECK.create());
        var cancel = new Button("Отмена");
        var delete = new Button("Удалить", VaadinIcon.TRASH.create());

        binder.forField(name).bind("name");

        save.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        save.addClickListener(e -> saveListener.onSave(currentPartner));
        save.addClickShortcut(Key.ENTER);

        delete.addThemeVariants(ButtonVariant.LUMO_ERROR);
        delete.addClickListener(e -> deleteListener.onDelete(currentPartner));

        cancel.addClickListener(e -> cancelListener.onCancel());

        getContent().add(name, new HorizontalLayout(save, cancel, delete));
    }
}
