use leptos::prelude::*;
use crate::components::layout::PageContent;
use leptos::ev::MouseEvent;
use std::rc::Rc;
use leptos::task::spawn_local;
use gloo_timers::callback::Timeout;
use leptos_router::{hooks::{use_params_map, use_navigate}};
use crate::api::{BlogArticle, create_blog_article, get_blog_articles, get_my_articles, update_blog_article, delete_blog_article, get_blog_article, get_blog_article_image, upload_blog_article_image};
use crate::auth::use_auth;
use crate::components::prelude::*;
use crate::components::input::CustomInput;
use crate::components::card::{CardContainer, Card, CardHeader, CardContent, CardVariant};
use crate::components::dropdown::Dropdown;
use rust_shared::i18n::Language;
use std::collections::HashMap;
use base64::Engine as _;
use leptos::wasm_bindgen::JsCast;

fn language_display_name(lang: &Language) -> String {
    match lang {
        Language::En => t8s!("English").to_string(),
        Language::Ru => t8s!("Russian").to_string(),
    }
}

fn format_date(date_str: &str) -> String {
    if let Ok(parsed_date) = chrono::DateTime::parse_from_rfc3339(date_str) {
        parsed_date.format("%b %d, %Y").to_string()
    } else if let Ok(parsed_date) = chrono::NaiveDateTime::parse_from_str(date_str, "%Y-%m-%d %H:%M:%S") {
        parsed_date.format("%b %d, %Y").to_string()
    } else {
        date_str.to_string()
    }
}

#[component]
pub fn WriteArticleButton() -> impl IntoView {
    let auth = use_auth();
    
    view! {
        <Show when=move || auth.is_authenticated.get() && auth.is_admin()>
            <a
                href="/en/blog/write"
                class="py-3 px-6 bg-[var(--accent-primary-gradient)] text-white rounded-full font-semibold text-sm border-none cursor-pointer transition-all duration-300 hover:opacity-80 hover:-translate-y-0.5 hover:shadow-[0_4px_15px_var(--auth-button-shadow)] no-underline"
                id="write-article-button"
            >
                <span class="flex items-center gap-2">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" id="write-icon">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                    </svg>
                    {t8r!("Write Article")}
                </span>
            </a>
        </Show>
    }
}

