package de.assecutor.votianlt.pages.view;

import com.vaadin.flow.component.AttachEvent;
import com.vaadin.flow.component.Key;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.dependency.JavaScript;
import com.vaadin.flow.component.html.Div;
import de.assecutor.votianlt.pages.base.ui.component.ViewToolbar;
import com.vaadin.flow.component.html.Paragraph;
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.Scroller;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.HasDynamicTitle;
import com.vaadin.flow.router.Route;
import de.assecutor.votianlt.ai.service.AiStatisticsService;
import de.assecutor.votianlt.security.SecurityService;
import de.assecutor.votianlt.util.DateTimeFormatUtil;
import jakarta.annotation.security.RolesAllowed;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.UUID;

@Route(value = "statistics", layout = de.assecutor.votianlt.pages.base.ui.view.MainLayout.class)
@RolesAllowed({ "USER", "ADMIN" })
@JavaScript("https://cdn.jsdelivr.net/npm/chart.js")
@Slf4j
public class StatisticsView extends VerticalLayout implements HasDynamicTitle {

    private final AiStatisticsService aiStatisticsService;
    private final SecurityService securityService;
    private final VerticalLayout chatContainer;
    private final TextField promptField;

    public StatisticsView(AiStatisticsService aiStatisticsService, SecurityService securityService) {
        this.aiStatisticsService = aiStatisticsService;
        this.securityService = securityService;

        // Prompt Field initialisieren
        this.promptField = new TextField();
        this.promptField.setPlaceholder(getTranslation("statistics.prompt.placeholder"));
        this.promptField.setWidthFull();
        this.promptField.setClearButtonVisible(true);
        this.promptField.addKeyPressListener(Key.ENTER, e -> sendPrompt());

        setSizeFull();
        setPadding(false);
        setSpacing(false);
        addClassName("statistics-chat-view");

        // Header
        ViewToolbar header = createHeader();
        add(header);

        // Chat Container mit Scroll
        chatContainer = new VerticalLayout();
        chatContainer.setWidthFull();
        chatContainer.setPadding(true);
        chatContainer.setSpacing(true);
        chatContainer.getStyle().set("padding-bottom", "20px");
        chatContainer.addClassName("statistics-chat-container");

        Scroller scroller = new Scroller(chatContainer);
        scroller.setSizeFull();
        scroller.setScrollDirection(Scroller.ScrollDirection.VERTICAL);
        scroller.getStyle().set("background", "var(--lumo-contrast-5pct)");
        scroller.addClassName("statistics-scroller");

        add(scroller);
        setFlexGrow(1, scroller);

        // Input Area
        HorizontalLayout inputArea = createInputArea();
        add(inputArea);
    }

    private ViewToolbar createHeader() {
        return new ViewToolbar(getTranslation("statistics.title"));
    }

    private HorizontalLayout createInputArea() {
        HorizontalLayout inputArea = new HorizontalLayout();
        inputArea.setWidthFull();
        inputArea.setPadding(true);
        inputArea.setSpacing(true);
        inputArea.setAlignItems(FlexComponent.Alignment.CENTER);
        inputArea.addClassName("statistics-input-panel");

        Button sendButton = new Button(VaadinIcon.PAPERPLANE.create());
        sendButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        sendButton.addClickListener(e -> sendPrompt());
        sendButton.getStyle().set("min-width", "50px");

        // Quick Action Buttons
        Button jobCountBtn = createQuickActionButton(getTranslation("statistics.quick.jobcount"),
                getTranslation("statistics.quick.jobcount.prompt"));
        Button revenueBtn = createQuickActionButton(getTranslation("statistics.quick.revenue"),
                getTranslation("statistics.quick.revenue.prompt"));
        Button trendBtn = createQuickActionButton(getTranslation("statistics.quick.trend"),
                getTranslation("statistics.quick.trend.prompt"));

        HorizontalLayout quickActions = new HorizontalLayout(jobCountBtn, revenueBtn, trendBtn);
        quickActions.setSpacing(true);
        quickActions.addClassName("statistics-quick-actions");

        VerticalLayout inputWrapper = new VerticalLayout();
        inputWrapper.setPadding(false);
        inputWrapper.setSpacing(true);
        inputWrapper.setWidthFull();

        HorizontalLayout inputRow = new HorizontalLayout(promptField, sendButton);
        inputRow.setWidthFull();
        inputRow.setFlexGrow(1, promptField);

        inputWrapper.add(quickActions, inputRow);

        inputArea.add(inputWrapper);
        inputArea.setFlexGrow(1, inputWrapper);

        return inputArea;
    }

