use leptos::prelude::*;
use leptos::task::spawn_local;
use rust_shared::repository::model::{PoolType, Country};
use crate::api::{get_proxy_countries, AuthError};
use strum::IntoEnumIterator;

#[component]
pub fn ProxyList(
    #[prop(optional)] id: Option<&'static str>,
    #[prop(optional)] class: Option<&'static str>,
) -> impl IntoView {
    let (selected_pool, set_selected_pool) = signal(PoolType::Datacenter);
    
    let (proxy_data, set_proxy_data) = signal::<Option<Vec<Country>>>(None);
    let (loading, set_loading) = signal(false);
    let (error, set_error) = signal::<Option<String>>(None);

    Effect::new(move |_| {
        let pool = selected_pool.get();
        set_loading.set(true);
        set_error.set(None);
        
        spawn_local(async move {
            match get_proxy_countries(pool).await {
                Ok(countries) => {
                    set_proxy_data.set(Some(countries));
                    set_error.set(None);
                }
                Err(e) => {
                    log::error!("Failed to fetch proxy countries: {:?}", e);
                    set_error.set(Some(format!("Failed to load proxy data: {}", e)));
                    set_proxy_data.set(None);
                }
            }
            set_loading.set(false);
        });
    });

    let base_classes = "flex flex-col items-start p-8 gap-8 bg-gradient-to-b from-[rgba(17,17,17,0.72)] to-[rgba(17,17,17,0.4)] rounded-3xl relative";
    let final_classes = match class {
        Some(c) => format!("{} {}", base_classes, c),
        None => base_classes.to_string(),
    };

    view! {
        <section
            class=final_classes
            id=id.unwrap_or("proxy-list")
        >
            <div class="flex flex-row items-start gap-2 w-full" id="proxy-tabs">
                {PoolType::iter().map(|pool| {
                    let is_active = Signal::derive(move || selected_pool.get() == pool);
                    let pool_name = get_pool_display_name(pool);
                    let is_premium = pool.is_premium();
                    
                    let handle_click = move |_| {
                        set_selected_pool.set(pool);
                    };
                    
                    view! {
                        <div 
                            class={move || {
                                if is_active.get() {
                                    "flex flex-row justify-center items-center p-3.5 gap-2 rounded-2xl flex-1 cursor-pointer bg-gradient-to-b from-[#FF5011] to-[#FF4400] shadow-[0px_0px_100px_rgba(255,68,0,0.5),0px_0px_200px_#FF4400]"
                                } else {
                                    "flex flex-row justify-center items-center p-3.5 gap-2 rounded-2xl flex-1 cursor-pointer border border-[rgba(255,249,247,0.4)]"
                                }
                            }}
                            on:click=handle_click
                            id=format!("proxy-tab-{}", pool.as_str())
                        >
                            <span 
                                class={move || {
                                    if is_active.get() {
                                        "text-lg font-semibold leading-6 tracking-[-0.02em] text-[rgba(255,249,247,0.8)]"
                                    } else {
                                        "text-lg font-semibold leading-6 tracking-[-0.02em] text-[rgba(255,249,247,0.4)]"
                                    }
                                }}
                                id=format!("proxy-tab-text-{}", pool.as_str())
                            >
                                {pool_name}
                            </span>
                            
                            {if is_premium {
                                view! {
                                    <div 
                                        class={move || {
                                            if is_active.get() {
                                                "flex flex-row justify-center items-center px-1.5 py-0.5 rounded-md bg-[rgba(255,249,247,0.2)]"
                                            } else {
                                                "flex flex-row justify-center items-center px-1.5 py-0.5 rounded-md bg-[rgba(255,249,247,0.05)]"
                                            }
                                        }}
                                        // style={move || {
                                        //     if !is_active.get() { "display: none;" } else { "" }
                                        // }}
                                        id=format!("proxy-tab-premium-{}", pool.as_str())
                                    >
                                        <span class="text-xs font-bold leading-[18px] tracking-[-0.02em] uppercase text-[rgba(255,249,247,0.6)]">
                                            "PREM"
                                        </span>
                                    </div>
                                }.into_any()
                            } else {
                                view! { <span></span> }.into_any()
                            }}
                        </div>
                    }
                }).collect::<Vec<_>>()}
            </div>
            
            <ProxyItems 
                loading=loading
                error=error
                proxy_data=proxy_data
            />
        </section>
    }
}

