package de.assecutor.votianlt.pages.base.ui.component;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.html.H3;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.icon.Icon;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.orderedlayout.FlexComponent;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import java.util.List;

/**
 * A compact tile representing a station (pickup or delivery) in a grid layout.
 * Shows only a title and text preview of entered data. Clicking the tile opens
 * a dialog for data entry.
 */
public class StationTile extends VerticalLayout {

    public enum StationType {
        PICKUP, DELIVERY
    }

    public interface ClickListener {
        void onClick(StationTile tile);
    }

    public interface DeleteListener {
        void onDelete(StationTile tile);
    }

    private final StationType type;
    private int stationNumber;
    private final H3 title;
    private final VerticalLayout previewContent;
    private ClickListener clickListener;
    private DeleteListener deleteListener;

    public StationTile(StationType type, int stationNumber, String titleText, boolean removable) {
        this.type = type;
        this.stationNumber = stationNumber;

        setPadding(false);
        setSpacing(false);
        addClassName("station-tile");
        getStyle().set("cursor", "pointer");
        getStyle().set("aspect-ratio", "1 / 1");
        getStyle().set("overflow", "hidden");
        getStyle().set("padding", "var(--lumo-space-m)");

        // Header with title and optional delete button
        title = new H3(titleText);
        title.getStyle().set("margin", "0").set("flex-grow", "1").set("font-size", "var(--lumo-font-size-m)");

        HorizontalLayout titleLayout = new HorizontalLayout();
        titleLayout.setWidthFull();
        titleLayout.setPadding(false);
        titleLayout.setSpacing(false);
        titleLayout.setDefaultVerticalComponentAlignment(FlexComponent.Alignment.START);
        titleLayout.add(title);

        if (removable) {
            Button deleteButton = new Button(new Icon(VaadinIcon.CLOSE_SMALL));
            deleteButton.addThemeVariants(ButtonVariant.LUMO_ERROR, ButtonVariant.LUMO_TERTIARY,
                    ButtonVariant.LUMO_ICON);
            deleteButton.getStyle().set("min-width", "0").set("min-height", "0").set("padding", "0").set("margin", "0")
                    .set("height", "var(--lumo-font-size-m)").set("line-height", "var(--lumo-font-size-m)");
            // Stop propagation on the client side to prevent the tile click from firing
            deleteButton.getElement().setAttribute("onclick", "event.stopPropagation()");
            deleteButton.addClickListener(e -> {
                if (deleteListener != null) {
                    deleteListener.onDelete(this);
                }
            });
            titleLayout.add(deleteButton);
        }

        add(titleLayout);

        // Preview content area
        previewContent = new VerticalLayout();
        previewContent.setPadding(false);
        previewContent.setSpacing(false);
        previewContent.getStyle().set("gap", "0.15rem");
        previewContent.getStyle().set("margin-top", "10px");
        previewContent.getStyle().set("flex-grow", "1");
        add(previewContent);

        // Show placeholder when no data
        updateEmptyPreview();

        // Click on the tile opens the dialog
        addClickListener(e -> {
            if (clickListener != null) {
                clickListener.onClick(this);
            }
        });
    }

    public void updatePreview(String company, String firstName, String lastName, String street, String houseNumber,
            String zip, String city) {
        updatePreview(company, firstName, lastName, street, houseNumber, zip, city, List.of());
    }

    public void updatePreview(String company, String firstName, String lastName, String street, String houseNumber,
            String zip, String city, List<String> additionalLines) {
        previewContent.removeAll();
        previewContent.setJustifyContentMode(FlexComponent.JustifyContentMode.START);
        previewContent.setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.START);

        boolean hasData = false;

        if (company != null && !company.trim().isEmpty()) {
            addPreviewLine(company);
            hasData = true;
        }

        String name = ((firstName != null ? firstName : "") + " " + (lastName != null ? lastName : "")).trim();
        if (!name.isEmpty()) {
            addPreviewLine(name);
            hasData = true;
        }

        String streetLine = ((street != null ? street : "") + " " + (houseNumber != null ? houseNumber : "")).trim();
        if (!streetLine.isEmpty()) {
            addPreviewLine(streetLine);
            hasData = true;
        }

        String zipCityLine = ((zip != null ? zip : "") + " " + (city != null ? city : "")).trim();
        if (!zipCityLine.isEmpty()) {
            addPreviewLine(zipCityLine);
            hasData = true;
        }

        if (additionalLines != null) {
            for (String line : additionalLines) {
                if (line != null && !line.trim().isEmpty()) {
                    addPreviewLine(line);
                    hasData = true;
                }
            }
        }

        if (!hasData) {
            updateEmptyPreview();
        }
    }

    private void updateEmptyPreview() {
        previewContent.removeAll();
        previewContent.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER);
        previewContent.setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.CENTER);
        Span placeholder = new Span(getTranslation("addjob.station.unused"));
        placeholder.getStyle().set("color", "var(--lumo-contrast-30pct)").set("font-size", "var(--lumo-font-size-xl)");
        previewContent.add(placeholder);
    }

    private void addPreviewLine(String text) {
        Span span = new Span(text);
        span.getStyle().set("font-size", "var(--lumo-font-size-xs)").set("line-height", "1.2")
                .set("word-break", "break-word").set("color", "var(--lumo-secondary-text-color)");
        previewContent.add(span);
    }

    public void updateTitle(String newTitle) {
        title.setText(newTitle);
    }

    public void updateStationNumber(int newNumber) {
        this.stationNumber = newNumber;
    }

    public StationType getType() {
        return type;
    }

    public int getStationNumber() {
        return stationNumber;
    }

    public void setClickListener(ClickListener listener) {
        this.clickListener = listener;
    }

    public void setDeleteListener(DeleteListener listener) {
        this.deleteListener = listener;
    }

    public void setInteractive(boolean interactive) {
        getStyle().set("cursor", interactive ? "pointer" : "default");
    }

    public void setAddressValidated(boolean validated) {
        if (validated) {
            addClassName("validated");
        } else {
            removeClassName("validated");
        }
    }
}
