package ru.vyatsu.qr_access_admin.client.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.checkbox.Checkbox;
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.EmailField;
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.client.entity.ClientEntity;

public class ClientEditor extends Composite<VerticalLayout> {

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

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

    public interface CancelListener {
        void onCancel();
    }

    private volatile ClientEntity currentClient;

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

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

    public void setCurrentClient(ClientEntity client) {
        this.currentClient = client;
        binder.setBean(client);
    }

    public ClientEditor() {
        var email = new EmailField("E-mail");
        var emailIsConfirmed = new Checkbox("e-mail подтвержден");

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

        binder.forField(email).bind("email");
        binder.forField(emailIsConfirmed).bind("emailIsConfirmed");

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

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

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

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