/// Get display name for pool type, removing "Premium" for ResidentialPremium
fn get_pool_display_name(pool: PoolType) -> String {
    match pool {
        PoolType::ResidentialPremium => "Residential".to_string(),
        _ => {
            pool.display_name(&rust_shared::i18n::Language::En).replace(" 📺", "").replace(" 🖥", "").replace(" 📱", "")
        }
    }
}

/// Get country flag emoji based on country code
fn get_country_flag(country_code: &str) -> &'static str {
    match country_code.to_uppercase().as_str() {
        "US" | "USA" => "🇺🇸",
        "GB" | "UK" => "🇬🇧",
        "DE" => "🇩🇪",
        "FR" => "🇫🇷",
        "CA" => "🇨🇦",
        "AU" => "🇦🇺",
        "JP" => "🇯🇵",
        "KR" => "🇰🇷",
        "CN" => "🇨🇳",
        "IN" => "🇮🇳",
        "BR" => "🇧🇷",
        "RU" => "🇷🇺",
        "IT" => "🇮🇹",
        "ES" => "🇪🇸",
        "NL" => "🇳🇱",
        "SE" => "🇸🇪",
        "NO" => "🇳🇴",
        "DK" => "🇩🇰",
        "FI" => "🇫🇮",
        "CH" => "🇨🇭",
        "AT" => "🇦🇹",
        "BE" => "🇧🇪",
        "PL" => "🇵🇱",
        "CZ" => "🇨🇿",
        "HU" => "🇭🇺",
        "GR" => "🇬🇷",
        "PT" => "🇵🇹",
        "IE" => "🇮🇪",
        "LU" => "🇱🇺",
        "SK" => "🇸🇰",
        "SI" => "🇸🇮",
        "LV" => "🇱🇻",
        "LT" => "🇱🇹",
        "EE" => "🇪🇪",
        "MT" => "🇲🇹",
        "CY" => "🇨🇾",
        "BG" => "🇧🇬",
        "RO" => "🇷🇴",
        "HR" => "🇭🇷",
        "MX" => "🇲🇽",
        "AR" => "🇦🇷",
        "CL" => "🇨🇱",
        "CO" => "🇨🇴",
        "PE" => "🇵🇪",
        "VE" => "🇻🇪",
        "UY" => "🇺🇾",
        "PY" => "🇵🇾",
        "BO" => "🇧🇴",
        "EC" => "🇪🇨",
        "GT" => "🇬🇹",
        "CR" => "🇨🇷",
        "PA" => "🇵🇦",
        "NI" => "🇳🇮",
        "HN" => "🇭🇳",
        "SV" => "🇸🇻",
        "BZ" => "🇧🇿",
        "TH" => "🇹🇭",
        "VN" => "🇻🇳",
        "SG" => "🇸🇬",
        "MY" => "🇲🇾",
        "ID" => "🇮🇩",
        "PH" => "🇵🇭",
        "TW" => "🇹🇼",
        "HK" => "🇭🇰",
        "MO" => "🇲🇴",
        "MN" => "🇲🇳",
        "KZ" => "🇰🇿",
        "UZ" => "🇺🇿",
        "KG" => "🇰🇬",
        "TJ" => "🇹🇯",
        "TM" => "🇹🇲",
        "AF" => "🇦🇫",
        "PK" => "🇵🇰",
        "BD" => "🇧🇩",
        "LK" => "🇱🇰",
        "NP" => "🇳🇵",
        "BT" => "🇧🇹",
        "MV" => "🇲🇻",
        "ZA" => "🇿🇦",
        "EG" => "🇪🇬",
        "NG" => "🇳🇬",
        "KE" => "🇰🇪",
        "GH" => "🇬🇭",
        "MA" => "🇲🇦",
        "TN" => "🇹🇳",
        "DZ" => "🇩🇿",
        "LY" => "🇱🇾",
        "SD" => "🇸🇩",
        "ET" => "🇪🇹",
        "UG" => "🇺🇬",
        "TZ" => "🇹🇿",
        "ZW" => "🇿🇼",
        "ZM" => "🇿🇲",
        "MW" => "🇲🇼",
        "MZ" => "🇲🇿",
        "BW" => "🇧🇼",
        "NA" => "🇳🇦",
        "SZ" => "🇸🇿",
        "LS" => "🇱🇸",
        "IL" => "🇮🇱",
        "PS" => "🇵🇸",
        "JO" => "🇯🇴",
        "LB" => "🇱🇧",
        "SY" => "🇸🇾",
        "IQ" => "🇮🇶",
        "IR" => "🇮🇷",
        "SA" => "🇸🇦",
        "AE" => "🇦🇪",
        "QA" => "🇶🇦",
        "KW" => "🇰🇼",
        "BH" => "🇧🇭",
        "OM" => "🇴🇲",
        "YE" => "🇾🇪",
        "IS" => "🇮🇸",
        "NZ" => "🇳🇿",
        "FJ" => "🇫🇯",
        _ => "🌍", // Default globe emoji for unknown countries
    }
}

