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::{send_password_recovery_email, AuthError};
use crate::{log_component, log_user_action};
use crate::components::prelude::*;

fn get_user_friendly_error(error: &AuthError) -> String {
    match error {
        AuthError::HttpError { status, message: _ } => {
            match status {
                400 => t8s!("Invalid email address. Please check your email and try again.").to_string(),
                404 => t8s!("No account found with this email address.").to_string(),
                422 => t8s!("Invalid email format. Please enter a valid email address.").to_string(),
                429 => t8s!("Too many requests. Please wait a moment before trying again.").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("email") || msg.contains("invalid") {
                t8s!("Invalid email address. Please check your email and try again.").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 ForgotPasswordPage() -> impl IntoView {
    log_component!(created, "ForgotPasswordPage");
    
    let navigate = use_navigate();
    let email = RwSignal::new(String::new());
    let is_loading = RwSignal::new(false);
    let error_message = RwSignal::new(None::<String>);
    let success_message = RwSignal::new(None::<String>);
    
    let password_recovery_sent_message = t8s!("Password recovery email sent to");
    let check_your_inbox_message = t8s!("Please check your inbox and follow the instructions to reset your password.");

    let handle_submit = move |_| {
        let email_value = email.get();
        
        if email_value.trim().is_empty() {
            error_message.set(Some(t8s!("Please enter your email address.").to_string()));
            return;
        }
        
        if !email_value.contains('@') {
            error_message.set(Some(t8s!("Please enter a valid email address.").to_string()));
            return;
        }
        
        is_loading.set(true);
        error_message.set(None);
        success_message.set(None);
        
        log_user_action!("forgot_password_submit", "ForgotPasswordPage", email_value);
        
        spawn_local(async move {
            match send_password_recovery_email(email_value.clone()).await {
                Ok(_) => {
                    log::info!("[VProxy][API] Password recovery email sent successfully to {}", email_value);
                    success_message.set(Some(format!(
                        "{} {}. {}",
                        password_recovery_sent_message,
                        email_value,
                        check_your_inbox_message
                    )));
                    is_loading.set(false);
                }
                Err(e) => {
                    log::error!("[VProxy][API] Password recovery email failed for {} - {}", email_value, e);
                    error_message.set(Some(get_user_friendly_error(&e)));
                    is_loading.set(false);
                }
            }
        });
    };
    
    let handle_back_to_login = move |_: leptos::ev::Event| {
        log_user_action!("forgot_password_back_to_login", "ForgotPasswordPage");
        navigate(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="forgot-password-title">
                                {t8s!("Forgot Password?")}
                            </h1>
                            <p class="text-[rgba(255,249,247,0.6)] text-sm" id="forgot-password-subtitle">
                                {t8s!("Enter your email address and we'll send you a link to reset your password.")}
                            </p>
                        </div>
                    </CardHeader>
                    
                    <CardContent>
                        <form on:submit=move |ev| {
                            ev.prevent_default();
                            handle_submit(());
                        }>
                            <div class="space-y-4">
                                <div>
                <CustomInput
                    input_type="email".to_string()
                    placeholder=t8s!("Enter your email address")
                    value=email.read_only()
                    on_change=email.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="forgot-password-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="forgot-password-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="forgot-password-submit"
                                >
                                    {move || if is_loading.get() { t8s!("Sending...") } else { t8s!("Send Recovery Email") }}
                                </PrimaryButton>
                                
                                <div class="text-center">
                                <SecondaryLinkButton
                                    href=t8r!("/en/login")().get()
                                    id="forgot-password-back"
                                >
                                    {t8r!("Back to Login")}
                                </SecondaryLinkButton>
                                </div>
                            </div>
                        </form>
                    </CardContent>
                </Card>
            </CardContainer>
        </div>
    }
}
