package com.example.computers.view;

import com.example.computers.entity.Computer;
import com.example.computers.entity.Repair;
import com.example.computers.repository.ComputerRepository;
import com.example.computers.repository.RepairRepository;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.datepicker.DatePicker;
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.NumberField;
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;

import java.time.LocalDate;

@Route(value = "repairs", layout = MainView.class)
@PageTitle("Ремонты")
public class RepairView extends VerticalLayout {

    private final RepairRepository repairRepository;
    private final ComputerRepository computerRepository;
    private final Grid<Repair> grid = new Grid<>(Repair.class, false);

    @Autowired
    public RepairView(RepairRepository repairRepository, ComputerRepository computerRepository) {
        this.repairRepository = repairRepository;
        this.computerRepository = computerRepository;

        grid.addColumn(r -> r.getComputer() != null ? r.getComputer().getModel() : "").setHeader("Компьютер");
        grid.addColumn(Repair::getRepairDate).setHeader("Дата");
        grid.addColumn(Repair::getDescription).setHeader("Описание");
        grid.addColumn(Repair::getCost).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(repairRepository.search(val));
        });

        ComboBox<Computer> computerFilter = new ComboBox<>();
        computerFilter.setPlaceholder("Все компьютеры");
        computerFilter.setItems(computerRepository.findAll());
        computerFilter.setItemLabelGenerator(Computer::getModel);
        computerFilter.setClearButtonVisible(true);
        computerFilter.setWidth("200px");
        computerFilter.addValueChangeListener(e -> {
            Computer val = e.getValue();
            if (val == null) updateList();
            else grid.setItems(repairRepository.findAll().stream()
                    .filter(r -> r.getComputer() != null && r.getComputer().getId().equals(val.getId()))
                    .toList());
        });

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

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

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

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

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

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

        DatePicker repairDate = new DatePicker("Дата ремонта");
        repairDate.setValue(repair.getRepairDate() != null ? repair.getRepairDate() : LocalDate.now());

        TextField description = new TextField("Описание");
        description.setValue(repair.getDescription() != null ? repair.getDescription() : "");

        NumberField cost = new NumberField("Стоимость");
        cost.setValue(repair.getCost() != null ? repair.getCost() : 0.0);

        Button save = new Button("Сохранить", e -> {
            repair.setComputer(computerBox.getValue());
            repair.setRepairDate(repairDate.getValue());
            repair.setDescription(description.getValue());
            repair.setCost(cost.getValue());
            repairRepository.save(repair);
            dialog.close();
            updateList();
        });
        Button cancel = new Button("Отмена", e -> dialog.close());

        dialog.add(new VerticalLayout(
                new FormLayout(computerBox, repairDate, description, cost),
                new HorizontalLayout(save, cancel)));
        dialog.open();
    }
}