package de.thpeetz.kontor.comics.views;

import de.thpeetz.kontor.common.views.ColumnToggleContextMenu;
import de.thpeetz.kontor.common.views.MainLayout;
import de.thpeetz.kontor.common.views.SearchFilterField;
import de.thpeetz.kontor.common.views.StatusIcon;
import org.springframework.context.annotation.Scope;

import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.spring.annotation.SpringComponent;

import de.thpeetz.kontor.comics.ComicConstants;
import de.thpeetz.kontor.comics.data.Comic;
import de.thpeetz.kontor.comics.services.ComicService;
import jakarta.annotation.security.PermitAll;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@SpringComponent
@Scope("prototype")
@PermitAll
@Route(value = ComicConstants.COMICS_ROUTE, layout = MainLayout.class)
@PageTitle("Comic | Comics | Kontor")
public class ComicView extends VerticalLayout {

    @Getter
    Grid<Comic> grid = new Grid<>(Comic.class, false);
    Grid.Column<Comic> idColumn = grid.addColumn(Comic::getId)
            .setHeader("ID").setResizable(true).setSortable(true);
    Grid.Column<Comic> createdColumn = grid.addColumn(Comic::getCreatedDate)
            .setHeader("Erstellt").setResizable(true).setSortable(true);
    Grid.Column<Comic> modifiedColumn = grid.addColumn(Comic::getLastModifiedDate)
            .setHeader("Geändert").setResizable(true).setSortable(true);
    Grid.Column<Comic> titleColumn = grid.addColumn(Comic::getTitle)
            .setHeader("Titel").setResizable(true).setSortable(true);
    Grid.Column<Comic> publisherColumn = grid.addColumn(Comic::getPublisherName)
            .setHeader("Verlag").setResizable(true).setSortable(true);
    Grid.Column<Comic> currentOrderColumn = grid.addComponentColumn(comic -> StatusIcon.create(comic.getCurrentOrder()))
            .setHeader("Bestellung").setWidth("6rem").setSortable(true);
    Grid.Column<Comic> completedColumn = grid.addComponentColumn(comic -> StatusIcon.create(comic.getCompleted()))
            .setHeader("Abgeschlossen").setWidth("6rem").setSortable(true);
    Grid.Column<Comic> weblinkColumn = grid.addColumn(Comic::getWeblink)
            .setHeader("Link").setResizable(true).setSortable(true);
    SearchFilterField searchFilterField = new SearchFilterField();
    @Getter
    ComicForm form;
    ComicService service;

    public ComicView(ComicService service) {
        this.service = service;
        addClassName("comic-view");
        setSizeFull();
        configureGrid();
        configureForm();

        add(getToolbar(), getContent());
        updateList();
    }

    private void configureGrid() {
        grid.addClassName("comic-grid");
        grid.setSizeFull();
        grid.getColumns().forEach(col -> col.setAutoWidth(true));
        grid.asSingleSelect().addValueChangeListener(event -> editComic(event.getValue()));
    }

    private void configureForm() {
        form = new ComicForm(service.findAllPublishers(null));
        form.setWidth("25em");
        form.setVisible(false);
        form.addSaveListener(this::saveComic);
        form.addDeleteListener(this::deleteComic);
        form.addCloseListener(e -> closeEditor());
    }

    private void saveComic(ComicForm.SaveEvent event) {
        service.saveComic(event.getComic());
        updateList();
        closeEditor();
    }

    private void deleteComic(ComicForm.DeleteEvent event) {
        service.deleteComic(event.getComic());
        updateList();
        closeEditor();
    }

    private Component getContent() {
        HorizontalLayout content = new HorizontalLayout(grid, form);
        content.setFlexGrow(2, grid);
        content.setFlexGrow(1, form);
        content.addClassName("content");
        content.setSizeFull();
        return content;
    }

    private HorizontalLayout getToolbar() {
        searchFilterField.addFilter("Bestellung");
        searchFilterField.addFilter("Abgeschlossen");
        searchFilterField.addValueChangeListener(e -> updateList());

        Button addComicButton = new Button("Add comic");
        addComicButton.addClickListener(click -> addComic());

        Button menuButton = new Button("Show/Hide Columns");
        menuButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
        ColumnToggleContextMenu<Comic> columnToggleContextMenu = new ColumnToggleContextMenu<>(menuButton);
        columnToggleContextMenu.addColumnToggleItem(idColumn);
        columnToggleContextMenu.addColumnToggleItem(createdColumn);
        columnToggleContextMenu.addColumnToggleItem(modifiedColumn);
        columnToggleContextMenu.addColumnToggleItem(titleColumn);
        columnToggleContextMenu.addColumnToggleItem(publisherColumn);
        columnToggleContextMenu.addColumnToggleItem(currentOrderColumn);
        columnToggleContextMenu.addColumnToggleItem(completedColumn);
        columnToggleContextMenu.addColumnToggleItem(weblinkColumn);
        HorizontalLayout toolbar = new HorizontalLayout(searchFilterField, addComicButton, menuButton);
        toolbar.addClassName("toolbar");
        return toolbar;
    }

    public void editComic(Comic comic) {
        if (comic == null) {
            closeEditor();
        } else {
            form.setComic(comic);
            if (comic.getComicWorks() == null) {
                log.info("No comic works");
            } else {
                log.info("Comic works sze: {}", comic.getComicWorks().size());
            }
            form.setComicWorks(comic.getComicWorks());
            form.setVisible(true);
            addClassName("editing");
        }
    }

    private void closeEditor() {
        form.setComic(null);
        form.setVisible(false);
        removeClassName("editing");
    }

    private void addComic() {
        grid.asSingleSelect().clear();
        editComic(new Comic());
    }

    public void updateList() {
        grid.setItems(service.findAllComicsByFilter(searchFilterField.getValue()));
    }
}
