use leptos::prelude::*;
use leptos::task::spawn_local;
use crate::components::prelude::*;
use crate::components::card::{Card, CardVariant};
use crate::auth::use_auth;
use crate::api::{get_whitelist_ips, add_ip_to_whitelist, remove_ip_from_whitelist, validate_ip_address, AuthError, WhitelistError};
use rust_shared::repository::model::{PoolType, Profile};
use strum::IntoEnumIterator;
use crate::utils::pool_utils::get_available_pools;

#[component]
pub fn WhitelistPage() -> impl IntoView {
    let auth = use_auth();
    
    let (selected_pool, set_selected_pool) = signal(PoolType::Residential);
    let (whitelist_ips, set_whitelist_ips) = signal(Vec::<String>::new());
    let (new_ip, set_new_ip) = signal(String::new());
    let (loading, set_loading) = signal(false);
    let (error, set_error) = signal(None::<String>);
    
    let profile = move || auth.get_profile();
    let available_pools = {
        let profile = profile.clone();
        move || {
            if let Some(profile) = profile() {
                get_available_pools(&profile)
            } else {
                vec![]
            }
        }
    };
    
    {
        let available_pools_clone = available_pools.clone();
        Effect::new(move |_| {
            let pools = available_pools_clone();
            if !pools.is_empty() && !pools.contains(&selected_pool.get()) {
                set_selected_pool.set(pools[0]);
            }
        });
    }
    
    Effect::new(move |_| {
        let pool = selected_pool.get();
        spawn_local(async move {
            set_loading.set(true);
            set_error.set(None);
            
            match get_whitelist_ips(pool).await {
                Ok(ips) => {
                    set_whitelist_ips.set(ips);
                }
                Err(e) => {
                    log::error!("Failed to fetch whitelist IPs: {:?}", e);
                    set_error.set(Some(t8s!("Failed to fetch whitelist IPs").to_string()));
                    set_whitelist_ips.set(vec![]);
                }
            }
            
            set_loading.set(false);
        });
    });
    
    let add_ip_logic = move || {
        // Prevent multiple simultaneous executions
        if loading.get() {
            return;
        }
        
        let ip = new_ip.get();
        let pool = selected_pool.get();
        
        if ip.trim().is_empty() {
            set_error.set(Some(t8s!("Please enter an IP address").to_string()));
            return;
        }
        
        if !validate_ip_address(&ip) {
            set_error.set(Some(t8s!("Invalid IP address format").to_string()));
            return;
        }
        
        spawn_local(async move {
            set_loading.set(true);
            set_error.set(None);
            
            match add_ip_to_whitelist(ip.clone(), pool).await {
                Ok(_) => {
                    set_new_ip.set(String::new());
                    match get_whitelist_ips(pool).await {
                        Ok(ips) => set_whitelist_ips.set(ips),
                        Err(e) => log::error!("Failed to refresh whitelist: {:?}", e),
                    }
                }
                Err(e) => {
                    log::error!("Failed to add IP: {:?}", e);
                    let error_message = match e {
                        WhitelistError::IpAlreadyBound => e.to_string(),
                        _ => t8s!("Failed to add IP address").to_string(),
                    };
                    set_error.set(Some(error_message));
                }
            }
            
            set_loading.set(false);
        });
    };
    
    let handle_add_ip = move |_: leptos::ev::MouseEvent| {
        add_ip_logic();
    };
    
    let handle_remove_ip = move |ip: String| {
        let pool = selected_pool.get();
        
        spawn_local(async move {
            set_loading.set(true);
            set_error.set(None);
            
            match remove_ip_from_whitelist(ip, pool).await {
                Ok(_) => {
                    match get_whitelist_ips(pool).await {
                        Ok(ips) => set_whitelist_ips.set(ips),
                        Err(e) => log::error!("Failed to refresh whitelist: {:?}", e),
                    }
                }
                Err(e) => {
                    log::error!("Failed to remove IP: {:?}", e);
                    set_error.set(Some("Failed to remove IP address".to_string()));
                }
            }
            
            set_loading.set(false);
        });
    };
    
    view! {
        <Card 
            variant=CardVariant::L2
            max_width="flex-1" 
            padding="p-3" 
            class="w-full"
            id="whitelist-card"
        >
            <div class="flex flex-col gap-4 mb-8" id="whitelist-header">
                <h1 class="text-2xl font-semibold text-[var(--main-light)] tracking-tight" id="whitelist-title">
                    {t8s!("IP Whitelist")}
                </h1>
                <p class="text-base text-[var(--main-light-40)] leading-relaxed" id="whitelist-description">
                    {t8s!("Manage IP addresses that are allowed to access your proxy pools. Only whitelisted IPs can use your proxies.")}
                </p>
            </div>
            
            {move || {
                let pools = available_pools();
                if pools.is_empty() {
                    view! {
                        <div class="flex flex-col items-center justify-center py-16 px-8 text-center" id="no-pools-state">
                            <div class="w-20 h-20 bg-[var(--text-muted)] bg-opacity-10 rounded-full flex items-center justify-center mb-6">
                                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-[var(--text-muted)]">
                                    <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11h-4v4h-2v-4H7v-2h4V7h2v4h4v2z"/>
                                    <path d="M12 6v6l4 2"/>
                                </svg>
                            </div>
                            
                            <h2 class="text-xl font-semibold text-[var(--main-light)] mb-3" id="no-pools-title">
                                {t8s!("No Proxy Pools Available")}
                            </h2>
                            
                            <p class="text-[var(--text-muted)] text-base leading-relaxed mb-6 max-w-md" id="no-pools-description">
                                {t8s!("You need to purchase proxy traffic before you can manage IP whitelists. Buy traffic for any pool type to get started.")}
                            </p>
                            
                            <div class="flex flex-col sm:flex-row gap-3" id="no-pools-actions">
                                <a 
                                    href=t8r!("/en/profile?section=buy-proxy")().get() 
                                    class="flex items-center justify-center px-6 py-3 bg-gradient-to-b from-[#FF5011] to-[#FF4400] shadow-[0_0_100px_rgba(255,68,0,0.5),0_0_200px_#FF4400] rounded-[14px] font-semibold text-base leading-[22px] tracking-tight text-[var(--main-light-80)] transition-all cursor-pointer border-transparent hover:shadow-[0_0_120px_rgba(255,68,0,0.6),0_0_240px_#FF4400]"
                                    id="buy-traffic-button"
                                >
                                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-2">
                                        <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11h-4v4h-2v-4H7v-2h4V7h2v4h4v2z"/>
                                    </svg>
                                    {t8s!("Buy Traffic")}
                                </a>
                                
                                <a 
                                    href="/prices" 
                                    class="flex items-center justify-center px-6 py-3 border border-[var(--main-light-40)] rounded-[14px] font-semibold text-base leading-[22px] tracking-tight text-[var(--main-light-40)] hover:text-[var(--main-light)] hover:border-[var(--main-light)] transition-all cursor-pointer bg-transparent"
                                    id="view-prices-button"
                                >
                                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-2">
                                        <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
                                    </svg>
                                    {t8s!("View Prices")}
                                </a>
                            </div>
                            
                            <div class="mt-8 p-4 bg-[var(--other-light-5)] rounded-[14px] max-w-lg" id="no-pools-info">
                                <h3 class="text-sm font-semibold text-[var(--main-light)] mb-2" id="info-title">
                                    {t8s!("What you'll get:")}
                                </h3>
                                <ul class="text-[var(--text-muted)] text-sm space-y-1" id="info-list">
                                    <li class="flex items-center">
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-2 text-green-400">
                                            <path d="M20 6L9 17l-5-5"/>
                                        </svg>
                                        {t8s!("Access to proxy pools")}
                                    </li>
                                    <li class="flex items-center">
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-2 text-green-400">
                                            <path d="M20 6L9 17l-5-5"/>
                                        </svg>
                                        {t8s!("IP whitelist management")}
                                    </li>
                                    <li class="flex items-center">
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-2 text-green-400">
                                            <path d="M20 6L9 17l-5-5"/>
                                        </svg>
                                        {t8s!("Real-time proxy access")}
                                    </li>
                                </ul>
                            </div>
                        </div>
                    }.into_any()
                } else {
                    view! {
            
            <div class="flex gap-2 mb-8" id="pool-tabs">
                <For 
                    each={
                        let available_pools = available_pools.clone();
                        move || available_pools()
                    }
                    key=|pool| format!("{:?}", pool)
                    children=move |pool| {
                        let pool_for_click = pool.clone();
                        let is_active = move || selected_pool.get() == pool;
                        
                        view! {
                            <button 
                                class=move || {
                                    if is_active() {
                                        "flex items-center justify-center px-4 py-3 gap-2 flex-1 h-[46px] bg-gradient-to-b from-[#FF5011] to-[#FF4400] shadow-[0_0_100px_rgba(255,68,0,0.5),0_0_200px_#FF4400] rounded-[14px] font-semibold text-base leading-[22px] tracking-tight text-[var(--main-light-80)] transition-all cursor-pointer border-transparent"
                                    } else {
                                        "flex items-center justify-center px-4 py-3 gap-2 flex-1 h-[46px] border border-[var(--main-light-40)] rounded-[14px] font-semibold text-base leading-[22px] tracking-tight text-[var(--main-light-40)] hover:text-[var(--main-light)] hover:border-[var(--main-light)] transition-all cursor-pointer bg-transparent"
                                    }
                                }
                                on:click=move |_| set_selected_pool.set(pool_for_click)
                                id=format!("pool-tab-{}", pool.as_str())
                            >
                                {get_pool_display_name(&pool)}
                                {if matches!(pool, PoolType::ResidentialPremium) {
                                    view! {
                                        <div class="flex items-center justify-center px-[6px] py-[1px] bg-[var(--other-light-5)] rounded-[6px] text-xs font-bold leading-[18px] tracking-tight uppercase text-[var(--main-light-40)]">
                                            "PREM"
                                        </div>
                                    }.into_any()
                                } else {
                                    view! {}.into_any()
                                }}
                            </button>
                        }
                    }
                />
            </div>
            
            <div class="flex flex-col gap-3 mb-8" id="add-ip-section">
                <h3 class="text-xs font-bold leading-[18px] tracking-tight uppercase text-[var(--main-light-40)]" id="add-ip-title">
                    {t8s!("Add IP Address")}
                </h3>
                <div class="flex gap-2" id="add-ip-container">
                    <div class="flex-1 flex items-center px-4 py-3 bg-[var(--other-light-5)] rounded-[10px]" id="ip-input-form">
                        <input 
                            type="text"
                            placeholder={t8s!("Enter IP address (e.g., 192.168.1.1)")}
                            class="flex-1 bg-transparent border-none outline-none text-base font-semibold text-[var(--main-light)] placeholder-[var(--main-light-40)]"
                            prop:value=move || new_ip.get()
                            on:input=move |ev| set_new_ip.set(event_target_value(&ev))
                            on:keydown=move |ev| {
                                if ev.key() == "Enter" {
                                    add_ip_logic();
                                }
                            }
                            prop:disabled=move || loading.get()
                            id="ip-input"
                        />
                    </div>
                    <button 
                        class="flex items-center justify-center w-[46px] h-[46px] bg-[var(--other-light-5)] rounded-[10px] text-[var(--main-light-40)] hover:text-[var(--main-light)] transition-colors cursor-pointer border-none disabled:opacity-50"
                        on:click=handle_add_ip
                        prop:disabled=move || loading.get() || new_ip.get().trim().is_empty()
                        id="add-ip-button"
                    >
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" id="add-icon">
                            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11h-4v4h-2v-4H7v-2h4V7h2v4h4v2z"/>
                        </svg>
                    </button>
                </div>
            </div>
            
            {move || error.get().map(|err| view! {
                <div class="mb-4 p-3 bg-red-500/10 border border-red-500/30 rounded-[10px] text-red-400 text-sm" id="error-message">
                    {err}
                </div>
            })}
            
            <div class="flex flex-col gap-3" id="ip-list-section">
                <h3 class="text-xs font-bold leading-[18px] tracking-tight uppercase text-[var(--main-light-40)]" id="ip-list-title">
                    {t8s!("Whitelisted IP Addresses")}
                </h3>
                <div class="p-4 bg-gradient-to-b from-[rgba(255,249,247,0.09)] to-[rgba(255,249,247,0.005)] bg-[rgba(17,17,17,0.4)] rounded-t-[14px] min-h-[218px]" id="ip-list-container">
                    {move || {
                        if loading.get() {
                            view! {
                                <div class="flex items-center justify-center h-32 text-[var(--main-light-40)]" id="loading-indicator">
                                    <div class="animate-spin rounded-full h-8 w-8 border-2 border-[var(--main-light-40)] border-t-transparent"></div>
                                    <span class="ml-3">{t8s!("Loading...")}</span>
                                </div>
                            }.into_any()
                        } else {
                            let ips = whitelist_ips.get();
                            if ips.is_empty() {
                                view! {
                                    <div class="flex items-center justify-center h-32 text-[var(--main-light-40)]" id="no-ips-message">
                                        {t8s!("No IP addresses whitelisted for this pool")}
                                    </div>
                                }.into_any()
                            } else {
                                view! {
                                    <div class="flex flex-col gap-2 max-h-[186px] overflow-y-auto" id="ip-list">
                                        <For 
                                            each=move || whitelist_ips.get().into_iter().enumerate()
                                            key=|(i, _)| *i
                                            children=move |(index, ip)| {
                                                let ip_for_remove = ip.clone();
                                                view! {
                                                    <div class="flex items-center justify-between px-4 py-3 bg-[var(--other-light-5)] rounded-[14px]" id=format!("ip-item-{}", index)>
                                                        <span class="text-lg font-semibold text-[var(--other-light-60)] leading-6 tracking-tight" id=format!("ip-text-{}", index)>
                                                            {ip}
                                                        </span>
                                                        <button 
                                                            class="flex items-center justify-center w-[22px] h-[22px] text-[var(--main-light-40)] hover:text-red-400 transition-colors cursor-pointer bg-transparent border-none"
                                                            on:click=move |_| handle_remove_ip(ip_for_remove.clone())
                                                            prop:disabled=move || loading.get()
                                                            title={t8s!("Remove IP")}
                                                            id=format!("remove-ip-{}", index)
                                                        >
                                                            <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor" class="transform rotate-45" id="delete-icon">
                                                                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11h-4v4h-2v-4H7v-2h4V7h2v4h4v2z"/>
                                                            </svg>
                                                        </button>
                                                    </div>
                                                }
                                            }
                                        />
                                    </div>
                                }.into_any()
                            }
                        }
                    }}
                </div>
            </div>
                    }.into_any()
                }
            }}
        </Card>
    }
}


fn get_pool_display_name(pool: &PoolType) -> String {
    match pool {
        PoolType::Residential => "Residential",
        PoolType::Datacenter => "Datacenter",
        PoolType::ResidentialPremium => "Residential Premium",
        PoolType::Mobile => "Mobile",
    }.to_string()
}