#[component]
pub fn ArticleForm(
    #[prop(optional)] article: Option<BlogArticle>,
    on_save: Callback<BlogArticle>,
    on_cancel: Callback<()>,
) -> impl IntoView {
    let is_editing = article.is_some();
    let article_clone = article.clone();
    
    let (title, set_title) = create_signal(
        article.as_ref().map(|a| a.title.clone()).unwrap_or_default()
    );
    let (content, set_content) = create_signal(
        article.as_ref().map(|a| a.content.clone()).unwrap_or_default()
    );
    let (language, set_language) = create_signal(
        article.as_ref().map(|a| a.language.clone()).unwrap_or_default()
    );
    let (hidden, set_hidden) = create_signal(
        article.as_ref().map(|a| a.hidden).unwrap_or(false)
    );
    let (image_data, set_image_data) = create_signal(None::<Vec<u8>>);
    let (image_preview, set_image_preview) = create_signal(None::<String>);
    let (is_loading, set_is_loading) = create_signal(false);
    let (error, set_error) = create_signal(None::<String>);
    let (success_message, set_success_message) = create_signal(None::<String>);
    let navigate = leptos_router::hooks::use_navigate();
    
    // Auto-hide success message after 3 seconds
    Effect::new(move |_| {
        if success_message.get().is_some() {
            let _timeout = Timeout::new(3000, move || {
                set_success_message.set(None);
            });
        }
    });
    
    // Handle image file selection
    let handle_image_change = move |ev: leptos::ev::Event| {
        let input = ev.target()
            .unwrap()
            .dyn_into::<web_sys::HtmlInputElement>()
            .unwrap();
        
        if let Some(files) = input.files() {
            if files.length() > 0 {
                let file = files.get(0).unwrap();
                
                // Create preview using leptos web utilities
                let reader = web_sys::FileReader::new().unwrap();
                let reader_clone = reader.clone();
                let set_preview = set_image_preview.clone();
                let set_data = set_image_data.clone();
                
                let closure = leptos::wasm_bindgen::closure::Closure::wrap(Box::new(move || {
                    let result = reader_clone.result().unwrap();
                    if let Ok(data_url) = result.dyn_into::<js_sys::JsString>() {
                        let data_url_str = data_url.as_string().unwrap();
                        set_preview.set(Some(data_url_str.clone()));
                        
                        // Extract base64 data from data URL
                        if let Some(base64_data) = data_url_str.strip_prefix("data:image/") {
                            if let Some(comma_pos) = base64_data.find(',') {
                                let base64_part = &base64_data[comma_pos + 1..];
                                if let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(base64_part) {
                                    set_data.set(Some(bytes));
                                }
                            }
                        }
                    }
                }) as Box<dyn FnMut()>);
                
                reader.set_onload(Some(closure.as_ref().unchecked_ref()));
                closure.forget(); // Prevent the closure from being dropped
                
                reader.read_as_data_url(&file).unwrap();
            }
        }
    };
    
    let handle_save = move |_| {
        let title_value = title.get();
        let content_value = content.get();
        
        if title_value.trim().is_empty() {
            set_error.set(Some("Title is required".to_string()));
            return;
        }
        
        if content_value.trim().is_empty() {
            set_error.set(Some("Content is required".to_string()));
            return;
        }
        
        set_is_loading.set(true);
        set_error.set(None);
        set_success_message.set(None);
        
        let title_clone = title_value.clone();
        let content_clone = content_value.clone();
        let language_value = language.get();
        let hidden_value = hidden.get();
        let article_for_async = article_clone.clone();
        let image_data_clone = image_data.get();
        
        spawn_local(async move {
            let result = if is_editing {
                let article_id = article_for_async.as_ref().unwrap().id;
                update_blog_article(
                    article_id,
                    Some(title_clone.clone()),
                    Some(content_clone.clone()),
                    Some(language_value.clone()),
                    Some(hidden_value),
                ).await
            } else {
                create_blog_article(
                    title_clone.clone(),
                    content_clone.clone(),
                    language_value.clone(),
                    hidden_value,
                ).await.map(|_| ())
            };
            
            // Handle image upload if image data was selected
            if let Some(img_data) = image_data_clone {
                let article_id = if is_editing {
                    article_for_async.as_ref().unwrap().id
                } else {
                    // For new articles, we need to get the ID from the creation response
                    // This is a limitation - we'd need to modify the API to return the article ID
                    // For now, we'll skip image upload for new articles
                    return;
                };
                
                // Upload image
                if let Err(e) = upload_blog_article_image(article_id, img_data).await {
                    log::warn!("Failed to upload image: {:?}", e);
                    // Don't fail the entire operation for image upload errors
                }
            }
            
            set_is_loading.set(false);
            
            match result {
                Ok(_) => {
                    if !is_editing {
                        let new_article = BlogArticle {
                            id: 0,
                            title: title_clone,
                            content: content_clone,
                            language: language_value.clone(),
                            hidden: hidden_value,
                            created_at: chrono::Utc::now().to_rfc3339(),
                            updated_at: chrono::Utc::now().to_rfc3339(),
                            has_image: Some(false),
                        };
                        set_success_message.set(Some("Article published successfully!".to_string()));
                        on_save.run(new_article);
                        
                        // Redirect to blog page after 2 seconds
                        let _timeout = Timeout::new(2000, move || {
                            let navigate = leptos_router::hooks::use_navigate();
                            let current_lang = crate::i18n::get_language_from_url();
                            let blog_path = match current_lang {
                                rust_shared::i18n::Language::Ru => "/ru/blog",
                                rust_shared::i18n::Language::En => "/en/blog",
                            };
                            navigate(blog_path, Default::default());
                        });
                    } else {
                        let mut updated_article = article_for_async.unwrap();
                        updated_article.title = title_clone;
                        updated_article.content = content_clone;
                        updated_article.language = language_value.clone();
                        updated_article.hidden = hidden_value;
                        updated_article.updated_at = chrono::Utc::now().to_rfc3339();
                        set_success_message.set(Some("Article updated successfully!".to_string()));
                        on_save.run(updated_article);
                        
                        // Redirect to blog page after 2 seconds
                        let _timeout = Timeout::new(2000, move || {
                            let navigate = leptos_router::hooks::use_navigate();
                            let current_lang = crate::i18n::get_language_from_url();
                            let blog_path = match current_lang {
                                rust_shared::i18n::Language::Ru => "/ru/blog",
                                rust_shared::i18n::Language::En => "/en/blog",
                            };
                            navigate(blog_path, Default::default());
                        });
                    }
                }
                Err(e) => {
                    let error_msg = match e {
                        crate::api::AuthError::NetworkError(_) => "Network connection error. Please check your internet connection.",
                        crate::api::AuthError::Other(msg) if msg.contains("PT500") => "Unexpected server error. Please try again later.",
                        crate::api::AuthError::Other(msg) if msg.contains("authentication") => "Authentication error. Please log in again.",
                        _ => "Failed to save article. Please try again later.",
                    };
                    set_error.set(Some(error_msg.to_string()));
                }
            }
        });
    };
    
    
    view! {
        <div class="max-w-4xl mx-auto p-4 sm:p-6 lg:p-8" id="article-form-container">
            <Card variant=CardVariant::Auth max_width="max-w-7xl" class="w-full" id="article-form-card">
                <CardHeader variant=CardVariant::Auth id="article-form-header">
                    {if is_editing { t8s!("Edit Article") } else { t8s!("Write New Article") }}
                </CardHeader>
                
                <CardContent id="article-form-content">
                    <div class="mb-4 sm:mb-6">
                        <p class="text-[var(--text-muted)] text-sm sm:text-base" id="form-description">
                            {if is_editing { t8s!("Update your article content and settings.") } else { t8s!("Share your thoughts and knowledge with the community.") }}
                        </p>
                    </div>
                    
                    <form class="flex flex-col gap-4 sm:gap-5 lg:gap-6" id="article-form" on:submit=move |ev| {
                        ev.prevent_default();
                        handle_save(());
                    } on:reset=move |_| {
                        navigate(t8s!("/en/blog"), Default::default());
                    }>
                        <div class="flex flex-col" id="title-field-container">
                            <CustomInput
                                placeholder=t8s!("Enter article title...")
                                value=title
                                on_change=set_title
                                disabled=is_loading
                                class="w-full".to_string()
                            />
                        </div>
                        
                        <div class="flex flex-col" id="content-field-container">
                            <textarea
                                id="article-content"
                                prop:value=move || content.get()
                                on:input=move |ev| set_content.set(event_target_value(&ev))
                                rows=8
                                class="w-full bg-[var(--input-bg)] border-2 border-[var(--input-border)] rounded-2xl p-4 sm:p-5 lg:p-6 text-[var(--text-muted)] text-sm sm:text-base font-medium font-['Inter'] transition-all duration-300 resize-vertical placeholder:text-[var(--text-muted)] focus:border-[var(--accent-primary)] focus:outline-none disabled:opacity-50 min-h-[200px] sm:min-h-[250px] lg:min-h-[300px]"
                                placeholder=t8s!("Write your article content here...")
                                disabled=is_loading
                            />
                        </div>
                        
                        <div class="flex flex-col" id="image-field-container">
                            <label for="article-image" class="text-[var(--text-muted)] text-sm font-medium mb-2" id="image-label">
                                {t8s!("Featured Image")}
                            </label>
                            <input
                                type="file"
                                id="article-image"
                                accept="image/*"
                                on:change=handle_image_change
                                disabled=is_loading
                                class="w-full bg-[var(--input-bg)] border-2 border-[var(--input-border)] rounded-2xl p-4 text-[var(--text-muted)] text-sm font-medium transition-all duration-300 focus:border-[var(--accent-primary)] focus:outline-none disabled:opacity-50 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-[var(--accent-primary)] file:text-white hover:file:bg-[var(--accent-primary)]/80"
                            />
                            
                            <Show when=move || image_preview.get().is_some()>
                                <div class="mt-4" id="image-preview-container">
                                    <img
                                        src=image_preview.get().unwrap()
                                        alt="Preview"
                                        class="w-full max-w-md h-48 object-cover rounded-xl border-2 border-[var(--input-border)]"
                                        id="image-preview"
                                    />
                                    <button
                                        type="button"
                                        on:click=move |_| {
                                            set_image_data.set(None);
                                            set_image_preview.set(None);
                                        }
                                        class="mt-2 px-3 py-1 bg-red-500/20 text-red-400 rounded-lg text-sm font-medium hover:bg-red-500/30 transition-colors"
                                        id="remove-image-button"
                                    >
                                        {t8s!("Remove Image")}
                                    </button>
                                </div>
                            </Show>
                        </div>
                        
                        <div class="flex flex-col" id="language-field-container">
                            <label for="article-language" class="text-[var(--text-muted)] text-sm font-medium mb-2" id="language-label">
                                {t8s!("Language")}
                            </label>
                            <Dropdown
                                selected=language
                                options=move || vec![Language::En, Language::Ru]
                                on_change=Callback::new(move |lang| set_language.set(lang))
                                display_fn=language_display_name
                                id="article-language"
                            />
                        </div>
                        
                        <div class="flex items-center gap-3" id="hidden-checkbox-container">
                            <input
                                type="checkbox"
                                id="article-hidden"
                                prop:checked=move || hidden.get()
                                on:change=move |ev| set_hidden.set(event_target_checked(&ev))
                                class="w-4 h-4 text-[var(--accent-primary)] bg-[var(--input-bg)] border-2 border-[var(--input-border)] rounded focus:ring-[var(--accent-primary)] focus:ring-2"
                                disabled=is_loading
                            />
                            <label for="article-hidden" class="text-[var(--text-muted)] text-sm font-medium" id="hidden-label">
                                {t8s!("Hide this article from public view")}
                            </label>
                        </div>
                        
                        <Show when=move || error.get().is_some()>
                            <div class="p-4 bg-red-500/10 border border-red-500/30 rounded-[10px] text-red-400 text-sm" id="form-error">
                                {error.get().unwrap()}
                            </div>
                        </Show>

                        <Show when=move || success_message.get().is_some()>
                            <div class="p-4 bg-green-500/10 border border-green-500/30 rounded-[10px] text-green-400 text-sm" id="form-success">
                                {success_message.get().unwrap()}
                            </div>
                        </Show>
                        
                        <div class="flex flex-col sm:flex-row gap-3 sm:gap-4 mt-4 sm:mt-6" id="form-buttons">
                            <button
                                type="submit"
                                class="flex-1 py-3 sm:py-4 px-4 sm:px-6 bg-[var(--accent-primary-gradient)] text-white rounded-xl sm:rounded-2xl font-medium transition-all duration-300 hover:opacity-80 disabled:opacity-50 text-sm sm:text-base"
                                disabled=is_loading
                                id="save-button"
                            >
                                {move || {
                                    if is_loading.get() {
                                        view! {
                                            <span class="flex items-center justify-center gap-2">
                                                <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                                                {t8s!("Saving...")}
                                            </span>
                                        }.into_any()
                                    } else {
                                        view! {
                                            {if is_editing { t8s!("Update Article") } else { t8s!("Publish Article") }}
                                        }.into_any()
                                    }
                                }}
                            </button>
                        </div>
                    </form>
                    
                </CardContent>
            </Card>
        </div>
    }
}

