package ru.vyatsu.qr_access_admin.door.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.combobox.ComboBox;
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.IntegerField;
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.door.entity.DoorEntity;
import ru.vyatsu.qr_access_admin.door.schedule.component.ScheduleEditor;
import ru.vyatsu.qr_access_admin.door.schedule.entity.ScheduleEntity;
import ru.vyatsu.qr_access_admin.door.schedule.entity.ScheduleRepository;
import ru.vyatsu.qr_access_admin.unit.entity.UnitRepository;
import ru.vyatsu.qr_access_admin.unit.mapper.UnitEntityUnitComboBoxModelMapper;
import ru.vyatsu.qr_access_admin.unit.model.UnitComboBoxModel;

import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;

public class DoorEditor extends Composite<VerticalLayout> {

    public interface SaveListener {
        void onSave(DoorEntity door, Collection<ScheduleEntity> schedule);
    }

    public interface DeleteListener {
        void onDelete(DoorEntity door) throws Exception;
    }

    public interface CancelListener {
        void onCancel();
    }

    private DoorEntity currentDoor;

    private final ScheduleEditor scheduleEditor;

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

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

    public void setCurrentDoor(DoorEntity door) {
        this.currentDoor = door;
        binder.setBean(door);
        scheduleEditor.setCurrentDoorId(door.getId());
        scheduleEditor.refreshScheduleView();
    }

    public DoorEditor(UnitRepository unitRepository, ScheduleRepository scheduleRepository) {
        ComboBox<UnitComboBoxModel> unitField = new ComboBox<>("Устройство");
        unitField.setRequired(true);
        unitField.setPageSize(100);
        Map<String, UnitComboBoxModel> units = unitRepository.findAll()
                .stream()
                .map(new UnitEntityUnitComboBoxModelMapper()::toModel)
                .collect(Collectors.toMap(UnitComboBoxModel::clientId, unit -> unit));
        unitField.setItems(units.values());
        unitField.setItemLabelGenerator(UnitComboBoxModel::clientName);
        IntegerField countField = new IntegerField("Количество мест");
        TextField descriptionField = new TextField("Описание");

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

        binder.forField(unitField)
                .withConverter(UnitComboBoxModel::clientId, units::get, "Invalid value")
                .bind("unitId");
        binder.forField(countField).bind("count");
        binder.forField(descriptionField).bind("description");

        save.addThemeVariants(ButtonVariant.LUMO_PRIMARY);

        scheduleEditor = new ScheduleEditor(scheduleRepository);

        save.addClickListener(e -> saveListener.onSave(currentDoor, scheduleEditor.getNewSchedule()));
        save.addClickShortcut(Key.ENTER);

        delete.addThemeVariants(ButtonVariant.LUMO_ERROR);
        delete.addClickListener(e -> {
            try {
                deleteListener.onDelete(currentDoor);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        });

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

        getContent().add(unitField, countField, descriptionField, scheduleEditor, new HorizontalLayout(save, cancel, delete));
    }
}