    private Button createQuickActionButton(String text, String prompt) {
        Button button = new Button(text);
        button.addThemeVariants(ButtonVariant.LUMO_SMALL, ButtonVariant.LUMO_TERTIARY);
        button.addClickListener(e -> {
            promptField.setValue(prompt);
            sendPrompt();
        });
        return button;
    }

    private void sendPrompt() {
        String prompt = promptField.getValue();
        if (prompt == null || prompt.isBlank()) {
            return;
        }

        // User Message anzeigen
        addUserMessage(prompt);
        promptField.clear();

        // Loading Indicator
        Div loadingMessage = createLoadingMessage();
        chatContainer.add(loadingMessage);
        scrollToBottom();

        // Async Anfrage an KI
        UI ui = UI.getCurrent();
        String currentUserId = securityService.getCurrentUserId().toHexString();
        new Thread(() -> {
            try {
                AiStatisticsService.StatisticsResponse response = aiStatisticsService.analyzeStatisticsQuery(prompt,
                        currentUserId);

                ui.access(() -> {
                    chatContainer.remove(loadingMessage);
                    addAiResponse(response);
                    scrollToBottom();
                });
            } catch (Exception e) {
                log.error("Error processing AI request", e);
                ui.access(() -> {
                    chatContainer.remove(loadingMessage);
                    addErrorMessage(getTranslation("statistics.error", e.getMessage()));
                    scrollToBottom();
                });
            }
        }).start();
    }

    private void addUserMessage(String message) {
        Div messageDiv = new Div();
        messageDiv.addClassNames("chat-message", "user-message");

        Div bubble = new Div();
        bubble.addClassNames("chat-bubble", "chat-bubble--user");

        Paragraph text = new Paragraph(message);
        text.getStyle().set("margin", "0");

        Span time = new Span(DateTimeFormatUtil.formatTime(LocalDateTime.now()));
        time.getStyle().set("font-size", "var(--lumo-font-size-xs)").set("opacity", "0.7").set("display", "block")
                .set("text-align", "right").set("margin-top", "var(--lumo-space-xs)");

        bubble.add(text, time);
        messageDiv.add(bubble);
        chatContainer.add(messageDiv);
    }

    private void addAiResponse(AiStatisticsService.StatisticsResponse response) {
        Div messageDiv = new Div();
        messageDiv.addClassNames("chat-message", "ai-message");

        Div bubble = new Div();
        bubble.addClassNames("chat-bubble", "chat-bubble--ai");

        // AI Icon
        HorizontalLayout header = new HorizontalLayout();
        header.setAlignItems(FlexComponent.Alignment.CENTER);
        header.setSpacing(true);

        Icon aiIcon = VaadinIcon.MAGIC.create();
        aiIcon.setSize("16px");
        aiIcon.getStyle().set("color", "var(--lumo-primary-color)");

        Span aiLabel = new Span(getTranslation("statistics.ai.label"));
        aiLabel.getStyle().set("font-weight", "bold").set("font-size", "var(--lumo-font-size-s)");

        header.add(aiIcon, aiLabel);
        bubble.add(header);

        // Text Response
        Div textDiv = new Div();
        textDiv.getStyle().set("margin-top", "var(--lumo-space-s)");
        String responseText = response.textResponse();
        if (responseText == null || responseText.isBlank()) {
            responseText = getTranslation("statistics.data.fetched");
        }
        textDiv.getElement().setProperty("innerHTML", formatMarkdown(responseText));
        bubble.add(textDiv);

        // Chart wenn vorhanden
        if (response.chartData() != null && !response.chartData().isEmpty()) {
            Div chartContainer = createChart(response.chartType(), response.chartData());
            if (chartContainer != null) {
                chartContainer.getStyle().set("margin-top", "var(--lumo-space-m)").set("height", "300px");
                bubble.add(chartContainer);
            }
        }

        if (response.tableHtml() != null && !response.tableHtml().isBlank()) {
            Div tableContainer = new Div();
            tableContainer.getStyle().set("margin-top", "var(--lumo-space-m)").set("overflow", "auto");
            tableContainer.getElement().setProperty("innerHTML", response.tableHtml());
            bubble.add(tableContainer);
        }

        // Timestamp
        Span time = new Span(DateTimeFormatUtil.formatTime(LocalDateTime.now()));
        time.getStyle().set("font-size", "var(--lumo-font-size-xs)").set("color", "var(--lumo-secondary-text-color)")
                .set("display", "block").set("margin-top", "var(--lumo-space-s)");
        bubble.add(time);

        messageDiv.add(bubble);
        chatContainer.add(messageDiv);
    }

