use leptos::prelude::*;
use crate::components::card::{Card, CardVariant};
use crate::components::prelude::*;
use crate::api::{GeneratedProxy, get_proxy, GetProxyRequest};
use rust_shared::repository::model::ProxyType;
use rust_shared::repository::model::PoolType;
use leptos::task::spawn_local;
use super::proxy_params_context::{use_proxy_params, proxy_region_to_string, pool_type_to_string};

pub use crate::api::GeneratedProxy as ProxyEntry;

#[component]
pub fn ProxyListPage(
    on_back: Callback<()>,
    #[prop(optional)] id: Option<&'static str>,
) -> impl IntoView {
    let params_context = use_proxy_params();
    let proxy_entries = RwSignal::new(Vec::<GeneratedProxy>::new());
    let is_loading = RwSignal::new(false);
    let error_message = RwSignal::new(None::<String>);
    
    Effect::new({
        let proxy_entries = proxy_entries.clone();
        let is_loading = is_loading.clone();
        let error_message = error_message.clone();
        let params_context = params_context.clone();
        
        move |_| {
            let _ = params_context.parameters.get();
            
            spawn_local(async move {
                is_loading.set(true);
                error_message.set(None);
                
                let params = params_context.parameters.get();
                
                let (session_type, sessionttl) = match params.proxy_type {
                    ProxyType::Rotating => ("rotating".to_string(), 0),
                    ProxyType::Sticky(Some(interval)) => ("sticky".to_string(), interval),
                    ProxyType::Sticky(None) => ("sticky".to_string(), 5), // Default 5 minutes
                };
                
                let request = GetProxyRequest {
                    anonymous: if params.anonymity { "true".to_string() } else { "false".to_string() },
                    session_type,
                    protocol: params.protocol.clone(),
                    format: params.format.to_string(),
                    quantity: params.proxy_count,
                    sessionttl,
                    pool: pool_type_to_string(&params.pool_type).to_string(),
                    countries: if params.countries.is_empty() { None } else { Some(params.countries) },
                    cities: if params.cities.is_empty() { None } else { Some(params.cities) },
                    states: if params.states.is_empty() { None } else { Some(params.states) },
                    excluded_asns: if params.asn_exclude.is_empty() { None } else { Some(params.asn_exclude) },
                    included_asns: if params.asn_include.is_empty() { None } else { Some(params.asn_include) },
                    zipcodes: if params.zip_codes.is_empty() { None } else { Some(params.zip_codes) },
                    region: proxy_region_to_string(&params.server_region).to_string(),
                };
                
                match get_proxy(request).await {
                    Ok(proxy_text) => {
                        let proxies: Vec<GeneratedProxy> = proxy_text
                            .lines()
                            .enumerate()
                            .filter_map(|(index, line)| {
                                if !line.trim().is_empty() {
                                    Some(GeneratedProxy {
                                        proxy_string: line.trim().to_string(),
                                        id: index as u32 + 1,
                                        country: None, 
                                        region: None,
                                        city: None,
                                    })
                                } else {
                                    None
                                }
                            })
                            .collect();
                            
                        proxy_entries.set(proxies);
                    }
                    Err(e) => {
                        log::error!("Failed to get proxies: {}", e);
                        error_message.set(Some(format!("{}: {}", t8s!("Failed to generate proxies"), e)));
                        proxy_entries.set(vec![
                            GeneratedProxy { 
                                proxy_string: "user123:pass456@192.168.1.1:8080".to_string(), 
                                id: 1, 
                                country: Some("US".to_string()), 
                                region: None, 
                                city: None 
                            },
                        ]);
                    }
                }
                
                is_loading.set(false);
            });
        }
    });

    let copy_proxy = move |proxy_string: String| {
        if let Some(window) = web_sys::window() {
            let clipboard = window.navigator().clipboard();
            let _ = clipboard.write_text(&proxy_string);
        }
    };

    view! {
        <div 
            class="w-full h-full flex flex-col"
            id=id.unwrap_or("proxy-list-page")
        >
            <Card 
                variant=CardVariant::L2
                max_width="w-full" 
                padding="p-0" 
                class="w-full flex-1 overflow-hidden relative"
                id="proxy-list-main-card"
            >
                <div class="flex items-center justify-between px-4 h-[56px] bg-[rgba(255,249,247,0.05)] backdrop-blur-[100px] rounded-t-[18px]" id="proxy-list-header">
                    <div class="flex items-center gap-2" id="header-left">
                    <button 
                        class="w-[22px] h-[22px] flex items-center justify-center"
                        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"
                            class="w-full h-full"
                        >
                            <path 
                                d="M19 11H5M12 18L5 11L12 4" 
                                stroke="rgba(255,249,247,0.4)" 
                                stroke-width="2" 
                                stroke-linecap="round" 
                                stroke-linejoin="round"
                            />
                        </svg>
                    </button>
                    <h1 class="font-semibold text-lg leading-6 tracking-[-0.02em] text-[rgba(255,249,247,0.95)]" id="proxy-list-title">
                        {t8r!("Proxy List")}
                    </h1>
                </div>

                    <button 
                        class="flex items-center gap-2 px-4 h-[36px] bg-gradient-to-b from-[#FF5011] to-[#FF4400] shadow-[0_0_100px_rgba(255,68,0,0.5),0_0_200px_#FF4400] rounded-[10px] font-semibold text-sm leading-[18px] tracking-[-0.02em] text-[rgba(255,249,247,0.8)] hover:shadow-[0_0_120px_rgba(255,68,0,0.6),0_0_220px_#FF4400] transition-all duration-200"
                        id="regenerate-button"
                        disabled=move || is_loading.get()
                        on:click=move |_| {
                            // trigger regeneration by clearing current proxies
                            // the effect will automatically regenerate with current parameters
                            proxy_entries.set(Vec::new());
                        }
                    >
                        <svg 
                            width="16" 
                            height="16" 
                            viewBox="0 0 16 16" 
                            fill="none" 
                            xmlns="http://www.w3.org/2000/svg"
                            class="w-4 h-4"
                        >
                            <path 
                                d="M13.65 2.35C12.2 0.9 10.2 0 8 0C3.58 0 0 3.58 0 8C0 12.42 3.58 16 8 16C11.73 16 14.84 13.45 15.73 10H13.65C12.83 12.33 10.61 14 8 14C4.69 14 2 11.31 2 8C2 4.69 4.69 2 8 2C9.66 2 11.14 2.69 12.22 3.78L10 6H16V0L13.65 2.35Z" 
                                fill="rgba(255,249,247,0.8)"
                            />
                        </svg>
                        {move || if is_loading.get() { t8s!("Generating...") } else { t8s!("Regenerate") }}
                    </button>
                </div>

                <div class="flex p-4 gap-4 h-[338px]" id="proxy-container">
                    <div class="flex flex-col gap-2 flex-1 h-full bg-[rgba(255,249,247,0.05)] rounded-[14px] p-4 overflow-y-auto" id="proxy-entries-container">
                        {move || {
                            if is_loading.get() {
                                view! {
                                    <div class="flex items-center justify-center h-full" id="loading-container">
                                        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-[rgba(255,249,247,0.8)]" id="loading-spinner"></div>
                                        <span class="ml-3 text-[rgba(255,249,247,0.6)]" id="loading-text">
                                            {t8r!("Generating proxies...")}
                                        </span>
                                    </div>
                                }.into_any()
                            } else if let Some(error) = error_message.get() {
                                view! {
                                    <div class="flex items-center justify-center h-full" id="error-container">
                                        <span class="text-red-400" id="error-text">
                                            {error}
                                        </span>
                                    </div>
                                }.into_any()
                            } else {
                                proxy_entries.with(|entries| {
                                    if entries.is_empty() {
                                        view! {
                                            <div class="flex items-center justify-center h-full" id="empty-container">
                                                <span class="text-[rgba(255,249,247,0.4)]" id="empty-text">
                                                    {t8r!("No proxies generated yet")}
                                                </span>
                                            </div>
                                        }.into_any()
                                    } else {
                                        entries.iter().enumerate().map(|(index, entry)| {
                            let proxy_str = entry.proxy_string.clone();
                            let copy_handler = copy_proxy.clone();
                            view! {
                                <div 
                                                    class="flex justify-between items-center px-4 py-[15px] gap-2 w-full bg-[rgba(255,249,247,0.05)] rounded-[14px]"
                                    id=format!("proxy-entry-{}", index)
                                >
                                    <span 
                                                        class="font-normal text-base leading-[22px] tracking-[-0.02em] text-[rgba(255,249,247,0.6)] flex-1 w-0"
                                                        style="overflow-wrap: break-word"
                                        id=format!("proxy-text-{}", index)
                                    >
                                        {proxy_str.clone()}
                                    </span>
                                    <button 
                                        class="w-[22px] h-[22px] flex items-center justify-center flex-shrink-0"
                                        id=format!("copy-button-{}", index)
                                        on:click=move |_| {
                                            copy_handler(proxy_str.clone());
                                        }
                                    >
                                                        <img src="/copy-icon.svg"/>
                                    </button>
                                </div>
                                            }
                                        }).collect::<Vec<_>>().into_any()
                                    }
                                })
                            }
                        }}
                    </div>
                </div>

                <div class="w-full mt-auto">
                  <div class="mx-auto mb-4 w-fit flex items-center gap-2" id="action-buttons">
                      <button 
                          class="flex justify-center items-center px-3 gap-2 h-[46px] bg-[rgba(255,249,247,0.8)] rounded-[14px] min-w-[144px]"
                          id="download-button"
                      >
                          <span 
                              class="font-semibold text-base leading-[22px] tracking-[-0.02em] text-[rgba(17,17,17,0.8)]"
                              id="download-text"
                          >
                              {t8r!("Download")}
                          </span>
                      </button>

                      <button 
                          class="flex justify-center items-center px-3 gap-2 h-[46px] border border-[rgba(255,249,247,0.4)] rounded-[14px] min-w-[190px]"
                          id="copy-all-button"
                          on:click=move |_| {
                              let all_proxies = proxy_entries.with(|entries| {
                                  entries.iter()
                                  .map(|entry| entry.proxy_string.clone())
                                  .collect::<Vec<_>>()
                                      .join("\n")
                              });
                              copy_proxy(all_proxies);
                          }
                      >
                          <span 
                              class="font-semibold text-base leading-[22px] tracking-[-0.02em] text-[rgba(255,249,247,0.4)]"
                              id="copy-all-text"
                          >
                              {t8r!("Copy All Proxies")}
                          </span>
                          <div class="w-[22px] h-[22px] flex items-center justify-center" id="copy-all-icon">
                              <img src="/copy-icon.svg"/>
                          </div>
                      </button>
                  </div>
                  <div class="mx-auto w-[420px]" id="warning-container">
                      <p class="font-normal text-base leading-[22px] tracking-[-0.02em] text-[rgba(255,249,247,0.4)] text-center" id="warning-text">
                          {t8r!("Please use these proxies responsibly and in accordance with our terms of service.")}
                      </p>
                  </div>
                </div>
            </Card>
        </div>
    }
}
