package ru.vyatsu.qr_access_admin.unit.component;

import ru.vyatsu.qr_access_admin.unit.model.UnitModel;
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.datetimepicker.DateTimePicker;
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;

public class UnitEditor extends Composite<VerticalLayout> {
    public interface SaveListener {
        void onSave(UnitModel unit);
    }

    public interface DeleteListener {
        void onDelete(UnitModel unit);
    }

    public interface CancelListener {
        void onCancel();
    }

    private volatile UnitModel currentUnit;

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

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

    public void setCurrentUnit(UnitModel unit) {
        this.currentUnit = unit;
        binder.setBean(unit);
    }

    public UnitEditor() {
        var clientId = new TextField("Идентификатор устройства");
        clientId.setRequired(true);
        var clientSecret = new TextField("Секрет устройства");
        clientSecret.setRequired(true);
        var clientSecretExpiresAt = new DateTimePicker("Актуален до");
        clientSecretExpiresAt.setRequiredIndicatorVisible(true);
        var clientName = new TextField("Человекочитаемое название устройства");
        clientName.setRequired(true);

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

        binder.forField(clientId).bind("clientId");
        binder.forField(clientSecret).bind("clientSecret");
        binder.forField(clientSecretExpiresAt).bind("clientSecretExpiresAt");
        binder.forField(clientName).bind("clientName");

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

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

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

        getContent().add(clientId, clientSecret, clientSecretExpiresAt, clientName, new HorizontalLayout(save, cancel, delete));
    }
}