#[component]
pub fn PublicArticleList(
    #[prop(optional)] search_query: Option<String>,
) -> impl IntoView {
    let (articles, set_articles) = create_signal(Vec::<BlogArticle>::new());
    let (article_images, set_article_images) = create_signal(HashMap::<i64, String>::new());
    let (is_loading, set_is_loading) = create_signal(true);
    let (error, set_error) = create_signal(None::<String>);
    
    let load_articles = {
        let search_query = search_query.clone();
        move || {
            set_is_loading.set(true);
            set_error.set(None);
            
            let current_language = crate::i18n::get_language_from_url();
            let search = search_query.clone();
            
            spawn_local(async move {
                match get_blog_articles(Some(50), Some(0), search, Some(current_language)).await {
                    Ok(articles_data) => {
                        set_articles.set(articles_data.clone());
                        
                        // Load images for articles that have them
                        let mut images = HashMap::new();
                        for article in &articles_data {
                            if article.has_image.unwrap_or(false) {
                                match get_blog_article_image(article.id).await {
                                    Ok(image_bytes) => {
                                        let base64_image = base64::engine::general_purpose::STANDARD.encode(&image_bytes);
                                        let data_url = format!("data:image/jpeg;base64,{}", base64_image);
                                        images.insert(article.id, data_url);
                                    }
                                    Err(e) => {
                                        log::warn!("Failed to fetch image for article {}: {:?}", article.id, e);
                                    }
                                }
                            }
                        }
                        
                        set_article_images.set(images);
                    }
                    Err(e) => {
                        let error_msg = match e {
                            crate::api::AuthError::NetworkError(_) => "Network connection error. Please check your internet connection.",
                            crate::api::AuthError::Other(msg) if msg.contains("PGRST202") => "Server configuration error. Please try again later.",
                            crate::api::AuthError::Other(msg) if msg.contains("PT500") => "Unexpected server error. Please try again later.",
                            crate::api::AuthError::Other(msg) if msg.contains("authentication") => "Authentication error. Please log in again.",
                            _ => "Failed to load articles. Please try again later.",
                        };
                        set_error.set(Some(error_msg.to_string()));
                    }
                }
                set_is_loading.set(false);
            });
        }
    };
    
    Effect::new(move |_| {
        load_articles();
    });
    
    Effect::new(move |_| {
        search_query.clone();
        let load_articles = {
            let search_query = search_query.clone();
            move || {
                set_is_loading.set(true);
                set_error.set(None);
                
                let current_language = crate::i18n::get_language_from_url();
                let search = search_query.clone();
                
                spawn_local(async move {
                    match get_blog_articles(Some(50), Some(0), search, Some(current_language)).await {
                        Ok(articles_data) => {
                            set_articles.set(articles_data.clone());
                            
                            // Load images for articles that have them
                            let mut images = HashMap::new();
                            for article in &articles_data {
                                if article.has_image.unwrap_or(false) {
                                    match get_blog_article_image(article.id).await {
                                        Ok(image_bytes) => {
                                            let base64_image = base64::engine::general_purpose::STANDARD.encode(&image_bytes);
                                            let data_url = format!("data:image/jpeg;base64,{}", base64_image);
                                            images.insert(article.id, data_url);
                                        }
                                        Err(e) => {
                                            log::warn!("Failed to fetch image for article {}: {:?}", article.id, e);
                                        }
                                    }
                                }
                            }
                            
                            set_article_images.set(images);
                        }
                        Err(e) => {
                            let error_msg = match e {
                                crate::api::AuthError::NetworkError(_) => "Network connection error. Please check your internet connection.",
                                crate::api::AuthError::Other(msg) if msg.contains("PGRST202") => "Server configuration error. Please try again later.",
                                crate::api::AuthError::Other(msg) if msg.contains("PT500") => "Unexpected server error. Please try again later.",
                                crate::api::AuthError::Other(msg) if msg.contains("authentication") => "Authentication error. Please log in again.",
                                _ => "Failed to load articles. Please try again later.",
                            };
                            set_error.set(Some(error_msg.to_string()));
                        }
                    }
                    set_is_loading.set(false);
                });
            }
        };
        load_articles();
    });
    
    view! {
        <div class="max-w-4xl mx-auto p-4 sm:p-6 lg:p-8" id="public-articles-container">
            
            <Show when=move || error.get().is_some()>
                <div class="mb-6 p-4 bg-red-500/10 border border-red-500/30 rounded-[10px] text-red-400 text-sm" id="public-articles-error">
                    {error.get().unwrap()}
                </div>
            </Show>
            
            <Show when=move || is_loading.get()>
                <div class="flex justify-center items-center py-12" id="public-articles-loading">
                    <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--accent-primary)]"></div>
                    <span class="ml-3 text-[var(--text-muted)]">{t8s!("Loading articles...")}</span>
                </div>
            </Show>
            
            <Show when=move || !is_loading.get() && articles.get().is_empty()>
                <div class="text-center py-12 text-[var(--text-muted)]" id="public-articles-empty">
                    <p>{t8s!("No articles found.")}</p>
                </div>
            </Show>
            
            <Show when=move || !is_loading.get() && !articles.get().is_empty()>
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4" id="public-articles-list">
                    <For
                        each=move || articles.get()
                        key=|article| article.id
                            children=move |article: BlogArticle| {
                                let article_id = article.id;
                                let navigate = leptos_router::hooks::use_navigate();
                                let images = article_images.get();

                                let article_path = format!("{}{}", t8s!("/en/blog/article/"), article_id);
                                
                                let handle_article_click = move |_| {
                                    log::info!("handle_article_click: {}", article_id);
                                    navigate(&article_path, Default::default());
                                };
                                
                                let image_url = images.get(&article_id).cloned();
                                
                                view! {
                                    <div 
                                        class="relative w-full aspect-[335/380] bg-gradient-to-b from-[rgba(17,17,17,0.72)] to-[rgba(17,17,17,0.4)] rounded-2xl overflow-hidden hover:shadow-lg transition-all duration-300 cursor-pointer" 
                                        id=format!("public-article-{}", article.id)
                                        on:click=handle_article_click
                                    >
                                        {if let Some(img_url) = image_url {
                                            view! {
                                                <img 
                                                    src=img_url
                                                    alt=article.title.clone()
                                                    class="absolute top-2 left-2 w-[calc(100%-1rem)] right-2 h-[40%] object-cover rounded-xl"
                                                    id=format!("public-article-image-{}", article.id)
                                                />
                                            }.into_any()
                                        } else {
                                            view! {
                                                <div class="absolute top-2 left-2 right-2 h-[40%] 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-xl flex items-center justify-center" id=format!("public-article-image-{}", article.id)>
                                                    <div class="w-24 h-8 bg-[rgba(255,249,247,0.2)] rounded flex items-center justify-center" id=format!("public-article-logo-{}", article.id)>
                                                        <span class="text-[rgba(255,249,247,0.8)] text-sm font-semibold">vproxy</span>
                                                    </div>
                                                </div>
                                            }.into_any()
                                        }}
                                        
                                        <div class="absolute top-[45%] left-4 right-4 bottom-4 flex flex-col gap-3" id=format!("public-article-content-{}", article.id)>
                                            <div class="flex flex-col gap-2">
                                                <span class="text-[rgba(255,249,247,0.4)] text-xs font-bold uppercase tracking-wide" id=format!("public-article-date-{}", article.id)>
                                                    {format_date(&article.created_at)}
                                                </span>
                                                <h3 class="text-[rgba(255,249,247,0.95)] text-lg sm:text-xl font-semibold leading-tight tracking-tight" id=format!("public-article-title-{}", article.id)>
                                                    {article.title.clone()}
                                                </h3>
                                                <p class="text-[rgba(255,249,247,0.4)] text-sm leading-relaxed tracking-tight line-clamp-2" id=format!("public-article-description-{}", article.id)>
                                                    {article.content.clone()}
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                }
                            }
                    />
                </div>
            </Show>
        </div>
    }
}

