use leptos::prelude::*;
use leptos_router::components::A;
use leptos_router::hooks::use_location;
use crate::auth::use_auth;
use crate::components::prelude::*;
use gloo_timers::future::TimeoutFuture;
use web_sys::Window;

fn scroll_to_prices(window: Option<Window>) {
    if let Some(window) = window {
        log::debug!("scroll_to_prices: window found");
        if let Some(el) = window.document().and_then(|d| d.get_element_by_id("prices")) {
            log::debug!("scroll_to_prices: element found, scrolling to prices");
            el.scroll_into_view_with_bool(true);
        }
    }
}

#[component]
fn NavLink(
    href: impl Fn() -> Memo<String> + 'static + Send + Sync,
    children: Children,
    #[prop(optional)] class: Option<&'static str>,
    #[prop(optional)] on_click: Option<Callback<()>>,
) -> impl IntoView {
    let location = use_location();
    let href_memo = href();
    
    let base_classes = "no-underline transition-all duration-300 font-medium py-2 px-4 rounded-full border-transparent cursor-pointer";
    
    view! {
        <A 
            href=move || href_memo.get()
            attr:class=move || {
                let current_path = location.pathname.get();
                let current_href = href_memo.get();
                let is_active = if current_href == t8s!("/en") {
                    current_path == t8s!("/en") || current_path == "/"
                } else {
                    log::info!("current_path {}, {}", current_path, current_href);
                    current_path.starts_with(&current_href)
                };
                
                let active_classes = if is_active {
                    "bg-white text-black font-semibold"
                } else {
                    "bg-transparent text-text-secondary hover:text-text-white hover:border-border-primary hover:bg-nav-hover-bg"
                };
                
                let final_classes = format!("{} {}", base_classes, active_classes);
                match class {
                    Some(c) => format!("{} {}", final_classes, c),
                    None => final_classes,
                }
            }
            on:click=move |_| if let Some(cb) = on_click.as_ref() { cb.run(()) }
            attr:id=move || format!("nav-link-{}", href_memo.get().replace("/", "").replace("-", "_"))
        >
            <span class="block">
                {children()}
            </span>
        </A>
    }
}

#[component]
fn LanguageSwitcher(
    #[prop(optional)] compact: bool,
) -> impl IntoView {
    let location = use_location();
    let text_size = if compact { "text-xs" } else { "text-sm" };
    let padding = if compact { "py-1 px-2" } else { "py-3 px-4" };
    
    // Get current path and create language-specific URLs
    let current_path = move || location.pathname.get();
    let en_url = move || {
        let path = current_path();
        log::debug!("LanguageSwitcher: generating EN URL for path: '{}'", path);
        if path.starts_with("/ru") {
            let new_path = format!("/en{}", path.strip_prefix("/ru").unwrap_or(""));
            log::debug!("LanguageSwitcher: switching from RU to EN: '{}' -> '{}'", path, new_path);
            new_path
        } else if path.starts_with("/en") {
            log::debug!("LanguageSwitcher: already EN, keeping: '{}'", path);
            path.to_string()
        } else {
            let new_path = format!("/en{}", path);
            log::debug!("LanguageSwitcher: default to EN: '{}' -> '{}'", path, new_path);
            new_path
        }
    };
    let ru_url = move || {
        let path = current_path();
        log::debug!("LanguageSwitcher: generating RU URL for path: '{}'", path);
        if path.starts_with("/en") {
            let new_path = format!("/ru{}", path.strip_prefix("/en").unwrap_or(""));
            log::debug!("LanguageSwitcher: switching from EN to RU: '{}' -> '{}'", path, new_path);
            new_path
        } else if path.starts_with("/ru") {
            log::debug!("LanguageSwitcher: already RU, keeping: '{}'", path);
            path.to_string()
        } else {
            let new_path = format!("/ru{}", path);
            log::debug!("LanguageSwitcher: default to RU: '{}' -> '{}'", path, new_path);
            new_path
        }
    };
    
    // Check if current language is active
    let is_en_active = move || {
        let path = current_path();
        path.starts_with("/en") || (!path.starts_with("/ru") && !path.starts_with("/en"))
    };
    let is_ru_active = move || current_path().starts_with("/ru");
    
    view! {
        <div class=format!("flex items-center gap-1 text-text-secondary {text_size} font-medium transition-colors duration-300 {padding} rounded-md hover:text-text-white") id="language-switcher">
            <A 
                href=move || en_url()
                attr:class=move || format!("cursor-pointer transition-colors duration-300 hover:text-accent-primary no-underline {}", 
                    if is_en_active() { "text-text-white font-bold" } else { "" }
                )
                attr:id="lang-en-button"
            >
                "EN"
            </A>
            <span class="font-normal" id="lang-separator">"/"</span>
            <A 
                href=move || ru_url()
                attr:class=move || format!("cursor-pointer transition-colors duration-300 hover:text-accent-primary no-underline {}", 
                    if is_ru_active() { "text-text-white font-bold" } else { "" }
                )
                attr:id="lang-ru-button"
            >
                "RU"
            </A>
        </div>
    }
}

