use leptos::prelude::*;
use leptos::task::spawn_local;
use leptos_router::hooks::use_navigate;
use crate::{t8s, t8r};
use crate::api::confirm_email;
use crate::components::card::{Card, CardContainer, CardHeader, CardContent, CardVariant};
use crate::{log_component, log_user_action, log_api};

#[component]
pub fn EmailConfirmPage() -> impl IntoView {
    log_component!(created, "EmailConfirmPage");
    
    let navigate = use_navigate();
    let (loading, set_loading) = signal(true);
    let (error_message, set_error_message) = signal(None::<String>);
    let (success_message, set_success_message) = signal(None::<String>);
    
    let confirmation_token = RwSignal::new(None::<String>);
    
    create_effect(move |_| {
        #[cfg(target_arch = "wasm32")]
        {
            std::panic::catch_unwind(|| {
                if let Some(window) = web_sys::window() {
                    let location = window.location();
                    if let Ok(href) = location.href() {
                        if let Ok(url) = web_sys::Url::new(&href) {
                            let search_params = url.search_params();
                            if let Some(token) = search_params.get("confirmation_token") {
                                confirmation_token.set(Some(token));
                                return;
                            }
                        }
                    }
                }
                confirmation_token.set(None);
            }).ok();
        }
    });
    
    Effect::new(move |_| {
        if let Some(token) = confirmation_token.get() {
            if token.is_empty() {
                set_error_message.set(Some(t8s!("Invalid confirmation link").to_string()));
                set_loading.set(false);
                return;
            }

            let invalid_or_already_used_confirmation_token = t8s!("Invalid or already used confirmation token");
            let confirmation_token_expired = t8s!("Confirmation token expired");
            let user_not_found = t8s!("User not found");
            let email_confirmation_failed = t8s!("Email confirmation failed");
            let email_confirmed_successfully = t8s!("Email confirmed successfully!");
            let login_url = t8s!("/en/login");
            
            let navigate_clone = navigate.clone();
            spawn_local(async move {
                log_api!(request, "confirm_email");
                
                match confirm_email(token).await {
                    Ok(_) => {
                        log_user_action!("email_confirmation_success", "EmailConfirmPage");
                        set_success_message.set(Some(email_confirmed_successfully.to_string()));
                        
                        // Redirect to login page after 2 seconds
                        spawn_local(async move {
                            gloo_timers::future::TimeoutFuture::new(2000).await;
                            navigate_clone(login_url, Default::default());
                        });
                    }
                    Err(e) => {
                        log_api!(error, "confirm_email", &format!("Email confirmation failed: {}", e));
                        set_error_message.set(Some(match e {
                            crate::api::AuthError::Other(msg) => {
                                if msg.contains("Invalid or already used confirmation token") {
                                    invalid_or_already_used_confirmation_token.to_string()
                                } else if msg.contains("Confirmation token expired") {
                                    confirmation_token_expired.to_string()
                                } else if msg.contains("User not found") {
                                    user_not_found.to_string()
                                } else {
                                    email_confirmation_failed.to_string()
                                }
                            }
                            _ => email_confirmation_failed.to_string(),
                        }));
                    }
                }
                
                set_loading.set(false);
            });
        } else {
            let invalid_confirmation_link = t8s!("Invalid confirmation link");
            // Check if we're still waiting for token extraction
            if confirmation_token.get().is_none() {
                // Give it a moment for URL parsing
                spawn_local(async move {
                    gloo_timers::future::TimeoutFuture::new(100).await;
                    if confirmation_token.get().is_none() {
                        set_error_message.set(Some(invalid_confirmation_link.to_string()));
                        set_loading.set(false);
                    }
                });
            }
        }
    });
    
    
    view! {
        <CardContainer id="email-confirm-page-container">
            <Card variant=CardVariant::Auth class="w-full max-w-md mx-auto" id="email-confirm-card">
                <CardHeader variant=CardVariant::Auth id="email-confirm-header">
                    {t8s!("Email Confirmation")}
                </CardHeader>
                
                <CardContent id="email-confirm-content">
                    <Show when=move || loading.get()>
                        { view! {
                            <div class="flex flex-col items-center justify-center py-8" id="email-confirm-loading">
                                <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-[var(--accent-color)] mb-4" id="email-confirm-spinner"></div>
                                <div class="text-[var(--text-secondary)] text-center" id="email-confirm-loading-text">
                                    {t8r!("Confirming your email...")}
                                </div>
                            </div>
                        }}
                    </Show>
                    
                    <Show when=move || error_message.get().is_some()>
                        {
                            let error = error_message.get().unwrap();
                            let navigate = use_navigate();
                            
                            let handle_go_home = {
                                let navigate = navigate.clone();
                                move |_: leptos::ev::MouseEvent| {
                                    log_user_action!("email_confirm_go_home", "EmailConfirmPage");
                                    navigate(t8s!("/en"), Default::default());
                                }
                            };
    
                            let handle_go_to_login = move |_: leptos::ev::MouseEvent| {
                                log_user_action!("email_confirm_go_to_login", "EmailConfirmPage");
                                navigate(t8s!("/en/login"), Default::default());
                            };
                            view! {
                                <div class="flex flex-col gap-4" id="email-confirm-error">
                                    <div class="p-4 bg-red-500/10 border border-red-500/30 rounded-[10px] text-center" id="email-confirm-error-message">
                                        <div class="text-red-400 text-lg font-semibold mb-2" id="email-confirm-error-title">
                                            {t8r!("Confirmation Failed")}
                                        </div>
                                        <div class="text-red-300 text-sm" id="email-confirm-error-description">
                                            {error}
                                        </div>
                                    </div>
                                    
                                    <div class="flex flex-col gap-2" id="email-confirm-error-actions">
                                        <button 
                                            type="button"
                                            class="bg-[var(--btn-secondary-bg)] text-[var(--text-alternative)] border-none rounded-xl py-4 px-5 text-base font-semibold cursor-pointer transition-all duration-300 mt-[10px] hover:bg-[var(--btn-secondary-bg-hover)] hover:-translate-y-px hover:shadow-[0_4px_12px_var(--shadow-darker)]"
                                            id="email-confirm-go-home-btn"
                                            on:click=handle_go_home
                                        >
                                            {t8r!("Go to Home")}
                                        </button>
                                        
                                        <button 
                                            type="button"
                                            class="bg-transparent text-[var(--text-secondary)] border border-[var(--border-color)] rounded-xl py-3 px-4 text-base font-semibold cursor-pointer transition-all duration-300 hover:bg-[var(--btn-secondary-bg-hover)] hover:-translate-y-px hover:shadow-[0_4px_12px_var(--shadow-darker)]"
                                            id="email-confirm-go-login-btn"
                                            on:click=handle_go_to_login
                                        >
                                            {t8r!("Go to Login")}
                                        </button>
                                    </div>
                                </div>
                            }
                        }
                    </Show>
                    
                    <Show when=move || success_message.get().is_some()>
                        {
                            let success = success_message.get().unwrap();
                            let navigate = use_navigate();
                            let handle_go_to_login = move |_: leptos::ev::MouseEvent| {
                                log_user_action!("email_confirm_go_to_login", "EmailConfirmPage");
                                navigate(t8s!("/en/login"), Default::default());
                            };
                            view! {
                                <div class="flex flex-col gap-4" id="email-confirm-success">
                                    <div class="p-4 bg-green-500/10 border border-green-500/30 rounded-[10px] text-center" id="email-confirm-success-message">
                                        <div class="text-green-400 text-lg font-semibold mb-2" id="email-confirm-success-title">
                                            {t8r!("Email Confirmed!")}
                                        </div>
                                        <div class="text-green-300 text-sm mb-4" id="email-confirm-success-description">
                                            {success}
                                        </div>
                                        <div class="text-green-300 text-xs" id="email-confirm-redirect-notice">
                                            {t8r!("Redirecting to login page...")}
                                        </div>
                                    </div>
                                    
                                    <button 
                                        type="button"
                                        class="bg-[var(--btn-secondary-bg)] text-[var(--text-alternative)] border-none rounded-xl py-4 px-5 text-base font-semibold cursor-pointer transition-all duration-300 mt-[10px] hover:bg-[var(--btn-secondary-bg-hover)] hover:-translate-y-px hover:shadow-[0_4px_12px_var(--shadow-darker)]"
                                        id="email-confirm-go-login-success-btn"
                                        on:click=handle_go_to_login
                                    >
                                        {t8r!("Go to Login")}
                                    </button>
                                </div>
                            }
                        }
                    </Show>
                    
                    <Show when=move || !loading.get() && error_message.get().is_none() && success_message.get().is_none()>
                        { view! {
                            <div class="text-center py-8" id="email-confirm-no-token">
                                <div class="text-[var(--text-secondary)]" id="email-confirm-no-token-message">
                                    {t8r!("No confirmation token provided")}
                                </div>
                            </div>
                        }}
                    </Show>
                </CardContent>
            </Card>
        </CardContainer>
    }
}