package com.example.computers.view;

import com.example.computers.entity.Component;
import com.example.computers.entity.Computer;
import com.example.computers.repository.ComponentRepository;
import com.example.computers.repository.ComputerRepository;
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 = "components", layout = MainView.class)
@PageTitle("Комплектующие")
public class ComponentView extends VerticalLayout {

    private final ComponentRepository componentRepository;
    private final ComputerRepository computerRepository;
    private final Grid<Component> grid = new Grid<>(Component.class, false);

    @Autowired
    public ComponentView(ComponentRepository componentRepository, ComputerRepository computerRepository) {
        this.componentRepository = componentRepository;
        this.computerRepository = computerRepository;

        grid.addColumn(Component::getType).setHeader("Тип");
        grid.addColumn(Component::getModel).setHeader("Модель");
        grid.addColumn(c -> c.getComputer() != null ? c.getComputer().getModel() : "").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(componentRepository.search(val));
        });

        ComboBox<String> typeFilter = new ComboBox<>();
        typeFilter.setPlaceholder("Все типы");
        typeFilter.setItems("CPU", "RAM", "SSD", "GPU", "Motherboard");
        typeFilter.setClearButtonVisible(true);
        typeFilter.setWidth("200px");
        typeFilter.addValueChangeListener(e -> {
            String val = e.getValue();
            if (val == null) updateList();
            else grid.setItems(componentRepository.findAll().stream()
                    .filter(c -> val.equals(c.getType()))
                    .toList());
        });

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

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

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

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

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

        ComboBox<String> type = new ComboBox<>("Тип");
        type.setItems("CPU", "RAM", "SSD", "GPU", "Motherboard");
        type.setValue(component.getType() != null ? component.getType() : "CPU");

        TextField model = new TextField("Модель");
        model.setValue(component.getModel() != null ? component.getModel() : "");

        ComboBox<Computer> computerBox = new ComboBox<>("Компьютер");
        computerBox.setItems(computerRepository.findAll());
        computerBox.setItemLabelGenerator(Computer::getModel);
        computerBox.setValue(component.getComputer());

        Button save = new Button("Сохранить", e -> {
            component.setType(type.getValue());
            component.setModel(model.getValue());
            component.setComputer(computerBox.getValue());
            componentRepository.save(component);
            dialog.close();
            updateList();
        });
        Button cancel = new Button("Отмена", e -> dialog.close());

        dialog.add(new VerticalLayout(
                new FormLayout(type, model, computerBox),
                new HorizontalLayout(save, cancel)));
        dialog.open();
    }
}