#[component]
fn NotificationButton(
    #[prop(optional)] compact: bool,
    #[prop(optional)] show_text: bool,
) -> impl IntoView {
    let padding = if compact { "p-3" } else { "p-2" };
    let _text_size = if compact { "text-sm" } else { "text-base" };
    
    let (show_dropdown, set_show_dropdown) = signal(false);
    
    view! {
        <div class="relative" id="notification-container">
            <button 
                class=format!("bg-none border-none text-text-secondary cursor-pointer {} rounded-md transition-all duration-300 flex items-center justify-center hover:text-text-white hover:bg-nav-hover-bg {}", padding, if !compact { "hover:scale-110" } else { "" })
                title="Notifications"
                id="notification-button"
                on:click=move |_| set_show_dropdown.update(|show| *show = !*show)
            >
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class=if show_text { "mr-2" } else { "" } id="notification-icon">
                    <path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/>
                    <path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/>
                </svg>
                {if show_text { t8r!("Notifications") } else { move || create_memo(|_| "".to_string()) }}
            </button>
            
            {move || if show_dropdown.get() {
                view! {
                    <div 
                        class="absolute right-0 mt-2 w-80 bg-[#2d2c2c] border border-[var(--main-light-40)] rounded-lg shadow-lg z-50"
                        id="notification-dropdown"
                    >
                        <div class="p-4">
                            <div class="flex items-center justify-between mb-3">
                                <h3 class="text-lg font-semibold text-[var(--text-primary)]">
                                    {t8r!("Notifications")}
                                </h3>
                                <button 
                                    class="text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors"
                                    on:click=move |_| set_show_dropdown.set(false)
                                    id="close-notifications"
                                >
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                        <path d="M18 6L6 18"/>
                                        <path d="M6 6l12 12"/>
                                    </svg>
                                </button>
                            </div>
                            
                            <div class="flex flex-col items-center justify-center py-8 text-center">
                                <div class="w-16 h-16 bg-[var(--text-muted)] bg-opacity-10 rounded-full flex items-center justify-center mb-4">
                                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-[var(--text-muted)]">
                                        <path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/>
                                        <path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/>
                                    </svg>
                                </div>
                                <p class="text-[var(--text-muted)] text-sm">
                                    {t8r!("You have no notifications now")}
                                </p>
                            </div>
                        </div>
                    </div>
                }.into_any()
            } else {
                view! {}.into_any()
            }}
        </div>
    }
}

#[component]
fn LoginButton(
    #[prop(optional)] compact: bool,
    #[prop(optional)] extra_compact: bool,
    #[prop(optional)] on_click: Option<Callback<()>>,
) -> impl IntoView {
    let auth = use_auth();
    let padding = if extra_compact { "py-1.5 px-3" } else if compact { "py-2 px-4" } else { "py-3 px-6" };
    let text_size = if extra_compact { "text-xs" } else if compact { "text-xs" } else { "text-sm" };

    view! {
        {move || {
            if auth.is_authenticated.get() {
                view! {
                    <div class="flex items-center gap-2" id="authenticated-user-controls">
                        <a
                            href=t8r!("/en/profile")().get()
                            class="flex flex-row justify-between items-center p-2 gap-2 w-[179px] h-[38px] bg-[var(--other-light-5)] rounded-full transition-all duration-300 border-none cursor-pointer hover:bg-[var(--other-light-20)] no-underline"
                            id="profile-button"
                        >
                            <img 
                                src="/icons/profile-default.svg" 
                                alt="Profile Avatar" 
                                class="w-[22px] h-[22px] flex-none"
                                id="profile-icon"
                            />
                            
                            <span class="flex-1 font-semibold text-base leading-[22px] tracking-tight text-[var(--main-light)] text-center" id="profile-username">
                                {t8r!("Profile")}
                            </span>
                            
                            <div class="relative w-[22px] h-full flex-none" id="profile-arrow-container">
                                <svg class="absolute w-full h-full fill-[var(--main-light-40)] transform -rotate-90" viewBox="0 0 20 20" id="profile-arrow">
                                    <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd"/>
                                </svg>
                            </div>
                        </a>
                    </div>
                }.into_any()
            } else {
                let base_classes = format!("[background:var(--accent-primary-gradient)] text-text-white {padding} rounded-full no-underline font-semibold {text_size} transition-all duration-300 border-none cursor-pointer hover:bg-auth-button-hover");
                let classes = if compact || extra_compact { base_classes } else { format!("{} hover:-translate-y-0.5 hover:shadow-[0_4px_15px_var(--auth-button-shadow)]", base_classes) };
                
                view! {
                    <A 
                        href=t8r!("/en/login")().get()
                        attr:class=classes
                        on:click=move |_| if let Some(cb) = on_click.as_ref() { cb.run(()) }
                        attr:id="login-button"
                    >
                        {t8r!("Sign in/Sign up")}
                    </A>
                }.into_any()
            }
        }}
    }
}

