package de.assecutor.votianlt.pages.view;

import com.vaadin.flow.component.Component;
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.combobox.ComboBox;
import com.vaadin.flow.component.html.*;
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 com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.router.BeforeEnterEvent;
import com.vaadin.flow.router.BeforeEnterObserver;
import com.vaadin.flow.server.auth.AnonymousAllowed;
import de.assecutor.votianlt.security.SecurityService;
import org.springframework.beans.factory.annotation.Value;

@Route("")
@PageTitle("VotianLT - Willkommen")
@AnonymousAllowed
public class StartView extends VerticalLayout implements BeforeEnterObserver {

    private final SecurityService securityService;
    private final String appVersion;

    public StartView(SecurityService securityService, @Value("${app.version:unknown}") String appVersion) {
        this.securityService = securityService;
        this.appVersion = appVersion;
        setSizeFull();
        setPadding(false);
        setSpacing(false);
        setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.STRETCH);

        // Header mit Navigation
        add(createHeader());

        // Hero Section
        add(createHeroSection());

        // System Section
        add(createSystemSection());

        // App Section
        add(createAppSection());

        // Footer
        add(createFooter());
    }

    @Override
    public void beforeEnter(BeforeEnterEvent event) {
        // Redirect authenticated users to dashboard
        if (securityService.isUserLoggedIn()) {
            event.forwardTo("dashboard");
        }
    }

    private Component createHeader() {
        HorizontalLayout header = new HorizontalLayout();
        header.setWidthFull();
        header.setPadding(true);
        header.setSpacing(true);
        header.setDefaultVerticalComponentAlignment(FlexComponent.Alignment.CENTER);
        header.setJustifyContentMode(FlexComponent.JustifyContentMode.BETWEEN);
        header.getStyle().set("background-color", "var(--lumo-contrast-5pct)");
        header.getStyle().set("border-bottom", "1px solid var(--lumo-contrast-10pct)");

        // Logo
        H1 logo = new H1("votian LT");
        logo.getStyle().set("color", "var(--lumo-primary-color)");
        logo.getStyle().set("margin", "0");
        logo.getStyle().set("font-weight", "bold");

        // Navigation - abhängig vom Anmeldestatus
        Component navigation = securityService.isUserLoggedIn() ? createAuthenticatedNavigation()
                : createAnonymousNavigation();

        header.add(logo, navigation);

        return header;
    }

    private Component createAnonymousNavigation() {
        HorizontalLayout navButtons = new HorizontalLayout();
        navButtons.setSpacing(true);
        navButtons.setDefaultVerticalComponentAlignment(FlexComponent.Alignment.CENTER);

        Button loginBtn = new Button("Anmelden", event -> login());
        loginBtn.addThemeVariants(ButtonVariant.LUMO_CONTRAST);

        Button registerBtn = new Button("Registrieren", event -> register());
        registerBtn.addThemeVariants(ButtonVariant.LUMO_PRIMARY);

        navButtons.add(loginBtn, registerBtn);
        return navButtons;
    }

    private Component createAuthenticatedNavigation() {
        HorizontalLayout navLayout = new HorizontalLayout();
        navLayout.setSpacing(true);
        navLayout.setDefaultVerticalComponentAlignment(FlexComponent.Alignment.CENTER);

        // Auftragserstellung Button
        Button createOrderBtn = new Button("Auftragserstellung", event -> UI.getCurrent().navigate("add_job"));
        createOrderBtn.addThemeVariants(ButtonVariant.LUMO_PRIMARY);

        // Verwaltung ComboBox
        ComboBox<String> managementCombo = new ComboBox<>();
        managementCombo.setPlaceholder("Verwaltung");
        managementCombo.setItems("Kunden", "Aufträge", "Firmen");
        managementCombo.addValueChangeListener(event -> {
            String value = event.getValue();
            if (value != null) {
                switch (value) {
                case "Kunden":
                    UI.getCurrent().navigate("customer");
                    break;
                case "Aufträge":
                    UI.getCurrent().navigate("orders");
                    break;
                case "Firmen":
                    UI.getCurrent().navigate("add_company");
                    break;
                }
                managementCombo.clear(); // Reset selection
            }
        });

        // Benutzer ComboBox
        String currentUser = securityService.getCurrentUsername();
        ComboBox<String> userCombo = new ComboBox<>();
        userCombo.setPlaceholder(currentUser);
        userCombo.setItems("Profil anzeigen", "Einstellungen", "Abmelden");
        userCombo.addValueChangeListener(event -> {
            String value = event.getValue();
            if (value != null) {
                switch (value) {
                case "Profil anzeigen":
                    break;
                case "Einstellungen":
                    break;
                case "Abmelden":
                    securityService.logout();
                    break;
                }
                userCombo.clear(); // Reset selection
            }
        });

        // Benachrichtigungs-Icon
        Button notificationBtn = new Button();
        notificationBtn.setIcon(VaadinIcon.BELL.create());
        notificationBtn.addThemeVariants(ButtonVariant.LUMO_ICON, ButtonVariant.LUMO_TERTIARY);
        notificationBtn.setTooltipText("Benachrichtigungen");
        notificationBtn.addClickListener(event -> {
            com.vaadin.flow.component.notification.Notification.show("Keine neuen Benachrichtigungen", 3000,
                    com.vaadin.flow.component.notification.Notification.Position.TOP_END);
        });

        navLayout.add(createOrderBtn, managementCombo, userCombo, notificationBtn);
        return navLayout;
    }

    private Component createHeroSection() {
        VerticalLayout heroSection = new VerticalLayout();
        heroSection.setWidthFull();
        heroSection.setPadding(true);
        heroSection.setSpacing(true);
        heroSection.setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.CENTER);
        heroSection.getStyle().set("background",
                "linear-gradient(135deg, var(--lumo-primary-color-10pct), var(--lumo-primary-color-50pct))");
        heroSection.getStyle().set("min-height", "400px");
        heroSection.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER);

        // Hero Image Placeholder
        Icon heroIcon = VaadinIcon.TRUCK.create();
        heroIcon.setSize("120px");
        heroIcon.getStyle().set("color", "var(--lumo-primary-color)");

        H1 heroTitle = new H1("VotianLT - Ihr digitaler Transportpartner");
        heroTitle.getStyle().set("text-align", "center");
        heroTitle.getStyle().set("color", "var(--lumo-primary-text-color)");
        heroTitle.getStyle().set("margin-bottom", "var(--lumo-space-l)");

        Paragraph heroDescription = new Paragraph("Für Solo-Selbstständige und Kleinunternehmer im Transportgewerbe - "
                + "volldigital und aus einem Guss. Konzentrieren Sie sich auf Ihr Geschäft, "
                + "wir kümmern uns um die Büroarbeit.");
        heroDescription.getStyle().set("text-align", "center");
        heroDescription.getStyle().set("max-width", "600px");
        heroDescription.getStyle().set("font-size", "var(--lumo-font-size-l)");

        Button ctaButton = new Button("Jetzt kostenlos testen", event -> register());
        ctaButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY, ButtonVariant.LUMO_LARGE);

        heroSection.add(heroIcon, heroTitle, heroDescription, ctaButton);
        return heroSection;
    }

    private Component createSystemSection() {
        VerticalLayout systemSection = new VerticalLayout();
        systemSection.setWidthFull();
        systemSection.setPadding(true);
        systemSection.setSpacing(true);
        systemSection.setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.CENTER);
        systemSection.getStyle().set("background-color", "var(--lumo-base-color)");

        // Section Header
        H2 systemTitle = new H2("Das System");
        systemTitle.getStyle().set("color", "var(--lumo-primary-color)");
        systemTitle.getStyle().set("text-align", "center");

        Paragraph systemIntro = new Paragraph(
                "Für Solo-Selbstständige und Kleinunternehmer im Transportgewerbe ist von entscheidender Bedeutung, "
                        + "dass sie sich in erster Linie auf ihr eigentliches Geschäft konzentrieren können: Kunden gewinnen und Waren von A nach B liefern.");
        systemIntro.getStyle().set("text-align", "center");
        systemIntro.getStyle().set("max-width", "800px");
        systemIntro.getStyle().set("margin-bottom", "var(--lumo-space-xl)");

        // Features Grid
        HorizontalLayout featuresGrid = new HorizontalLayout();
        featuresGrid.setWidthFull();
        featuresGrid.setSpacing(true);
        featuresGrid.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER);
        featuresGrid.setDefaultVerticalComponentAlignment(FlexComponent.Alignment.STRETCH);

        // Feature Cards
        featuresGrid.add(createFeatureCard(VaadinIcon.COG, "Einrichtungsassistent",
                "Mithilfe des Einrichtungsassistenten haben Sie die Möglichkeit, Ihr Nutzerprofil zu vervollständigen."),
                createFeatureCard(VaadinIcon.USERS, "Kunden- und Auftragsverwaltung",
                        "Mit der Kunden- und Auftragsverwaltung haben Sie alle Kontaktdaten und Auftragsdetails stets im Blick."),
                createFeatureCard(VaadinIcon.CLIPBOARD_TEXT, "Auftragserstellung",
                        "Stellen Sie mit wenigen Mausklicks Aufträge ins System ein und legen Sie fest, welcher Mitarbeiter welchen Transportauftrag abarbeiten soll."));

        systemSection.add(systemTitle, systemIntro, featuresGrid);
        return systemSection;
    }

    private Component createFeatureCard(VaadinIcon iconType, String title, String description) {
        VerticalLayout card = new VerticalLayout();
        card.setSpacing(true);
        card.setPadding(true);
        card.setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.CENTER);
        card.getStyle().set("border", "1px solid var(--lumo-contrast-20pct)");
        card.getStyle().set("border-radius", "var(--lumo-border-radius-m)");
        card.getStyle().set("background-color", "var(--lumo-base-color)");
        card.getStyle().set("box-shadow", "var(--lumo-box-shadow-xs)");
        card.setWidth("300px");
        card.setHeightFull();

        Icon icon = iconType.create();
        icon.setSize("48px");
        icon.getStyle().set("color", "var(--lumo-primary-color)");

        H3 cardTitle = new H3(title);
        cardTitle.getStyle().set("text-align", "center");
        cardTitle.getStyle().set("margin", "var(--lumo-space-s) 0");

        Paragraph cardDescription = new Paragraph(description);
        cardDescription.getStyle().set("text-align", "center");
        cardDescription.getStyle().set("font-size", "var(--lumo-font-size-s)");

        card.add(icon, cardTitle, cardDescription);
        return card;
    }

    private Component createAppSection() {
        VerticalLayout appSection = new VerticalLayout();
        appSection.setWidthFull();
        appSection.setPadding(true);
        appSection.setSpacing(true);
        appSection.setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.CENTER);
        appSection.getStyle().set("background-color", "var(--lumo-contrast-5pct)");

        H2 appTitle = new H2("Die App");
        appTitle.getStyle().set("color", "var(--lumo-primary-color)");
        appTitle.getStyle().set("text-align", "center");

        Paragraph appDescription = new Paragraph(
                "Jeder Auftrag kann optional über die votianLT-App abgearbeitet werden – ganz ohne \"Zettelwirtschaft\". "
                        + "So gelangen alle relevanten Auftragsinformationen direkt auf das Smartphone des Fahrers.");
        appDescription.getStyle().set("text-align", "center");
        appDescription.getStyle().set("max-width", "800px");

        Icon appIcon = VaadinIcon.MOBILE.create();
        appIcon.setSize("80px");
        appIcon.getStyle().set("color", "var(--lumo-primary-color)");

        appSection.add(appTitle, appDescription, appIcon);
        return appSection;
    }

    private Component createFooter() {
        VerticalLayout footer = new VerticalLayout();
        footer.setWidthFull();
        footer.setPadding(true);
        footer.setSpacing(true);
        footer.setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.CENTER);
        footer.getStyle().set("background-color", "var(--lumo-contrast-10pct)");
        footer.getStyle().set("border-top", "1px solid var(--lumo-contrast-20pct)");

        // Company Info
        H3 companyTitle = new H3("Impressum");
        companyTitle.getStyle().set("color", "var(--lumo-primary-color)");
        companyTitle.getStyle().set("text-align", "center");

        VerticalLayout companyInfo = new VerticalLayout();
        companyInfo.setSpacing(false);
        companyInfo.setPadding(false);
        companyInfo.setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.CENTER);

        companyInfo.add(new Paragraph("Assecutor Data Service GmbH"), new Paragraph("Ottensener Str. 8, 22525 Hamburg"),
                new Paragraph("Telefon: +49 40 18 123 771 0"), new Paragraph("E-Mail: ahoi@assecutor.de"));

        // Call to Action
        Paragraph ctaText = new Paragraph("Registrieren Sie sich noch heute und nutzen den kostenfreien Probemonat, "
                + "um das System auf Herz und Nieren zu testen.");
        ctaText.getStyle().set("text-align", "center");
        ctaText.getStyle().set("font-weight", "bold");
        ctaText.getStyle().set("color", "var(--lumo-primary-color)");
        ctaText.getStyle().set("margin-top", "var(--lumo-space-l)");

        Paragraph slogan = new Paragraph("Betreiben Sie Ihr Geschäft smart … mit votianLT!");
        slogan.getStyle().set("text-align", "center");
        slogan.getStyle().set("font-style", "italic");
        slogan.getStyle().set("color", "var(--lumo-primary-color)");

        // Versionsnummer
        Span versionSpan = new Span("Version " + appVersion);
        versionSpan.getStyle().set("color", "var(--lumo-secondary-text-color)")
                .set("font-size", "var(--lumo-font-size-s)").set("margin-top", "var(--lumo-space-l)");

        footer.add(companyTitle, companyInfo, ctaText, slogan, versionSpan);
        return footer;
    }

    private void register() {
        UI.getCurrent().navigate("register");
    }

    private void login() {
        UI.getCurrent().navigate("login");
    }
}
