package com.example.computers.view;

import com.example.computers.entity.Manufacturer;
import com.example.computers.repository.ManufacturerRepository;
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 = "manufacturers", layout = MainView.class)
@PageTitle("Производители")
public class ManufacturerView extends VerticalLayout {

    private final ManufacturerRepository manufacturerRepository;
    private final Grid<Manufacturer> grid = new Grid<>(Manufacturer.class, false);

    @Autowired
    public ManufacturerView(ManufacturerRepository manufacturerRepository) {
        this.manufacturerRepository = manufacturerRepository;

        grid.addColumn(Manufacturer::getName).setHeader("Название");
        grid.addColumn(Manufacturer::getCountry).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(manufacturerRepository.search(val));
        });

        ComboBox<String> countryFilter = new ComboBox<>();
        countryFilter.setPlaceholder("Все страны");
        countryFilter.setItems(
                manufacturerRepository.findAll().stream()
                        .map(Manufacturer::getCountry)
                        .distinct()
                        .toList()
        );
        countryFilter.setClearButtonVisible(true);
        countryFilter.setWidth("200px");
        countryFilter.addValueChangeListener(e -> {
            String val = e.getValue();
            if (val == null) updateList();
            else grid.setItems(manufacturerRepository.findAll().stream()
                    .filter(m -> val.equals(m.getCountry()))
                    .toList());
        });

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

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

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

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

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

        TextField name = new TextField("Название");
        name.setValue(manufacturer.getName() != null ? manufacturer.getName() : "");

        TextField country = new TextField("Страна");
        country.setValue(manufacturer.getCountry() != null ? manufacturer.getCountry() : "");

        Button save = new Button("Сохранить", e -> {
            manufacturer.setName(name.getValue());
            manufacturer.setCountry(country.getValue());
            manufacturerRepository.save(manufacturer);
            dialog.close();
            updateList();
        });
        Button cancel = new Button("Отмена", e -> dialog.close());

        dialog.add(new VerticalLayout(
                new FormLayout(name, country),
                new HorizontalLayout(save, cancel)));
        dialog.open();
    }
}