package com.example.computers.view;

import com.example.computers.entity.Location;
import com.example.computers.repository.LocationRepository;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.orderedlayout.FlexComponent;
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.router.PageTitle;
import com.vaadin.flow.router.Route;
import org.springframework.beans.factory.annotation.Autowired;

@Route(value = "locations", layout = MainView.class)
@PageTitle("Локации")
public class LocationView extends VerticalLayout {

    private final LocationRepository locationRepository;
    private final Grid<Location> grid = new Grid<>(Location.class, false);

    @Autowired
    public LocationView(LocationRepository locationRepository) {
        this.locationRepository = locationRepository;

        grid.addColumn(Location::getBuilding).setHeader("Здание");
        grid.addColumn(Location::getRoom).setHeader("Кабинет");
        grid.addColumn(Location::getResponsiblePerson).setHeader("Ответственный");

        TextField searchField = new TextField();
        searchField.setPlaceholder("Поиск по зданию, кабинету...");
        searchField.setWidth("300px");
        searchField.addValueChangeListener(e -> {
            String val = e.getValue().trim();
            if (val.isEmpty()) updateList();
            else grid.setItems(locationRepository.search(val));
        });

        ComboBox<String> buildingFilter = new ComboBox<>();
        buildingFilter.setPlaceholder("Все здания");
        buildingFilter.setItems(
                locationRepository.findAll().stream()
                        .map(Location::getBuilding)
                        .distinct()
                        .toList()
        );
        buildingFilter.setClearButtonVisible(true);
        buildingFilter.setWidth("200px");
        buildingFilter.addValueChangeListener(e -> {
            String val = e.getValue();
            if (val == null) updateList();
            else grid.setItems(locationRepository.findAll().stream()
                    .filter(l -> val.equals(l.getBuilding()))
                    .toList());
        });

        HorizontalLayout filters = new HorizontalLayout(searchField, buildingFilter);
        filters.setAlignItems(FlexComponent.Alignment.BASELINE);

        Button addButton    = new Button("Добавить",      e -> openForm(new Location()));
        Button editButton   = new Button("Редактировать", e -> {
            Location selected = grid.asSingleSelect().getValue();
            if (selected != null) openForm(selected);
        });
        Button deleteButton = new Button("Удалить", e -> {
            Location selected = grid.asSingleSelect().getValue();
            if (selected != null) { locationRepository.delete(selected); updateList(); }
        });

        add(new HorizontalLayout(addButton, editButton, deleteButton), filters, grid);
        updateList();
    }

    private void updateList() {
        grid.setItems(locationRepository.findAll());
    }

    private void openForm(Location location) {
        Dialog dialog = new Dialog();
        dialog.setWidth("400px");

        TextField building = new TextField("Здание");
        building.setValue(location.getBuilding() != null ? location.getBuilding() : "");

        TextField room = new TextField("Кабинет");
        room.setValue(location.getRoom() != null ? location.getRoom() : "");

        TextField responsiblePerson = new TextField("Ответственный");
        responsiblePerson.setValue(location.getResponsiblePerson() != null ? location.getResponsiblePerson() : "");

        Button save = new Button("Сохранить", e -> {
            location.setBuilding(building.getValue());
            location.setRoom(room.getValue());
            location.setResponsiblePerson(responsiblePerson.getValue());
            locationRepository.save(location);
            dialog.close();
            updateList();
        });
        Button cancel = new Button("Отмена", e -> dialog.close());

        dialog.add(new VerticalLayout(
                new FormLayout(building, room, responsiblePerson),
                new HorizontalLayout(save, cancel)));
        dialog.open();
    }
}