#[component]
fn DesktopNavigation() -> impl IntoView {
    view! {
        <nav class="hidden lg:flex gap-10 mx-auto" id="desktop-navigation">
            <NavLink href=t8r!("/en/prices") on_click=Callback::from(move || {
                #[cfg(target_arch = "wasm32")]
                wasm_bindgen_futures::spawn_local(async move {
                    TimeoutFuture::new(0).await;
                    scroll_to_prices(web_sys::window());
                });
            })>
                {t8r!("Prices")}
            </NavLink>
            <NavLink href=t8r!("/en/proxy")>
                {t8r!("Proxy-Online")}
            </NavLink>
            <NavLink href=t8r!("/en/shares")>
                {t8r!("Promotions")}
            </NavLink>
            <NavLink href=t8r!("/en/reviews")>
                {t8r!("Reviews")}
            </NavLink>
            <NavLink href=t8r!("/en/blog")>
                {t8r!("Blog")}
            </NavLink>
        </nav>
    }
}

#[component]
fn TabletNavigation() -> impl IntoView {
    view! {
        <nav class="hidden md:flex lg:hidden gap-3 mx-auto" id="tablet-navigation">
            <NavLink href=t8r!("/en/prices") class="text-xs py-1.5 px-2" on_click=Callback::from(move || {
                #[cfg(target_arch = "wasm32")]
                wasm_bindgen_futures::spawn_local(async move {
                    TimeoutFuture::new(0).await;
                    scroll_to_prices(web_sys::window());
                });
            })>
                {t8r!("Prices")}
            </NavLink>
            <NavLink href=t8r!("/en/proxy") class="text-xs py-1.5 px-2">
                {t8r!("Online")}
            </NavLink>
            <NavLink href=t8r!("/en/shares") class="text-xs py-1.5 px-2">
                {t8r!("Promotions")}
            </NavLink>
            <NavLink href=t8r!("/en/reviews") class="text-xs py-1.5 px-2">
                {t8r!("Reviews")}
            </NavLink>
            <NavLink href=t8r!("/en/blog") class="text-xs py-1.5 px-2">
                {t8r!("Blog")}
            </NavLink>
        </nav>
    }
}

#[component]
fn DesktopUserControls() -> impl IntoView {
    view! {
        <div class="hidden lg:flex items-center gap-5" id="desktop-user-controls">
            <LanguageSwitcher />
            <NotificationButton />
            <LoginButton />
        </div>
    }
}

#[component]
fn TabletUserControls() -> impl IntoView {
    view! {
        <div class="hidden md:flex lg:hidden items-center gap-2" id="tablet-user-controls">
            <LanguageSwitcher compact=true />
            <LoginButton extra_compact=true />
        </div>
    }
}

#[component]
fn MobileMenuButton(
    is_open: ReadSignal<bool>,
    on_toggle: Callback<()>,
) -> impl IntoView {
    view! {
        <button 
            class="md:hidden bg-none border-none text-text-secondary cursor-pointer p-2 rounded-md transition-all duration-300 flex items-center justify-center hover:text-text-white hover:bg-nav-hover-bg"
            id="mobile-menu-toggle"
            on:click=move |_| on_toggle.run(())
            title="Menu"
        >
            <svg 
                width="24" 
                height="24" 
                viewBox="0 0 24 24" 
                fill="none" 
                stroke="currentColor" 
                stroke-width="2" 
                stroke-linecap="round" 
                stroke-linejoin="round"
                class=move || if is_open.get() { "hidden" } else { "" }
                id="hamburger-icon"
            >
                <line x1="3" y1="6" x2="21" y2="6"/>
                <line x1="3" y1="12" x2="21" y2="12"/>
                <line x1="3" y1="18" x2="21" y2="18"/>
            </svg>
            <svg 
                width="24" 
                height="24" 
                viewBox="0 0 24 24" 
                fill="none" 
                stroke="currentColor" 
                stroke-width="2" 
                stroke-linecap="round" 
                stroke-linejoin="round"
                class=move || if is_open.get() { "" } else { "hidden" }
                id="close-icon"
            >
                <line x1="18" y1="6" x2="6" y2="18"/>
                <line x1="6" y1="6" x2="18" y2="18"/>
            </svg>
        </button>
    }
}

