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.contextmenu.ContextMenu;
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.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
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.HasDynamicTitle;
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.model.Language;
import de.assecutor.votianlt.pages.base.ui.component.DialogStylingHelper;
import de.assecutor.votianlt.security.SessionAuthenticationService;
import de.assecutor.votianlt.security.SecurityService;
import de.assecutor.votianlt.service.DemoModeService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

import java.util.Locale;

@Route("")
@AnonymousAllowed
public class StartView extends VerticalLayout implements BeforeEnterObserver, HasDynamicTitle {

    private final SecurityService securityService;
    private final DemoModeService demoModeService;
    private final SessionAuthenticationService sessionAuthenticationService;
    private final AuthenticationManager authenticationManager;
    private final String appVersion;

    public StartView(SecurityService securityService, DemoModeService demoModeService,
            SessionAuthenticationService sessionAuthenticationService, AuthenticationManager authenticationManager,
            @Value("${app.version:unknown}") String appVersion) {
        this.securityService = securityService;
        this.demoModeService = demoModeService;
        this.sessionAuthenticationService = sessionAuthenticationService;
        this.authenticationManager = authenticationManager;
        this.appVersion = appVersion;
        addClassName("landing-view");
        setSizeFull();
        setPadding(false);
        setSpacing(true);
        setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.STRETCH);

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

        // Hero Section
        add(createHeroSection());

        // System Section
        add(createSystemSection());

        // App Section
        add(createAppSection());

        // Footer
        add(createFooter());