#[component]
pub fn MyArticleList() -> impl IntoView {
    let auth = use_auth();
    let auth_clone = auth.clone();
    let (articles, set_articles) = create_signal(Vec::<BlogArticle>::new());
    let (article_images, set_article_images) = create_signal(HashMap::<i64, String>::new());
    let (is_loading, set_is_loading) = create_signal(true);
    let (error, set_error) = create_signal(None::<String>);
    
    let load_articles = move || {
        if !auth_clone.is_authenticated.get() || !auth_clone.is_admin() {
            set_is_loading.set(false);
            return;
        }
        
        set_is_loading.set(true);
        set_error.set(None);
        
        spawn_local(async move {
            match get_my_articles(Some(50), Some(0)).await {
                Ok(articles_data) => {
                    set_articles.set(articles_data.clone());
                    
                    // Load images for articles that have them
                    let mut images = HashMap::new();
                    for article in &articles_data {
                        if article.has_image.unwrap_or(false) {
                            match get_blog_article_image(article.id).await {
                                Ok(image_bytes) => {
                                    let base64_image = base64::engine::general_purpose::STANDARD.encode(&image_bytes);
                                    let data_url = format!("data:image/jpeg;base64,{}", base64_image);
                                    images.insert(article.id, data_url);
                                }
                                Err(e) => {
                                    log::warn!("Failed to fetch image for article {}: {:?}", article.id, e);
                                }
                            }
                        }
                    }
                    
                    set_article_images.set(images);
                }
                Err(e) => {
                    let error_msg = match e {
                        crate::api::AuthError::NetworkError(_) => "Network connection error. Please check your internet connection.",
                        crate::api::AuthError::Other(msg) if msg.contains("PGRST202") => "Server configuration error. Please try again later.",
                        crate::api::AuthError::Other(msg) if msg.contains("PT500") => "Unexpected server error. Please try again later.",
                        crate::api::AuthError::Other(msg) if msg.contains("authentication") => "Authentication error. Please log in again.",
                        _ => "Failed to load articles. Please try again later.",
                    };
                    set_error.set(Some(error_msg.to_string()));
                }
            }
            set_is_loading.set(false);
        });
    };
    
    Effect::new(move |_| {
        load_articles();
    });
    
    let (show_delete_confirm, set_show_delete_confirm) = create_signal(false);
    let (article_to_delete, set_article_to_delete) = create_signal(None::<i64>);
    let (is_deleting, set_is_deleting) = create_signal(false);

    let handle_delete_click = move |article_id: i64| {
        set_article_to_delete.set(Some(article_id));
        set_show_delete_confirm.set(true);
    };

    let handle_delete_confirm = move |_| {
        if let Some(article_id) = article_to_delete.get() {
            set_is_deleting.set(true);
            spawn_local(async move {
                match delete_blog_article(article_id).await {
                    Ok(_) => {
                        set_articles.update(|articles| {
                            articles.retain(|a| a.id != article_id);
                        });
                        set_show_delete_confirm.set(false);
                        set_article_to_delete.set(None);
                    }
                    Err(e) => {
                        let error_msg = match e {
                            crate::api::AuthError::NetworkError(_) => "Network connection error. Please check your internet connection.",
                            crate::api::AuthError::Other(msg) if msg.contains("PT500") => "Unexpected server error. Please try again later.",
                            crate::api::AuthError::Other(msg) if msg.contains("authentication") => "Authentication error. Please log in again.",
                            _ => "Failed to delete article. Please try again later.",
                        };
                        set_error.set(Some(error_msg.to_string()));
                    }
                }
                set_is_deleting.set(false);
            });
        }
    };

    let handle_delete_cancel = move |_| {
        set_show_delete_confirm.set(false);
        set_article_to_delete.set(None);
    };
    
    
        view! {
            <Show when=move || auth.is_authenticated.get() && auth.is_admin()>
                <div class="max-w-4xl mx-auto p-4 sm:p-6 lg:p-8" id="my-articles-container">
                
                <Show when=move || error.get().is_some()>
                    <div class="mb-6 p-4 bg-red-500/10 border border-red-500/30 rounded-[10px] text-red-400 text-sm" id="my-articles-error">
                        {error.get().unwrap()}
                    </div>
                </Show>
                
                    <Show when=move || is_loading.get()>
                        <div class="flex justify-center items-center py-12" id="my-articles-loading">
                            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--accent-primary)]"></div>
                            <span class="ml-3 text-[var(--text-muted)]">{t8s!("Loading articles...")}</span>
                        </div>
                    </Show>
                
                <Show when=move || !is_loading.get() && articles.get().is_empty()>
                    <div class="text-center py-12 text-[var(--text-muted)]" id="my-articles-empty">
                        <p>{t8s!("No articles found.")}</p>
                    </div>
                </Show>
                
                <Show when=move || !is_loading.get() && !articles.get().is_empty()>
                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4" id="my-articles-list">
                        <For
                            each=move || articles.get()
                            key=|article| article.id
                            children=move |article: BlogArticle| {
                                let article_id = article.id;
                                let article_path = format!("{}{}", t8s!("/en/blog/article/"), article_id);
                                let navigate = leptos_router::hooks::use_navigate();
                                let images = article_images.get();
                                
                                let handle_article_click = move |_| {
                                    log::info!("handle_article_click: {}", article_id);
                                    navigate(&article_path, Default::default());
                                };

                                let image_url = images.get(&article_id).cloned();

                                view! {
                                    <div class="relative w-full aspect-[335/380] bg-gradient-to-b from-[rgba(17,17,17,0.72)] to-[rgba(17,17,17,0.4)] rounded-2xl overflow-hidden hover:shadow-lg transition-all duration-300" 
                                         id=format!("my-article-{}", article.id)
                                         on:click=handle_article_click
                                    >
                                        {if let Some(img_url) = image_url {
                                            view! {
                                                <img 
                                                    src=img_url
                                                    alt=article.title.clone()
                                                    class="absolute top-2 left-2 right-2 h-[40%] w-[calc(100%-1rem)] object-cover rounded-xl"
                                                    id=format!("my-article-image-{}", article.id)
                                                />
                                            }.into_any()
                                        } else {
                                            view! {
                                                <div class="absolute top-2 left-2 right-2 h-[40%] 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-xl flex items-center justify-center" id=format!("my-article-image-{}", article.id)>
                                                    <div class="w-24 h-8 bg-[rgba(255,249,247,0.2)] rounded flex items-center justify-center" id=format!("my-article-logo-{}", article.id)>
                                                        <span class="text-[rgba(255,249,247,0.8)] text-sm font-semibold">vproxy</span>
                                                    </div>
                                                </div>
                                            }.into_any()
                                        }}
                                        
                                        // Content container
                                        <div class="absolute top-[45%] left-4 right-4 bottom-4 flex flex-col gap-3" id=format!("my-article-content-{}", article.id)>
                                            <div class="flex flex-col gap-2">
                                                <div class="flex items-center justify-between">
                                                    <span class="text-[rgba(255,249,247,0.4)] text-xs font-bold uppercase tracking-wide" id=format!("my-article-date-{}", article.id)>
                                                        {format_date(&article.created_at)}
                                                    </span>
                                                    {if article.hidden {
                                                        view! {
                                                            <span class="px-2 py-1 bg-[rgba(255,193,7,0.2)] text-[rgba(255,193,7,0.8)] rounded-full text-xs font-medium" id=format!("my-article-hidden-{}", article.id)>
                                                                {t8s!("Hidden")}
                                                            </span>
                                                        }.into_any()
                                                    } else {
                                                        ().into_any()
                                                    }}
                                                </div>
                                                <h3 class="text-[rgba(255,249,247,0.95)] text-lg sm:text-xl font-semibold leading-tight tracking-tight" id=format!("my-article-title-{}", article.id)>
                                                    {article.title.clone()}
                                                </h3>
                                                <p class="text-[rgba(255,249,247,0.4)] text-sm leading-relaxed tracking-tight line-clamp-2" id=format!("my-article-description-{}", article.id)>
                                                    {article.content.clone()}
                                                </p>
                                            </div>
                                            
                                            // Action buttons
                                            <div class="flex gap-2 mt-2" id=format!("my-article-actions-{}", article.id)>
                                                <a
                                                    href=format!("/en/blog/edit/{}", article.id)
                                                    class="flex-1 px-3 py-1 text-xs bg-[rgba(59,130,246,0.8)] text-white rounded-lg hover:opacity-80 transition-all duration-300 no-underline text-center"
                                                    id=format!("edit-button-{}", article.id)
                                                >
                                                    {t8s!("Edit")}
                                                </a>
                                                <button
                                                    type="button"
                                                    class="flex-1 px-3 py-1 text-xs bg-[rgba(239,68,68,0.8)] text-white rounded-lg hover:opacity-80 transition-all duration-300"
                                                    on:click=move |_| handle_delete_click(article.id)
                                                    id=format!("delete-button-{}", article.id)
                                                >
                                                    {t8s!("Delete")}
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                }
                            }
                        />
                    </div>
                </Show>
            </div>
        </Show>

        // Delete confirmation modal
        <Show when=move || show_delete_confirm.get()>
            <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" id="delete-modal-overlay">
                <div class="bg-[#2d2c2c] border-2 border-[var(--card-border)] rounded-2xl p-6 max-w-md mx-4" id="delete-modal">
                    <div class="text-center">
                        <h3 class="text-lg font-semibold text-[var(--text-primary)] mb-4" id="delete-modal-title">
                            {t8s!("Confirm Deletion")}
                        </h3>
                        <p class="text-[var(--text-muted)] mb-6" id="delete-modal-message">
                            {t8s!("Are you sure you want to delete this article? This action cannot be undone.")}
                        </p>
                        <div class="flex gap-3 justify-center">
                            <button
                                type="button"
                                class="px-6 py-2 bg-[var(--input-bg)] border-2 border-[var(--input-border)] text-[var(--text-muted)] rounded-xl font-medium transition-all duration-300 hover:bg-[var(--input-border)] disabled:opacity-50"
                                on:click=handle_delete_cancel
                                disabled=is_deleting
                                id="delete-cancel-button"
                            >
                                {t8s!("Cancel")}
                            </button>
                            <button
                                type="button"
                                class="px-6 py-2 bg-[rgba(239,68,68,0.8)] text-white rounded-xl font-medium transition-all duration-300 hover:opacity-80 disabled:opacity-50"
                                on:click=handle_delete_confirm
                                disabled=is_deleting
                                id="delete-confirm-button"
                            >
                                {move || {
                                    if is_deleting.get() {
                                        view! {
                                            <span class="flex items-center gap-2">
                                                <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                                                {t8s!("Deleting...")}
                                            </span>
                                        }.into_any()
                                    } else {
                                        view! {
                                            {t8s!("Delete")}
                                        }.into_any()
                                    }
                                }}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </Show>
    }
}

