use leptos::prelude::*;
use leptos::task::spawn_local;
use leptos_router::hooks::use_navigate;
use crate::components::input::CustomInput;
use crate::components::card::{Card, CardContainer, CardHeader, CardContent, CardVariant};
use crate::components::button::{SecondaryLinkButton, PrimaryButton};
use crate::api::{reset_password_with_recovery_code, AuthError};
use crate::{log_component, log_user_action, log_api};
use crate::components::prelude::*;

fn get_user_friendly_error(error: &AuthError) -> String {
    match error {
        AuthError::HttpError { status, message: _ } => {
            match status {
                400 => t8s!("Invalid recovery code or password. Please check your input and try again.").to_string(),
                401 => t8s!("Recovery code has expired or is invalid. Please request a new one.").to_string(),
                404 => t8s!("Recovery code not found. Please request a new password recovery email.").to_string(),
                422 => t8s!("Invalid password format. Please choose a stronger password.").to_string(),
                500 => t8s!("A server error occurred. Please try again later.").to_string(),
                503 => t8s!("Service temporarily unavailable. Please try again later.").to_string(),
                _ => t8s!("An unexpected error occurred. Please try again.").to_string()
            }
        },
        AuthError::NetworkError(_) => t8s!("Network error. Please check your connection and try again.").to_string(),
        AuthError::Other(msg) => {
            if msg.contains("recovery") || msg.contains("code") || msg.contains("expired") {
                t8s!("Recovery code has expired or is invalid. Please request a new one.").to_string()
            } else if msg.contains("password") || msg.contains("weak") {
                t8s!("Password is too weak. Please choose a stronger password.").to_string()
            } else {
                t8s!("An unexpected error occurred. Please try again.").to_string()
            }
        },
        _ => t8s!("An unexpected error occurred. Please try again.").to_string()
    }
}