        // Unterer Abstand
        Div bottomSpacer = new Div();
        bottomSpacer.setHeight("20px");
        bottomSpacer.setMinHeight("20px");
        add(bottomSpacer);
    }

    @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.addClassNames("page-shell", "surface-panel", "landing-header");

        // Logo
        H1 logo = new H1("votian LT");
        logo.addClassName("landing-logo");

        // 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);
        navButtons.addClassName("landing-nav");

        Button loginBtn = new Button(getTranslation("start.button.login"), event -> login());
        loginBtn.addThemeVariants(ButtonVariant.LUMO_CONTRAST);
        loginBtn.addClassName("landing-nav-button");

        Button registerBtn = new Button(getTranslation("start.button.register"), event -> register());
        registerBtn.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        registerBtn.addClassName("landing-nav-button");

        // Sprachauswahl Button

        Button languageBtn = createLanguageSelector();

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

    private Button createLanguageSelector() {
        // Aktuelle Sprache aus der UI-Locale ermitteln (wird vom
        // LocaleVaadinInitListener gesetzt)
        String currentLang = getCurrentLanguageFromLocale();
        String flag = getFlagForLanguage(currentLang);

        Button languageBtn = new Button(flag + " " + currentLang);
        languageBtn.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
        languageBtn.addClassName("landing-language-button");

        ContextMenu languageMenu = new ContextMenu();
        languageMenu.setOpenOnClick(true);
        languageMenu.setTarget(languageBtn);

        // Alle Sprachen hinzufügen
        for (Language lang : Language.values()) {
            String langFlag = getFlagForLanguage(lang.name());
            String langText = langFlag + " " + lang.getDisplayName();

            languageMenu.addItem(langText, event -> {
                setLanguageCookie(lang.name());
                // Seite neu laden um die neue Sprache anzuwenden
                UI.getCurrent().getPage().reload();
            });
        }

        return languageBtn;
    }

    private String getCurrentLanguageFromLocale() {
        // Aktuelle UI-Locale verwenden (wird vom LocaleVaadinInitListener aus
        // Cookie/Browser gesetzt)
        Locale locale = UI.getCurrent().getLocale();
        if (locale == null) {
            return "DE";
        }

        String language = locale.getLanguage();
        return switch (language) {
        case "en" -> "EN";
        case "fr" -> "FR";
        case "es" -> "ES";
        case "tr" -> "TR";
        case "pl" -> "PL";
        case "ru" -> "RU";
        case "et" -> "EE"; // Estnisch
        case "lv" -> "LV"; // Lettisch
        case "lt" -> "LT"; // Litauisch
        default -> "DE"; // German as default
        };
    }

    private String getFlagForLanguage(String languageCode) {
        if (languageCode == null) {
            return "🇩🇪";
        }
        return switch (languageCode.toUpperCase()) {
        case "DE" -> "🇩🇪";
        case "EN" -> "🇬🇧";
        case "FR" -> "🇫🇷";
        case "ES" -> "🇪🇸";
        case "TR" -> "🇹🇷";
        case "PL" -> "🇵🇱";
        case "RU" -> "🇷🇺";
        case "EE" -> "🇪🇪";
        case "LV" -> "🇱🇻";
        case "LT" -> "🇱🇹";
        default -> "🇩🇪";
        };
    }

    private void setLanguageCookie(String languageCode) {
        UI.getCurrent().getPage().executeJs("const maxAge = 365 * 24 * 60 * 60;"
                + "document.cookie = 'votianlt.language=' + $0 + ';path=/;max-age=' + maxAge + ';SameSite=Lax';",
                languageCode);
    }

    private Component createAuthenticatedNavigation() {
        HorizontalLayout navLayout = new HorizontalLayout();
        navLayout.setSpacing(true);
        navLayout.setDefaultVerticalComponentAlignment(FlexComponent.Alignment.CENTER);
        navLayout.addClassName("landing-nav");

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

        // 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", "Abmelden");
        userCombo.addValueChangeListener(event -> {
            String value = event.getValue();
            if (value != null) {
                switch (value) {
                case "Profil anzeigen":
                    break;
                case "Abmelden":
                    openLogoutConfirmDialog();
                    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.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER);
        heroSection.addClassNames("page-shell", "hero-panel", "landing-hero");

        // Hero Image Placeholder
        Icon heroIcon = VaadinIcon.TRUCK.create();
        heroIcon.setSize("120px");
        heroIcon.addClassName("hero-panel-icon");

        H1 heroTitle = new H1(getTranslation("start.title"));
        heroTitle.addClassName("hero-panel-title");

        Paragraph heroDescription = new Paragraph(getTranslation("start.hero.description"));
        heroDescription.addClassName("hero-panel-text");

        Button demoButton = new Button(getTranslation("start.button.demo"), event -> loginDemo());
        demoButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY, ButtonVariant.LUMO_LARGE);
        demoButton.addClassNames("hero-cta", "hero-demo-cta");
        demoButton.setWidthFull();

        Button ctaButton = new Button(getTranslation("cta.freetest"), event -> register());
        ctaButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY, ButtonVariant.LUMO_LARGE);
        ctaButton.addClassName("hero-cta");
        ctaButton.setWidthFull();

        Paragraph demoHint = new Paragraph(getTranslation("start.hero.demo.hint"));
        demoHint.addClassName("hero-choice-hint");

        Paragraph trialHint = new Paragraph(getTranslation("start.hero.trial.hint"));
        trialHint.addClassName("hero-choice-hint");

        VerticalLayout demoAction = new VerticalLayout();
        demoAction.setPadding(false);
        demoAction.setSpacing(false);
        demoAction.setWidthFull();
        demoAction.setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.CENTER);
        demoAction.addClassName("hero-action-group");
        demoAction.add(demoButton, demoHint);

        VerticalLayout trialAction = new VerticalLayout();
        trialAction.setPadding(false);
        trialAction.setSpacing(false);
        trialAction.setWidthFull();
        trialAction.setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.CENTER);
        trialAction.addClassName("hero-action-group");
        trialAction.add(ctaButton, trialHint);

        VerticalLayout heroActions = new VerticalLayout();
        heroActions.setPadding(false);
        heroActions.setSpacing(false);
        heroActions.setWidthFull();
        heroActions.setMaxWidth("420px");
        heroActions.setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.CENTER);
        heroActions.addClassName("hero-actions");
        heroActions.add(demoAction, trialAction);

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

    private Component createSystemSection() {
        VerticalLayout systemSection = new VerticalLayout();
        systemSection.setWidthFull();
        systemSection.setPadding(true);
        systemSection.setSpacing(true);
        systemSection.setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.CENTER);
        systemSection.addClassNames("page-shell", "surface-panel", "section-panel");

        // Section Header
        H2 systemTitle = new H2(getTranslation("start.system.title"));
        systemTitle.addClassName("section-title");

        Paragraph systemIntro = new Paragraph(getTranslation("start.system.intro"));
        systemIntro.addClassName("section-intro");

        // Features Grid
        Div featuresGrid = new Div();
        featuresGrid.addClassName("tile-grid");

        // Feature Cards
        featuresGrid.add(
                createFeatureCard(VaadinIcon.COG, getTranslation("start.feature.setup.title"),
                        getTranslation("start.feature.setup.desc")),
                createFeatureCard(VaadinIcon.USERS, getTranslation("start.feature.customers.title"),
                        getTranslation("start.feature.customers.desc")),
                createFeatureCard(VaadinIcon.CLIPBOARD_TEXT, getTranslation("start.feature.jobs.title"),
                        getTranslation("start.feature.jobs.desc")));

        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.setWidthFull();
        card.addClassName("feature-card");

        Icon icon = iconType.create();
        icon.setSize("48px");
        icon.addClassName("feature-card-icon");

        H3 cardTitle = new H3(title);
        cardTitle.addClassName("feature-card-title");

        Paragraph cardDescription = new Paragraph(description);
        cardDescription.addClassName("feature-card-description");

        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.addClassNames("page-shell", "surface-panel", "app-overview-panel");

        H2 appTitle = new H2(getTranslation("start.app.title"));
        appTitle.addClassName("section-title");

        Paragraph appDescription = new Paragraph(getTranslation("start.app.description"));
        appDescription.addClassName("section-intro");

        Icon appIcon = VaadinIcon.MOBILE.create();
        appIcon.setSize("80px");
        appIcon.addClassName("feature-card-icon");

        Paragraph ctaText = new Paragraph(getTranslation("start.cta.text"));
        ctaText.addClassName("app-cta");

        Paragraph slogan = new Paragraph(getTranslation("start.slogan"));
        slogan.addClassName("app-slogan");

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

    private Component createFooter() {
        VerticalLayout footer = new VerticalLayout();
        footer.setWidthFull();
        footer.setPadding(true);
        footer.setSpacing(true);
        footer.setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.CENTER);
        footer.addClassNames("page-shell", "surface-panel", "footer-panel");

        // Company Info
        H3 companyTitle = new H3(getTranslation("start.imprint.title"));
        companyTitle.addClassName("section-title");

        VerticalLayout companyInfo = new VerticalLayout();
        companyInfo.setSpacing(false);
        companyInfo.setPadding(false);
        companyInfo.setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.CENTER);
        companyInfo.addClassName("footer-details");

        companyInfo.add(new Paragraph(getTranslation("start.imprint.company")),
                new Paragraph(getTranslation("start.imprint.address")),
                new Paragraph(getTranslation("start.imprint.phone")),
                new Paragraph(getTranslation("start.imprint.email")));

        // Versionsnummer
        Span versionSpan = new Span("Version " + appVersion);
        versionSpan.addClassName("footer-version");

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

    private void openLogoutConfirmDialog() {
        var dialog = DialogStylingHelper.createConfirmationDialog(
                getTranslation("logout.confirm.title"),
                getTranslation("logout.confirm.message"),
                "460px",
                getTranslation("button.cancel"),
                getTranslation("nav.logout"),
                securityService::logout,
                ButtonVariant.LUMO_PRIMARY,
                ButtonVariant.LUMO_ERROR);
        dialog.open();
    }

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

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

    private void loginDemo() {
        String sessionId = sessionAuthenticationService.getCurrentSessionId().orElse(null);
        if (sessionId == null) {
            showDemoNotification(getTranslation("demo.start.error"), NotificationVariant.LUMO_ERROR);
            return;
        }

        boolean prepared = false;
        try {
            prepared = demoModeService.tryPrepareDemoSession(sessionId);
            if (!prepared) {
                showDemoNotification(getTranslation("demo.session.active"), NotificationVariant.LUMO_ERROR);
                return;
            }

            var auth = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(DemoModeService.DEMO_USERNAME, DemoModeService.DEMO_PASSWORD));
            sessionAuthenticationService.storeAuthentication(auth);
            UI.getCurrent().getPage().setLocation("/dashboard");
        } catch (Exception ex) {
            if (prepared) {
                demoModeService.cleanupAndReleaseIfOwned(sessionId);
            }
            showDemoNotification(getTranslation("demo.start.error"), NotificationVariant.LUMO_ERROR);
        }
    }

    private void showDemoNotification(String message, NotificationVariant variant) {
        Notification notification = Notification.show(message, 4000, Notification.Position.TOP_CENTER);
        notification.addThemeVariants(variant);
    }

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