/// Format number with thousands separators
fn format_number(num: u32) -> String {
    if num < 1000 {
        num.to_string()
    } else if num < 1_000_000 {
        let thousands = num / 1000;
        let remainder = num % 1000;
        if remainder == 0 {
            format!("{}K", thousands)
        } else {
            format!("{}.{}K", thousands, remainder / 100)
        }
    } else {
        let millions = num / 1_000_000;
        let remainder = num % 1_000_000;
        if remainder == 0 {
            format!("{}M", millions)
        } else {
            format!("{}.{}M", millions, remainder / 100_000)
        }
    }
}

#[component]
pub fn ProxyItems(
    loading: ReadSignal<bool>,
    error: ReadSignal<Option<String>>,
    proxy_data: ReadSignal<Option<Vec<Country>>>,
    #[prop(optional)] id: Option<&'static str>,
    #[prop(optional)] class: Option<&'static str>,
) -> impl IntoView {
    view! {
        <div 
            class=format!("flex flex-row items-start p-4 gap-4 w-full rounded-2xl bg-gradient-to-b from-[rgba(255,249,247,0.09)] to-[rgba(255,249,247,0.005)] backdrop-blur-sm {}", class.unwrap_or(""))
            id=id.unwrap_or("proxy-items")
        >
            <div class="flex flex-col items-start gap-2 w-full h-[472px] overflow-y-auto scrollbar-thin scrollbar-track-[rgba(255,249,247,0.05)] scrollbar-thumb-[rgba(255,249,247,0.6)] scrollbar-thumb-rounded-full" id="proxy-item-container">
                {move || {
                    if loading.get() {
                        view! {
                            <div class="flex items-center justify-center w-full h-full" id="proxy-loading">
                                <div class="text-[rgba(255,249,247,0.6)] text-lg">
                                    "Loading proxy data..."
                                </div>
                            </div>
                        }.into_any()
                    } else if let Some(error_msg) = error.get() {
                        view! {
                            <div class="flex items-center justify-center w-full h-full" id="proxy-error">
                                <div class="text-red-400 text-lg text-center">
                                    {error_msg}
                                </div>
                            </div>
                        }.into_any()
                    } else if let Some(countries) = proxy_data.get() {
                        let mut sorted_countries = countries.clone();
                        sorted_countries.sort_by(|a, b| b.count.cmp(&a.count));
                        
                        view! {
                            {sorted_countries.into_iter().map(|country| {
                                let flag_emoji = get_country_flag(&country.code);
                                let formatted_count = format_number(country.count);
                                let country_code = country.code.clone();
                                let country_name = country.name.clone();
                                
                                view! {
                                    <div 
                                        class="flex flex-row justify-between items-center px-4 py-3.5 gap-2 w-full rounded-2xl bg-[rgba(255,249,247,0.05)] hover:bg-[rgba(255,249,247,0.08)] transition-colors duration-200"
                                        id=format!("proxy-item-{}", country_code)
                                    >
                                        <div class="flex flex-row items-center gap-2" id=format!("proxy-title-{}", country_code)>
                                            <div class="w-[22px] h-[22px] flex items-center justify-center text-lg flag-emoji" id=format!("proxy-flag-{}", country_code)>
                                                {flag_emoji}
                                            </div>
                                            <div class="text-lg font-semibold leading-6 tracking-[-0.02em] text-[rgba(255,249,247,0.6)]" id=format!("proxy-name-{}", country_code)>
                                                {country_name}
                                            </div>
                                        </div>
                                        
                                        <div class="text-lg font-semibold leading-6 tracking-[-0.02em] text-[rgba(255,249,247,0.6)]" id=format!("proxy-count-{}", country_code)>
                                            {formatted_count}
                                        </div>
                                    </div>
                                }
                            }).collect::<Vec<_>>()}
                        }.into_any()
                    } else {
                        view! {
                            <div class="flex items-center justify-center w-full h-full" id="proxy-empty">
                                <div class="text-[rgba(255,249,247,0.6)] text-lg">
                                    "No proxy data available"
                                </div>
                            </div>
                        }.into_any()
                    }
                }}
            </div>
        </div>
    }
}