    private void addErrorMessage(String message) {
        Div messageDiv = new Div();
        messageDiv.addClassNames("chat-message", "error-message");

        Div bubble = new Div();
        bubble.addClassNames("chat-bubble", "chat-bubble--error");

        Icon errorIcon = VaadinIcon.EXCLAMATION_CIRCLE.create();
        errorIcon.setSize("16px");
        errorIcon.getStyle().set("color", "var(--lumo-error-color)");

        Span text = new Span(message);
        text.getStyle().set("color", "var(--lumo-error-text-color)");

        HorizontalLayout content = new HorizontalLayout(errorIcon, text);
        content.setAlignItems(FlexComponent.Alignment.CENTER);
        content.setSpacing(true);

        bubble.add(content);
        messageDiv.add(bubble);
        chatContainer.add(messageDiv);
    }

    private Div createLoadingMessage() {
        Div messageDiv = new Div();
        messageDiv.addClassNames("chat-message", "loading-message");

        Div bubble = new Div();
        bubble.addClassNames("chat-bubble", "chat-bubble--loading");

        Span dots = new Span(getTranslation("statistics.loading"));
        dots.getStyle().set("color", "var(--lumo-secondary-text-color)").set("font-style", "italic");

        bubble.add(dots);
        messageDiv.add(bubble);
        return messageDiv;
    }

    private Div createChart(String chartType, String chartData) {
        if (chartType == null || chartData == null) {
            return null;
        }

        String canvasId = "chart-" + UUID.randomUUID().toString().substring(0, 8);
        Div chartContainer = new Div();
        chartContainer.addClassName("chart-wrapper");
        chartContainer.getStyle().set("background", "var(--lumo-contrast-5pct)")
                .set("border-radius", "var(--lumo-border-radius-m)").set("padding", "var(--lumo-space-s)");

        chartContainer.getElement().setProperty("innerHTML",
                "<canvas id='" + canvasId + "' style='width: 100%; height: 100%;'></canvas>");

        // Moderne Chart.js Konfiguration mit Animationen und Styling
        String chartOptions = getChartOptions(chartType);

        // JavaScript direkt mit eingebetteter Konfiguration ausführen
        String script = String.format("""
                (function() {
                    function initChart() {
                        if (typeof Chart === 'undefined') {
                            console.log('Chart.js not loaded yet, retrying...');
                            setTimeout(initChart, 100);
                            return;
                        }
                        const canvas = document.getElementById('%s');
                        if (!canvas) {
                            console.log('Canvas not found, retrying...');
                            setTimeout(initChart, 50);
                            return;
                        }
                        // Vorheriges Chart zerstören falls vorhanden
                        if (canvas.chartInstance) {
                            canvas.chartInstance.destroy();
                        }
                        const ctx = canvas.getContext('2d');
                        try {
                            canvas.chartInstance = new Chart(ctx, {
                                type: '%s',
                                data: %s,
                                options: %s
                            });
                            console.log('Chart created successfully');
                        } catch (e) {
                            console.error('Chart creation error:', e);
                        }
                    }
                    initChart();
                })();
                """, canvasId, chartType, chartData, chartOptions);

        chartContainer.getElement().executeJs(script);

        return chartContainer;
    }

