use leptos::prelude::*;
use crate::components::card::{Card, CardVariant};
use crate::components::button::PrimaryButton;
use crate::auth::use_auth;
use rust_shared::repository::model::{PoolType, Profile};
use crate::components::prelude::*;
use super::usage_statistics::UsageStatistics;
use super::promo_code_section::PromoCodeSection;

#[component]
pub fn HomeCenter(
    on_buy_proxy_click: Callback<()>,
) -> impl IntoView {
    let _auth = use_auth();

    view! {
        <Card 
            variant=CardVariant::L2
            max_width="w-full" 
            padding="p-0"
            class="w-full h-full flex flex-col"
            id="home-center-card"
        >
            <div id="home-center-card__planet">
                <div id="home-center-card__planet__shading">
                </div>
            </div>
            
            <div class="p-[16px] mt-auto">
                <div class="mb-6" id="proxy-pools-section">
                           <h3 class="text-[24px] font-semibold text-white mb-[24px] text-center" id="proxy-pools-title">
                               {t8s!("Your traffic")}
                           </h3>
                    <div class="flex flex-col gap-3" id="proxy-pools-stack">
                        <ProxyPoolsDisplay />
                    </div>
                </div>
                
                <div class="mt-auto" id="buy-section">
                    <div class="mb-4" id="promo-section">
                        <PromoCodeSection />
                    </div>
                    <PrimaryButton 
                        id="buy-button"
                        class="w-full".to_string()
                        on:click=move |_| on_buy_proxy_click.run(())
                    >
                        {t8s!("Buy More Traffic")}
                    </PrimaryButton>
                </div>
            </div>
        </Card>
    }
}

#[component]
fn ProxyPoolsDisplay() -> impl IntoView {
    let auth = use_auth();
    
    let proxy_pools = vec![
        (PoolType::Datacenter, t8s!("Datacenter")),
        (PoolType::Residential, t8s!("Residential")),
        (PoolType::ResidentialPremium, t8s!("Residential Premium")),
        (PoolType::Mobile, t8s!("Mobile")),
    ];

    view! {
        {move || {
            if let Some(user_data) = auth.user_data.get() {
                let profile = &user_data.profile;
                proxy_pools.iter().enumerate().map(|(index, (pool_type, pool_label))| {
                    let balance_format = profile.get_pool(pool_type)
                        .map(|pool| pool.balance_format)
                        .unwrap_or_else(|| "0 GB".to_string());
                    
                    let pool_id = match index {
                        0 => "pool-datacenter",
                        1 => "pool-residential", 
                        2 => "pool-residential-premium",
                        3 => "pool-mobile",
                        _ => "pool-unknown",
                    };
                    
                    view! {
                        <ProxyPoolCard 
                            pool_name=pool_label.to_string()
                            amount=balance_format
                            id=pool_id
                        />
                    }
                }).collect::<Vec<_>>()
            } else {
                proxy_pools.iter().enumerate().map(|(index, (_, pool_label))| {
                    let pool_id = match index {
                        0 => "pool-datacenter",
                        1 => "pool-residential", 
                        2 => "pool-residential-premium",
                        3 => "pool-mobile",
                        _ => "pool-unknown",
                    };
                    
                    view! {
                        <ProxyPoolCard 
                            pool_name=pool_label.to_string()
                            amount=t8s!("Loading...").to_string()
                            id=pool_id
                        />
                    }
                }).collect::<Vec<_>>()
            }
        }}
    }
}

#[component]
fn ProxyPoolCard(
    pool_name: String,
    amount: String,
    id: &'static str,
) -> impl IntoView {
    view! {
        <Card 
            variant=CardVariant::L3
            max_width="w-full" 
            padding="p-2" 
            class="w-full rounded-xl"
            id=id
        >
            <div class="flex justify-between items-center">
                <div class="flex items-center gap-2">
                    {move || {
                        let name = pool_name.clone();
                        let is_premium = name.contains(t8s!("Premium"));

                        log::info!("pool type {}", name.clone());

                        let display_name = if is_premium {
                            name.replace(t8s!("Premium"), "").trim().to_string()
                        } else {
                            name
                        };

                        log::info!("pool type {}", display_name);
                        
                        view! {
                            <span class="text-lg font-semibold text-white">
                                {display_name}
                            </span>
                            {if is_premium {
                                view! { <div class="premium-label">"PREM"</div> }.into_any()
                            } else {
                                view! { <div></div> }.into_any()
                            }}
                        }
                    }}
                </div>
                <span class="text-lg font-bold">
                    {move || {
                        let amount_str = amount.clone();
                        let parts: Vec<&str> = amount_str.split_whitespace().collect();
                        if parts.len() >= 2 {
                            let number = parts[0];
                            let unit = parts[1..].join(" ");
                            view! {
                                <span class="text-white">{number}</span>
                                <span class="text-gray-400 ml-1">{format!(" {}", unit)}</span>
                            }.into_any()
                        } else {
                            view! {
                                <span class="text-white">{amount_str}</span>
                            }.into_any()
                        }
                    }}
                </span>
            </div>
        </Card>
    }
}

#[component]
pub fn HomeRight() -> impl IntoView {
    view! {
        <UsageStatistics />
    }
}
