use leptos::prelude::*;
use leptos::task::spawn_local;
use crate::components::prelude::*;
use crate::components::dropdown::Dropdown;
use super::dashboard::proxy_params_context::use_proxy_params;
use crate::api::{get_pool_prices, calculate_detailed_price, get_payment_systems, create_invoice_web, process_referral_payment};
use crate::auth::use_auth;
use rust_shared::repository::model::{PoolType, PurchaseRequest, ReferralPaymentRequest, PaymentSystem, Profile};
use crate::api::DetailedPriceCalculation;
use crate::utils::pool_utils::get_available_pools;
use strum::IntoEnumIterator;

#[component]
pub fn BuyProxyPage(
    on_back: Callback<()>,
) -> impl IntoView {
    let params_context = use_proxy_params();
    let _parameters = params_context.parameters;
    let auth = use_auth();
    let referral_context = use_referral_tracking();
    
    let profile = {
        let auth = auth.clone();
        move || auth.get_profile()
    };
    let _available_pools = {
        let profile = profile.clone();
        move || {
            if let Some(profile) = profile() {
                get_available_pools(&profile)
            } else {
                vec![]
            }
        }
    };
    
    let (traffic_amount, set_traffic_amount) = signal(1u32);
    let (selected_pool, set_selected_pool) = signal(PoolType::Residential);
    let (promo_code, set_promo_code) = signal("".to_string());
    let (selected_payment, set_selected_payment) = signal("".to_string());
    let (is_processing, set_is_processing) = signal(false);
    let (error_message, set_error_message) = signal("".to_string());
    
    let pool_display = |pool: &PoolType| {
        match pool {
            PoolType::Residential => t8s!("Residential").to_string(),
            PoolType::ResidentialPremium => t8s!("Residential Premium").to_string(),
            PoolType::Datacenter => t8s!("Datacenter").to_string(),
            PoolType::Mobile => t8s!("Mobile").to_string(),
        }
    };
    
    let (pool_prices, set_pool_prices) = signal(None::<std::collections::HashMap<PoolType, f64>>);
    let (payment_systems, set_payment_systems) = signal(Vec::<PaymentSystem>::new());
    let (price_calculation, set_price_calculation) = signal(None::<DetailedPriceCalculation>);
    
    let auth_for_initial = auth.clone();
    let auth_for_calc = auth.clone();
    let auth_for_purchase = auth.clone();
    
    Effect::new(move |_| {
        if let Some(token) = auth_for_initial.get_token() {
            spawn_local(async move {
                match get_pool_prices(&token).await {
                    Ok(prices) => {
                        let mut price_map = std::collections::HashMap::new();
                        price_map.insert(PoolType::Residential, prices.residential);
                        price_map.insert(PoolType::ResidentialPremium, prices.residential_premium);
                        price_map.insert(PoolType::Datacenter, prices.datacenter);
                        price_map.insert(PoolType::Mobile, prices.mobile);
                        set_pool_prices.set(Some(price_map));
                    }
                    Err(e) => {
                        set_error_message.set(format!("{}: {}", t8s!("Failed to load prices"), e));
                    }
                }
                
                match get_payment_systems(&token).await {
                    Ok(mut systems) => {
                        systems.retain(|system| system.name != "telegram_stars");
                        set_payment_systems.set(systems);
                    }
                    Err(e) => {
                        set_error_message.set(format!("{}: {}", t8s!("Failed to load payment methods"), e));
                    }
                }
            });
        }
    });
    
    Effect::new(move |_| {
        if let Some(token) = auth_for_calc.get_token() {
            if let Some(_prices) = pool_prices.get() {
                let amount = traffic_amount.get();
                let pool = selected_pool.get();
                let promo_code_value = promo_code.get();
                let promo = if promo_code_value.trim().is_empty() { 
                    None 
                } else { 
                    Some(promo_code_value.trim().to_string()) 
                };
                
                spawn_local(async move {
                    match calculate_detailed_price(&token, pool, amount, promo.as_deref()).await {
                        Ok(calculation) => {
                            set_price_calculation.set(Some(calculation));
                            set_error_message.set("".to_string());
                        }
                        Err(e) => {
                            set_error_message.set(format!("{}: {}", t8s!("Failed to calculate price"), e));
                            set_price_calculation.set(None);
                        }
                    }
                });
            }
        }
    });
    
    let handle_purchase = move || {
        if is_processing.get() {
            return;
        }
        
        if traffic_amount.get() == 0 {
            set_error_message.set(t8s!("Please enter a valid amount").to_string());
            return;
        }
        
        if selected_payment.get().is_empty() {
            set_error_message.set(t8s!("Please select a payment method").to_string());
            return;
        }
        
        if let Some(token) = auth_for_purchase.get_token() {
            set_is_processing.set(true);
            set_error_message.set("".to_string());
            
            let amount = traffic_amount.get();
            let pool = selected_pool.get();
            let promo_code_value = promo_code.get();
            let promo = if promo_code_value.trim().is_empty() { 
                None 
            } else { 
                Some(promo_code_value.trim().to_string()) 
            };
            let payment_method = selected_payment.get();
            let is_referral = payment_method == "referalpay";
            let referral_data = referral_context.referral_data.get();
            
            spawn_local(async move {
                let result = if is_referral {
                    let request = ReferralPaymentRequest {
                        amount,
                        pool,
                        promocode: promo,
                    };
                    process_referral_payment(&token, request).await
                } else {
                    let request = PurchaseRequest {
                        payment_method,
                        amount,
                        pool,
                        promocode: promo,
                    };
                    
                    if referral_data.referral_code.is_some() || referral_data.admin_referral_code.is_some() {
                        let _ = crate::api::track_referral_source(
                            referral_data.referral_code.as_deref(),
                            referral_data.admin_referral_code.as_deref(),
                            None, // utm_source
                            None, // utm_medium
                            None, // utm_campaign
                        ).await;
                    }
                    
                    create_invoice_web(&token, request).await.map(|url| {
                        web_sys::window().unwrap().location().set_href(&url).unwrap();
                    })
                };
                
                match result {
                    Ok(_) => {
                        if is_referral {
                            set_error_message.set(t8s!("Payment successful! Your traffic has been added.").to_string());
                        }
                    }
                    Err(e) => {
                        set_error_message.set(format!("{}: {}", t8s!("Payment failed"), e));
                    }
                }
                
                set_is_processing.set(false);
            });
        }
    };
    
    view! {
        <div class="w-full h-full flex flex-col rounded-[18px]" style="background: var(--buy-proxy-page-bg);" id="buy-proxy-page">
            <div class="flex items-center px-4 py-4 rounded-t-[18px] gap-2" style="background: var(--buy-proxy-header-bg); backdrop-filter: var(--buy-proxy-header-backdrop);" id="buy-proxy-header">
                <button
                    class="w-[22px] h-[22px] transition-colors duration-200 hover:opacity-80"
                    style="color: var(--main-light-40);"
                    id="back-button"
                    on:click=move |_| on_back.run(())
                >
                    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M8.25 5.5L3.75 10L8.25 14.5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                </button>
                <h1 class="text-lg font-semibold" style="color: var(--main-light);" id="buy-proxy-title">
                    {t8s!("Buy Proxy")}
                </h1>
            </div>
            
            <Show when=move || !error_message.get().is_empty()>
                {move || view! {
                    <div class="mx-4 mt-4 p-3 bg-red-900/20 border border-red-500/30 rounded-lg" id="error-message">
                        <p class="text-red-400 text-sm" id="error-text">
                            {error_message.get()}
                        </p>
                    </div>
                }}
            </Show>
            
            <div class="flex-1 flex p-4 gap-6" id="buy-proxy-content">
                <div class="flex flex-col gap-4 w-1/2" id="proxy-info-container">
                    <div class="flex flex-col gap-3" id="traffic-amount-section">
                        <h3 class="font-bold text-xs leading-[18px] tracking-[-0.02em] uppercase" style="color: var(--main-light-40);" id="traffic-amount-title">
                            {t8s!("TRAFFIC AMOUNT (GB)")}
                        </h3>
                        <div class="flex items-center justify-between p-[14px] gap-2 h-[46px] rounded-[10px]" style="background: var(--buy-proxy-field-bg);" id="traffic-amount-input">
                                <input
                                    type="number"
                                placeholder=t8s!("1") 
                                    min="1"
                                max="999999"
                                class="flex-1 h-[22px] bg-transparent font-semibold text-base leading-[22px] tracking-[-0.02em] outline-none"
                                style="color: var(--main-light-40);"
                                prop:value=move || traffic_amount.get().to_string()
                                on:input=move |ev| {
                                    if let Ok(value) = event_target_value(&ev).parse::<u32>() {
                                        set_traffic_amount.set(value.max(1));
                                    }
                                }
                            />
                        </div>
                        </div>
                        
                    <div class="flex flex-col gap-3" id="pool-type-section">
                        <h3 class="font-bold text-xs leading-[18px] tracking-[-0.02em] uppercase" style="color: var(--main-light-40);" id="pool-type-title">
                            {t8s!("PROXY POOL")}
                        </h3>
                        <Dropdown 
                            selected=selected_pool
                            options=move || vec![PoolType::Residential, PoolType::ResidentialPremium, PoolType::Datacenter, PoolType::Mobile]
                            on_change=Callback::new(move |pool| set_selected_pool.set(pool))
                            display_fn=pool_display
                            id="pool-dropdown"
                        />
                    </div>
                    
                    <div class="flex flex-col gap-3" id="promo-code-section">
                        <h3 class="font-bold text-xs leading-[18px] tracking-[-0.02em] uppercase" style="color: var(--main-light-40);" id="promo-code-title">
                            {t8s!("PROMO CODE (OPTIONAL)")}
                        </h3>
                        <div class="flex items-center justify-between p-[14px] gap-2 h-[46px] rounded-[10px]" style="background: var(--buy-proxy-field-bg);" id="promo-code-input">
                            <input 
                                type="text" 
                                placeholder=t8s!("Enter promo code") 
                                class="flex-1 h-[22px] bg-transparent font-semibold text-base leading-[22px] tracking-[-0.02em] outline-none"
                                style="color: var(--main-light-40);"
                                prop:value=promo_code
                                on:input=move |ev| set_promo_code.set(event_target_value(&ev))
                            />
                            </div>
                        </div>
                        
                    <div class="flex flex-col gap-3" id="total-cost-section">
                        <h3 class="font-bold text-xs leading-[18px] tracking-[-0.02em] uppercase" style="color: var(--main-light-40);" id="total-cost-title">
                            {t8s!("TOTAL COST")}
                        </h3>
                        <div class="flex items-center justify-between p-[14px] gap-2 h-[46px] rounded-[10px]" style="background: var(--buy-proxy-field-bg);" id="total-cost-display">
                            <span class="font-semibold text-base leading-[22px] tracking-[-0.02em]" style="color: var(--main-light);" id="total-cost-amount">
                                {move || {
                                    if let Some(calc) = price_calculation.get() {
                                        format!("${:.2}", calc.final_price)
                                    } else {
                                        "$0.00".to_string()
                                    }
                                }}
                                </span>
                            <span class="font-normal text-base leading-[22px] tracking-[-0.02em] cursor-help" style="color: var(--main-light-40);" id="cost-breakdown" title={t8s!("Discounts for 100, 300, 500, and 1000 GB")}>
                                {t8s!("Breakdown")}
                            </span>
                            </div>
                        </div>

                        <div class="flex flex-col gap-3" id="payment-method-dropdown-section">
                            <h3 class="font-bold text-xs leading-[18px] tracking-[-0.02em] uppercase" style="color: var(--main-light-40);" id="payment-method-title">
                                {t8s!("PAYMENT METHOD")}
                            </h3>

                            <Dropdown 
                                selected=selected_payment
                                options=move || payment_systems.get().into_iter().enumerate().map(|(index, system)| system.name)
                                on_change=Callback::new(move |system| set_selected_payment.set(system))
                                display_fn=|system| {system.to_string()}
                                id="payment-method-dropdown"
                            />
                        </div>
                        
                        <button
                        class=move || {
                            if is_processing.get() {
                                "flex items-center justify-center p-3 h-[46px] rounded-[14px] cursor-not-allowed w-full"
                            } else {
                                "flex items-center justify-center p-3 h-[46px] rounded-[14px] hover:opacity-90 transition-opacity duration-200 w-full"
                            }
                        }
                        style=move || {
                            if is_processing.get() {
                                "background: var(--buy-proxy-button-bg-disabled);"
                            } else {
                                "background: var(--buy-proxy-button-bg);"
                            }
                        }
                        id="buy-button"
                        disabled=is_processing
                        on:click=move |_| handle_purchase()
                    >
                        <span class="font-semibold text-base leading-[22px] tracking-[-0.02em]" style="color: var(--buy-proxy-button-text);" id="buy-button-text">
                            {move || if is_processing.get() { t8s!("Processing...") } else { t8s!("Buy Now") }}
                        </span>
                        </button>

                    </div>
                    
                <div class="flex flex-col gap-3 w-1/2 overflow-y-auto overflow-x-hidden" id="payment-methods-container">
                    <h3 class="font-bold text-xs leading-[18px] tracking-[-0.02em] uppercase" style="color: var(--main-light-40);" id="payment-methods-title">
                        {t8s!("PAYMENT METHOD")}
                        </h3>
                    <div class="flex flex-col gap-2 pr-2" id="payment-methods-list">
                        <Show when=move || !payment_systems.get().is_empty()>
                            {move || {
                                payment_systems.get().into_iter().enumerate().map(|(index, system)| {
                                    let system_name = system.name.clone();
                                    let system_desc = system.description.clone();
                                    let system_name_for_click = system_name.clone();
                                    let system_name_for_display = system_name.clone();
                                    let system_name_for_class = system_name.clone();
                                    let system_name_for_style = system_name.clone();
                                    let system_desc_for_show = system_desc.clone();
                                    let system_desc_for_check = system_desc.clone();
                                    
                                    let _icon = match system.name.to_lowercase().as_str() {
                                        name if name.contains("card") || name.contains("credit") => "💳",
                                        name if name.contains("paypal") => "🅿️",
                                        name if name.contains("bitcoin") || name.contains("btc") => "₿",
                                        name if name.contains("ethereum") || name.contains("eth") => "Ξ",
                                        name if name.contains("usdt") => "₮",
                                        name if name.contains("litecoin") || name.contains("ltc") => "Ł",
                                        name if name.contains("monero") || name.contains("xmr") => "ɱ",
                                        name if name.contains("dogecoin") || name.contains("doge") => "Ð",
                                        name if name.contains("referral") || name.contains("referal") => "🎁",
                                        _ => "💳",
                                    };
                                
                                view! {
                                    <button
                                        class=move || {
                                                if selected_payment.get() == system_name_for_class {
                                                    "flex flex-col items-center justify-center p-6 gap-2 w-full h-[104px] rounded-[18px] transition-colors duration-200"
                                            } else {
                                                    "flex flex-col items-center justify-center p-6 gap-2 w-full h-[104px] rounded-[18px] hover:opacity-80 transition-opacity duration-200"
                                                }
                                            }
                                            style=move || {
                                                if selected_payment.get() == system_name_for_style {
                                                    "border: 1px solid var(--buy-proxy-payment-border-selected); background: var(--buy-proxy-payment-bg-selected);"
                                                } else {
                                                    "border: 1px solid var(--buy-proxy-payment-border);"
                                                }
                                            }
                                            id=format!("payment-method-{}", index)
                                            on:click=move |_| set_selected_payment.set(system_name_for_click.clone())
                                        >
                                            <span class="font-semibold text-2xl leading-[30px] tracking-[-0.02em] text-center" style="color: var(--main-light-80);" id=format!("payment-name-{}", index)>
                                                {system_name_for_display}
                                            </span>
                                            <Show when=move || !system_desc_for_check.is_empty()>
                                                <div 
                                                    class="font-bold text-xs leading-[18px] tracking-[-0.02em] uppercase text-center" 
                                                    style="color: var(--main-light-40);"
                                                    id=format!("payment-desc-{}", index)
                                                    inner_html=system_desc_for_show.clone()
                                                />
                                            </Show>
                                    </button>
                                }
                                }).collect::<Vec<_>>()
                            }}
                        </Show>
                        <Show when=move || payment_systems.get().is_empty()>
                            {move || view! {
                                <div class="flex items-center justify-center p-6 w-full h-[104px]" style="color: var(--main-light-40);" id="loading-payment-methods">
                                    {t8s!("Loading payment methods...")}
                        </div>
                            }}
                        </Show>
                    </div>
                </div>
            </div>
        </div>
    }
}
