use leptos::prelude::*;
use leptos::task::spawn_local;
use crate::components::prelude::*;
use crate::components::button::PrimaryButton;
use crate::components::input::CustomInput;
use crate::auth::use_auth;
use crate::api::{activate_traffic_promocode, AuthError};

#[component]
pub fn PromoCodeSection() -> impl IntoView {
    let auth = use_auth();
    let (promo_code, set_promo_code) = signal(String::new());
    let (is_loading, set_is_loading) = signal(false);
    let (success_message, set_success_message) = signal(None::<String>);
    let (error_message, set_error_message) = signal(None::<String>);

    let success_message_text = t8s!("Promo code activated successfully!");
    let error_message_text = t8s!("Failed to activate promo code");
    let login_message = t8s!("Please log in to activate promo codes");

    let handle_activate_promo = move |_| {
        if is_loading.get() {
            return;
        }

        let code = promo_code.get();
        if code.trim().is_empty() {
            set_error_message.set(Some(t8s!("Please enter a promo code").to_string()));
            return;
        }

        set_is_loading.set(true);
        set_error_message.set(None);
        set_success_message.set(None);

        let auth_clone = auth.clone();
        let promo_code_clone = code.clone();
        let set_loading = set_is_loading.clone();
        let set_error = set_error_message.clone();
        let set_success = set_success_message.clone();

        spawn_local(async move {
            if let Some(token) = auth_clone.get_token() {
                match activate_traffic_promocode(&token, &promo_code_clone).await {
                    Ok(_) => {
                        set_success.set(Some(success_message_text.to_string()));
                        set_promo_code.set(String::new());
                        
                        // Refresh profile to update traffic balances
                        if let Err(e) = auth_clone.refresh_profile().await {
                            log::warn!("Failed to refresh profile after promo activation: {}", e);
                        }
                        
                        // Hide success message after 3 seconds
                        set_timeout(move || {
                            set_success.set(None);
                        }, std::time::Duration::from_secs(3));
                    }
                    Err(e) => {
                        let error_msg = match e {
                            AuthError::Other(msg) => msg,
                            _ => error_message_text.to_string(),
                        };
                        set_error.set(Some(error_msg));
                    }
                }
            } else {
                set_error.set(Some(login_message.to_string()));
            }
            set_loading.set(false);
        });
    };

    view! {
        <div class="w-full" id="promo-code-section">
            <div class="flex gap-2">
                <CustomInput
                    placeholder=t8s!("Promo code")
                    input_type="text".to_string()
                    value=promo_code
                    on_change=set_promo_code
                    disabled=is_loading
                    class="flex-1".to_string()
                />
                <PrimaryButton
                    id="promo-code-activate-button"
                    class="px-4 py-2 text-sm".to_string()
                    no_margin=true
                    on:click=handle_activate_promo
                    disabled=is_loading.into()
                >
                    {move || if is_loading.get() { t8s!("...") } else { t8s!("Activate") }}
                </PrimaryButton>
            </div>
            
            {move || {
                if let Some(success) = success_message.get() {
                    view! {
                        <div class="text-xs text-green-400 mt-2" id="promo-success-message">
                            {success}
                        </div>
                    }.into_any()
                } else if let Some(error) = error_message.get() {
                    view! {
                        <div class="text-xs text-red-400 mt-2" id="promo-error-message">
                            {error}
                        </div>
                    }.into_any()
                } else {
                    view! { <div></div> }.into_any()
                }
            }}
        </div>
    }
}