#[component]
fn MobileNavigationOverlay(
    is_open: ReadSignal<bool>,
    on_close: Callback<()>,
) -> impl IntoView {
    
    view! {
        <div 
            class=move || format!("fixed inset-0 bg-black bg-opacity-50 z-50 transition-opacity duration-300 {}", 
                if is_open.get() { "opacity-100 pointer-events-auto" } else { "opacity-0 pointer-events-none" }
            )
            id="mobile-menu-overlay"
            on:click=move |_| on_close.run(())
        >
            <div 
                class=move || if is_open.get() { "open" } else { "closed" }
                id="mobile-menu-panel"
                on:click=move |ev| ev.stop_propagation()
            >
                <div class="p-6" id="mobile-menu-content">
                    // <div class="flex items-center justify-between mb-8" id="mobile-menu-header">
                    //     <h2 class="text-xl font-semibold text-text-white" id="mobile-menu-title">{t8r!("Menu")}</h2>
                    //     <button 
                    //         class="bg-none border-none text-text-secondary cursor-pointer p-2 rounded-md transition-all duration-300 hover:text-text-white hover:bg-nav-hover-bg"
                    //         on:click=move |_| on_close.run(())
                    //         id="mobile-menu-close-btn"
                    //     >
                    //         <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" id="mobile-close-icon">
                    //             <line x1="18" y1="6" x2="6" y2="18"/>
                    //             <line x1="6" y1="6" x2="18" y2="18"/>
                    //         </svg>
                    //     </button>
                    // </div>

                    <div id="mobile-language-section">
                        <LanguageSwitcher />
                    </div>

                    <nav class="flex flex-col gap-4 mb-8" on:click=move |_| on_close.run(()) id="mobile-navigation-links">
                        <NavLink href=t8r!("/en/prices") class="py-3 px-4 block" on_click=Callback::from(move || {
                            #[cfg(target_arch = "wasm32")]
                            wasm_bindgen_futures::spawn_local(async move {
                                TimeoutFuture::new(0).await;
                                scroll_to_prices(web_sys::window());
                            });
                        })>
                            {t8r!("Prices")}
                        </NavLink>
                        <NavLink href=t8r!("/en/proxy") class="py-3 px-4 block">
                            {t8r!("Proxy-Online")}
                        </NavLink>
                        <NavLink href=t8r!("/en/shares") class="py-3 px-4 block">
                            {t8r!("Promotions")}
                        </NavLink>
                        <NavLink href=t8r!("/en/reviews") class="py-3 px-4 block">
                            {t8r!("Reviews")}
                        </NavLink>
                        <NavLink href=t8r!("/en/blog") class="py-3 px-4 block">
                            {t8r!("Blog")}
                        </NavLink>
                    </nav>

                    <div class="flex flex-col gap-4" id="mobile-user-controls">
                        <NotificationButton compact=true show_text=true />
                    </div>
                    <LoginButton compact=true />
                </div>
            </div>
        </div>
    }
}

#[component]
pub fn Header() -> impl IntoView {
    let (is_mobile_menu_open, set_is_mobile_menu_open) = signal(false);
    
    let toggle_mobile_menu = Callback::new(move |_| {
        set_is_mobile_menu_open.update(|is_open| *is_open = !*is_open);
    });
    
    let close_mobile_menu = Callback::new(move |_| {
        set_is_mobile_menu_open.set(false);
    });
    
    view! {
        <header class=move || if is_mobile_menu_open.get() { "fixed" } else { "" } 
                id="main-header">
            <A href=t8s!("/en") attr:class="font-semibold text-2xl text-text-secondary no-underline transition-colors duration-300 hover:text-text-white" attr:id="logo-link">
                "VProxy"
            </A>

            <DesktopNavigation />

            <TabletNavigation />

            <div class="flex gap-5 items-center" id="user-controls-section">
                <DesktopUserControls />
                <TabletUserControls />
                <MobileMenuButton 
                    is_open=is_mobile_menu_open 
                    on_toggle=toggle_mobile_menu 
                />
            </div>
        </header>

        <MobileNavigationOverlay 
            is_open=is_mobile_menu_open 
            on_close=close_mobile_menu 
        />
    }
}