#[component]
pub fn PasswordRecoveryPage() -> impl IntoView {
    log_component!(created, "PasswordRecoveryPage");
    
    let navigate = use_navigate();
    
    // Extract recovery code from URL query parameters
    let recovery_code = RwSignal::new(None::<String>);
    
    // Extract recovery code on client side only
    create_effect(move |_| {
        log::info!("[DEBUG] create_effect running");
        #[cfg(target_arch = "wasm32")]
        {
            log::info!("[DEBUG] In WASM environment, attempting URL extraction");
            std::panic::catch_unwind(|| {
                if let Some(window) = web_sys::window() {
                    log::info!("[DEBUG] Got window");
                    let location = window.location();
                    if let Ok(href) = location.href() {
                        log::info!("[DEBUG] Current URL: {}", href);
                        if let Ok(url) = web_sys::Url::new(&href) {
                            let search_params = url.search_params();
                            log::info!("[DEBUG] Search params: {}", search_params.to_string());
                            if let Some(code) = search_params.get("recovery_code") {
                                log::info!("[DEBUG] Found recovery code: {}", code);
                                recovery_code.set(Some(code));
                                return;
                            } else {
                                log::warn!("[DEBUG] No recovery_code parameter found");
                            }
                        } else {
                            log::error!("[DEBUG] Failed to create URL from href");
                        }
                    } else {
                        log::error!("[DEBUG] Failed to get href from location");
                    }
                } else {
                    log::error!("[DEBUG] Failed to get window");
                }
                recovery_code.set(None);
            }).unwrap_or_else(|_| {
                log::error!("[DEBUG] Panic caught in URL extraction");
                recovery_code.set(None);
            })
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            log::info!("[DEBUG] Not in WASM environment, setting None");
            recovery_code.set(None);
        }
    });
    
    let new_password = RwSignal::new(String::new());
    let confirm_password = RwSignal::new(String::new());
    let is_loading = RwSignal::new(false);
    let error_message = RwSignal::new(None::<String>);
    let success_message = RwSignal::new(None::<String>);
    
    // Check if recovery code is present
    let has_recovery_code = create_memo(move |_| {
        let has_code = recovery_code.get().is_some();
        log::info!("[DEBUG] has_recovery_code: {}", has_code);
        if let Some(code) = recovery_code.get() {
            log::info!("[DEBUG] Recovery code value: {}", code);
        }
        has_code
    });
    
    // Clone navigate for use in closures
    let navigate_clone = navigate.clone();
    
    let handle_back_to_login = move |_: leptos::ev::Event| {
        log_user_action!("password_recovery_back_to_login", "PasswordRecoveryPage");
        navigate_clone(t8s!("/en/login"), Default::default());
    };
    
    let should_redirect = RwSignal::new(false);
    
    // Watch for redirect signal
    create_effect(move |_| {
        if should_redirect.get() {
            let navigate_redirect = navigate.clone();
            spawn_local(async move {
                gloo_timers::future::TimeoutFuture::new(2000).await;
                navigate_redirect(t8s!("/en/login"), Default::default());
            });
        }
    });
    
    view! {
        <div class="min-h-screen bg-gradient-to-br from-[#0a0a0a] via-[#1a1a1a] to-[#0a0a0a] flex items-center justify-center p-4">
            <CardContainer class="w-full max-w-md">
                <Card variant=CardVariant::L2>
                    <CardHeader>
                        <div class="text-center">
                            <h1 class="text-2xl font-bold text-[rgba(255,249,247,0.95)] mb-2" id="password-recovery-title">
                                {t8s!("Reset Your Password")}
                            </h1>
                            <p class="text-[rgba(255,249,247,0.6)] text-sm" id="password-recovery-subtitle">
                                {move || if has_recovery_code.get() {
                                    t8s!("Enter your new password below.")
                                } else {
                                    t8s!("Invalid recovery link. Please request a new password recovery email.")
                                }}
                            </p>
                        </div>
                    </CardHeader>
                    
                    <CardContent>
                        {move || if has_recovery_code.get() {
                            view! {
                                <form on:submit=move |ev| {
                                    ev.prevent_default();
                                    let new_password_value = new_password.get();
                                    let confirm_password_value = confirm_password.get();
                                    
                                    if new_password_value.trim().is_empty() {
                                        error_message.set(Some(t8s!("Please enter a new password.").to_string()));
                                        return;
                                    }
                                    
                                    if new_password_value.len() < 8 {
                                        error_message.set(Some(t8s!("Password must be at least 8 characters long.").to_string()));
                                        return;
                                    }
                                    
                                    if new_password_value != confirm_password_value {
                                        error_message.set(Some(t8s!("Passwords do not match. Please try again.").to_string()));
                                        return;
                                    }
                                    
                                    if let Some(code) = recovery_code.get() {
                                        is_loading.set(true);
                                        error_message.set(None);
                                        success_message.set(None);
                                        
                                        log_user_action!("password_recovery_submit", "PasswordRecoveryPage", code);
                                        
                                        spawn_local(async move {
                                            // Use the password recovery endpoint instead of change_account_password
                                            match reset_password_with_recovery_code(code, new_password_value.clone()).await {
                                                Ok(_) => {
                                                    log::info!("[VProxy][API] Password recovery successful");
                                                    success_message.set(Some(t8s!("Password updated successfully! You can now log in with your new password.").to_string()));
                                                    is_loading.set(false);
                                                    
                                                    // Redirect to login after a short delay
                                                    should_redirect.set(true);
                                                }
                                                Err(e) => {
                                                    log::error!("[VProxy][API] Password recovery failed - {}", e);
                                                    error_message.set(Some(get_user_friendly_error(&e)));
                                                    is_loading.set(false);
                                                }
                                            }
                                        });
                                    } else {
                                        error_message.set(Some(t8s!("Invalid recovery link. Please request a new password recovery email.").to_string()));
                                    }
                                }>
                                    <div class="space-y-4">
                                        <div>
                <CustomInput
                    input_type="password".to_string()
                    placeholder=t8s!("Enter new password")
                    value=new_password.read_only()
                    on_change=new_password.write_only()
                    class="w-full".to_string()
                />
                                        </div>
                                        
                                        <div>
                                            <CustomInput
                                                input_type="password".to_string()
                                                placeholder=t8s!("Confirm new password")
                                                value=confirm_password.read_only()
                                                on_change=confirm_password.write_only()
                                                class="w-full".to_string()
                                            />
                                        </div>
                                        
                                        {move || {
                                            if let Some(error) = error_message.get() {
                                                view! {
                                                    <div class="bg-red-500/10 border border-red-500/20 rounded-lg p-3" id="password-recovery-error">
                                                        <p class="text-red-400 text-sm">{error}</p>
                                                    </div>
                                                }.into_any()
                                            } else if let Some(success) = success_message.get() {
                                                view! {
                                                    <div class="bg-green-500/10 border border-green-500/20 rounded-lg p-3" id="password-recovery-success">
                                                        <p class="text-green-400 text-sm">{success}</p>
                                                    </div>
                                                }.into_any()
                                            } else {
                                                ().into_any()
                                            }
                                        }}
                                        
                                        <PrimaryButton
                                            button_type="submit".to_string()
                                            disabled=is_loading.into()
                                            class="w-full".to_string()
                                            id="password-recovery-submit"
                                        >
                                            {move || if is_loading.get() { t8s!("Updating...") } else { t8s!("Update Password") }}
                                        </PrimaryButton>
                                        
                                        <div class="text-center">
                                            <SecondaryLinkButton
                                                href=t8r!("/en/login")().get()
                                                id="password-recovery-back"
                                            >
                                                {t8r!("Back to Login")}
                                            </SecondaryLinkButton>
                                        </div>
                                    </div>
                                </form>
                            }.into_any()
                        } else {
                            view! {
                                <div class="space-y-4">
                                    <div class="bg-red-500/10 border border-red-500/20 rounded-lg p-3" id="password-recovery-invalid-link">
                                        <p class="text-red-400 text-sm">
                                            {t8s!("This recovery link is invalid or has expired. Please request a new password recovery email.")}
                                        </p>
                                    </div>
                                    
                                    <div class="text-center">
                                        <SecondaryLinkButton
                                            href=t8r!("/en/login")().get()
                                            id="password-recovery-back-invalid"
                                        >
                                            {t8r!("Back to Login")}
                                        </SecondaryLinkButton>
                                    </div>
                                </div>
                            }.into_any()
                        }}
                    </CardContent>
                </Card>
            </CardContainer>
        </div>
    }
}