    private String getChartOptions(String chartType) {
        // Gradient und moderne Farben für verschiedene Chart-Typen
        return switch (chartType) {
        case "line" -> """
                {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: {
                        intersect: false,
                        mode: 'index'
                    },
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                usePointStyle: true,
                                padding: 20
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0,0,0,0.8)',
                            titleFont: { size: 14, weight: 'bold' },
                            bodyFont: { size: 13 },
                            padding: 12,
                            cornerRadius: 8
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0,0,0,0.05)'
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            }
                        }
                    },
                    elements: {
                        line: {
                            tension: 0.4,
                            borderWidth: 3
                        },
                        point: {
                            radius: 4,
                            hoverRadius: 6,
                            hitRadius: 10
                        }
                    },
                    animation: {
                        duration: 1000,
                        easing: 'easeOutQuart'
                    }
                }
                """;
        case "bar" -> """
                {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                usePointStyle: true,
                                padding: 20
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0,0,0,0.8)',
                            titleFont: { size: 14, weight: 'bold' },
                            bodyFont: { size: 13 },
                            padding: 12,
                            cornerRadius: 8
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0,0,0,0.05)'
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            }
                        }
                    },
                    elements: {
                        bar: {
                            borderRadius: 6,
                            borderSkipped: false
                        }
                    },
                    animation: {
                        duration: 800,
                        easing: 'easeOutQuart'
                    }
                }
                """;
        case "doughnut" -> """
                {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'right',
                            labels: {
                                usePointStyle: true,
                                padding: 15,
                                font: { size: 12 }
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0,0,0,0.8)',
                            titleFont: { size: 14, weight: 'bold' },
                            bodyFont: { size: 13 },
                            padding: 12,
                            cornerRadius: 8
                        }
                    },
                    cutout: '60%',
                    animation: {
                        animateRotate: true,
                        animateScale: true,
                        duration: 1000,
                        easing: 'easeOutQuart'
                    }
                }
                """;
        case "pie" -> """
                {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'right',
                            labels: {
                                usePointStyle: true,
                                padding: 15,
                                font: { size: 12 }
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0,0,0,0.8)',
                            titleFont: { size: 14, weight: 'bold' },
                            bodyFont: { size: 13 },
                            padding: 12,
                            cornerRadius: 8
                        }
                    },
                    animation: {
                        animateRotate: true,
                        animateScale: true,
                        duration: 1000,
                        easing: 'easeOutQuart'
                    }
                }
                """;
        case "radar" -> """
                {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top',
                            labels: {
                                usePointStyle: true,
                                padding: 15
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0,0,0,0.8)',
                            titleFont: { size: 14, weight: 'bold' },
                            bodyFont: { size: 13 },
                            padding: 12,
                            cornerRadius: 8
                        }
                    },
                    scales: {
                        r: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0,0,0,0.1)'
                            },
                            pointLabels: {
                                font: { size: 12 }
                            }
                        }
                    },
                    elements: {
                        line: {
                            borderWidth: 2
                        },
                        point: {
                            radius: 4,
                            hoverRadius: 6
                        }
                    },
                    animation: {
                        duration: 1000,
                        easing: 'easeOutQuart'
                    }
                }
                """;
        case "polarArea" -> """
                {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'right',
                            labels: {
                                usePointStyle: true,
                                padding: 15,
                                font: { size: 12 }
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0,0,0,0.8)',
                            titleFont: { size: 14, weight: 'bold' },
                            bodyFont: { size: 13 },
                            padding: 12,
                            cornerRadius: 8
                        }
                    },
                    scales: {
                        r: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0,0,0,0.1)'
                            }
                        }
                    },
                    animation: {
                        animateRotate: true,
                        animateScale: true,
                        duration: 1000,
                        easing: 'easeOutQuart'
                    }
                }
                """;
        default -> """
                {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    },
                    animation: {
                        duration: 800
                    }
                }
                """;
        };
    }

    private String formatMarkdown(String text) {
        if (text == null)
            return "";
        // Einfache Markdown-Formatierung
        return text.replace("\n", "<br>").replaceAll("\\*\\*(.+?)\\*\\*", "<strong>$1</strong>")
                .replaceAll("\\*(.+?)\\*", "<em>$1</em>").replaceAll("`(.+?)`", "<code>$1</code>");
    }

    private void scrollToBottom() {
        chatContainer.getElement().executeJs("this.parentElement.scrollTop = this.parentElement.scrollHeight");
    }

    @Override
    protected void onAttach(AttachEvent attachEvent) {
        super.onAttach(attachEvent);
        scrollToBottom();
    }

    @Override
    public String getPageTitle() {
        return getTranslation("page.title.statistics");
    }
}