#[component]
pub fn ArticlePage() -> impl IntoView {
    let params = use_params_map();
    let navigate = use_navigate();
    let navigate_clone = navigate.clone();
    
    let (article, set_article) = create_signal(None::<BlogArticle>);
    let (article_image, set_article_image) = create_signal(None::<String>);
    let (is_loading, set_is_loading) = create_signal(true);
    let (error, set_error) = create_signal(None::<String>);
    
    let url = t8s!("/en/blog");
    
    let load_article = move || {
        if let Some(id_str) = params.get().get("id") {
            if let Ok(article_id) = id_str.parse::<i64>() {
                set_is_loading.set(true);
                set_error.set(None);
                
                spawn_local(async move {
                    match get_blog_article(article_id).await {
                        Ok(article_data) => {
                            set_article.set(Some(article_data.clone()));
                            
                            // Load image if article has one
                            if article_data.has_image.unwrap_or(false) {
                                match get_blog_article_image(article_id).await {
                                    Ok(image_bytes) => {
                                        let base64_image = base64::engine::general_purpose::STANDARD.encode(&image_bytes);
                                        let data_url = format!("data:image/jpeg;base64,{}", base64_image);
                                        set_article_image.set(Some(data_url));
                                    }
                                    Err(e) => {
                                        log::warn!("Failed to fetch image for article {}: {:?}", article_id, e);
                                    }
                                }
                            }
                        }
                        Err(e) => {
                            let error_msg = match e {
                                crate::api::AuthError::NetworkError(_) => "Network connection error. Please check your internet connection.",
                                crate::api::AuthError::Other(msg) if msg.contains("PGRST202") => "Article not found.",
                                crate::api::AuthError::Other(msg) if msg.contains("PT500") => "Unexpected server error. Please try again later.",
                                crate::api::AuthError::Other(msg) if msg.contains("authentication") => "Authentication error. Please log in again.",
                                _ => "Failed to load article. Please try again later.",
                            };
                            set_error.set(Some(error_msg.to_string()));
                        }
                    }
                    set_is_loading.set(false);
                });
            } else {
                set_error.set(Some("Invalid article ID".to_string()));
                set_is_loading.set(false);
            }
        } else {
            set_error.set(Some("Article ID not found".to_string()));
            set_is_loading.set(false);
        }
    };
    
    Effect::new(move |_| {
        load_article();
    });
    
    view! {
        <PageContent /*class="max-w-4xl mx-auto p-4 sm:p-6 lg:p-8"*/ id="article-page-container">
            <Show when=move || error.get().is_some()>
                <div class="mb-6 p-4 bg-red-500/10 border border-red-500/30 rounded-[10px] text-red-400 text-sm" id="article-error">
                    {error.get().unwrap()}
                </div>
            </Show>
            
            <Show when=move || is_loading.get()>
                <div class="flex justify-center items-center py-12" id="article-loading">
                    <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--accent-primary)]"></div>
                    <span class="ml-3 text-[var(--text-muted)]">{t8s!("Loading article...")}</span>
                </div>
            </Show>
            
            <Show when=move || !is_loading.get() && article.get().is_some()>
                <div class="flex flex-col items-start p-0 gap-8 w-full max-w-[600px] mx-auto" id="article-container">
                    // Navigation
                    <div class="flex flex-row items-center p-0 gap-2 w-[77px] h-[22px] rounded-[999px]" id="article-navigation">
                        {
                            let navigate = leptos_router::hooks::use_navigate();
                            let url = t8s!("/en/blog");

                            view! {
                                <button
                                    class="flex items-center gap-2 text-[rgba(255,249,247,0.4)] hover:text-[rgba(255,249,247,0.6)] transition-colors duration-200"
                                    on:click=move |_| {
                                        navigate(&url, Default::default());
                                    }
                                    id="article-back-button"
                                >
                                    <svg class="w-[22px] h-[22px]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                                    </svg>
                                    <span class="text-[16px] font-semibold leading-[22px] tracking-[-0.02em] text-center" id="back-text">
                                        {t8s!("Back")}
                                    </span>
                                </button>
                            }
                        }
                    </div>
                    
                    // Image
                    <Show when=move || article_image.get().is_some()>
                        <div class="w-[600px] h-[336px] 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-[14px] overflow-hidden" id="article-image-container">
                            <img 
                                src=article_image.get().unwrap()
                                alt=move || article.get().map(|a| a.title.clone()).unwrap_or_default()
                                class="w-full h-full object-cover"
                                id="article-image"
                            />
                        </div>
                    </Show>
                    
                    <Show when=move || article_image.get().is_none()>
                        <div class="w-[600px] h-[336px] 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-[14px] flex items-center justify-center" id="article-image-placeholder">
                            <div class="w-24 h-8 bg-[rgba(255,249,247,0.2)] rounded flex items-center justify-center">
                                <span class="text-[rgba(255,249,247,0.8)] text-sm font-semibold">vproxy</span>
                            </div>
                        </div>
                    </Show>
                    
                    // Date
                    <div class="w-[82px] h-[24px]" id="article-date-container">
                        <span class="text-[18px] font-normal leading-[24px] tracking-[-0.02em] text-[rgba(255,249,247,0.4)]" id="article-date">
                            {move || article.get().map(|a| format_date(&a.created_at)).unwrap_or_default()}
                        </span>
                    </div>
                    
                    // Title
                    <div class="w-[600px] h-auto" id="article-title-container">
                        <h1 class="text-[48px] font-semibold leading-[54px] tracking-[-0.02em] text-[rgba(255,249,247,0.95)]" id="article-title">
                            {move || article.get().map(|a| a.title.clone()).unwrap_or_default()}
                        </h1>
                    </div>
                    
                    // Content Container
                    <div class="flex flex-col items-start p-0 gap-8 w-[600px]" id="article-content-container">
                        <div class="w-[600px] h-auto" id="article-content">
                            <div class="text-[18px] font-normal leading-[24px] tracking-[-0.02em] text-[rgba(255,249,247,0.6)] whitespace-pre-wrap" id="article-body">
                                {move || article.get().map(|a| a.content.clone()).unwrap_or_default()}
                            </div>
                        </div>
                    </div>
                </div>
            </Show>
        </PageContent>
    }
}
