package de.thpeetz.kontor.comics.views;

import com.vaadin.flow.component.button.*;
import de.thpeetz.kontor.comics.data.*;
import de.thpeetz.kontor.common.views.*;
import lombok.*;
import org.springframework.context.annotation.Scope;

import com.vaadin.flow.component.Component;
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.component.textfield.TextField;
import com.vaadin.flow.data.value.ValueChangeMode;
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.services.ComicService;
import jakarta.annotation.security.PermitAll;

@SpringComponent
@Scope("prototype")
@PermitAll
@Route(value = ComicConstants.PUBLISHER_ROUTE, layout = MainLayout.class)
@PageTitle("Publisher | Comics | Kontor")
public class PublisherView extends VerticalLayout {

    @Getter
    Grid<Publisher> grid = new Grid<>(Publisher.class, false);
    Grid.Column<Publisher> idColumn = grid.addColumn(Publisher::getId)
            .setHeader("ID").setResizable(true).setSortable(true);
    Grid.Column<Publisher> createdColumn = grid.addColumn(Publisher::getCreatedDate)
            .setHeader("Erstellt").setResizable(true).setSortable(true);
    Grid.Column<Publisher> modifiedColumn = grid.addColumn(Publisher::getLastModifiedDate)
            .setHeader("Geändert").setResizable(true).setSortable(true);
    Grid.Column<Publisher> nameColumn = grid.addColumn(Publisher::getName)
            .setHeader("Titel").setResizable(true).setSortable(true);
    Grid.Column<Publisher> parentCompanyColumn = grid.addColumn(Publisher::getParentCompanyName)
            .setHeader("Parent Company").setResizable(true).setSortable(true);
    Grid.Column<Publisher> imprintColumn = grid.addComponentColumn(publisher -> StatusIcon.create(publisher.getParentCompany() != null))
            .setHeader("Imprint").setWidth("6rem").setSortable(true);
    Grid.Column<Publisher> weblinkColumn = grid.addColumn(Publisher::getWeblink)
            .setHeader("Link").setResizable(true).setSortable(true);
    TextField filterText = new TextField();
    @Getter
    PublisherForm form;

    ComicService service;

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

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

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

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

    private void savePublisher(PublisherForm.SaveEvent event) {
        service.savePublisher(event.getPublisher());
        updateList();
        closeEditor();
    }

    private void deletePublisher(PublisherForm.DeleteEvent event) {
        service.deletePublisher(event.getPublisher());
        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() {
        filterText.setPlaceholder("Filter by name...");
        filterText.setClearButtonVisible(true);
        filterText.setValueChangeMode(ValueChangeMode.LAZY);
        filterText.addValueChangeListener(e -> updateList());

        Button addPublisherButton = new Button("Add publisher");
        addPublisherButton.addClickListener(click -> addPublisher());

        Button menuButton = new Button("Show/Hide Columns");
        menuButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
        ColumnToggleContextMenu<Publisher> columnToggleContextMenu = new ColumnToggleContextMenu<>(menuButton);
        columnToggleContextMenu.addColumnToggleItem(idColumn);
        columnToggleContextMenu.addColumnToggleItem(createdColumn);
        columnToggleContextMenu.addColumnToggleItem(modifiedColumn);
        columnToggleContextMenu.addColumnToggleItem(nameColumn);
        columnToggleContextMenu.addColumnToggleItem(parentCompanyColumn);
        columnToggleContextMenu.addColumnToggleItem(imprintColumn);
        columnToggleContextMenu.addColumnToggleItem(weblinkColumn);
        HorizontalLayout toolbar = new HorizontalLayout(filterText, addPublisherButton, menuButton);
        toolbar.addClassName("toolbar");
        return toolbar;
    }

    public void editPublisher(Publisher publisher) {
        if (publisher == null) {
            closeEditor();
        } else {
            form.setPublisher(publisher);
            form.setVisible(true);
            addClassName("editing");
        }
    }

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

    private void addPublisher() {
        grid.asSingleSelect().clear();
        editPublisher(new Publisher());
    }

    public void updateList() {
        grid.setItems(service.findAllPublishers(filterText.getValue()));
    }
}
