use leptos::prelude::*;
use leptos::task::spawn_local;
use leptos_router::{hooks::{use_location, use_params_map}};
use crate::components::layout::PageContent;
use crate::components::blog::{WriteArticleButton, ArticleForm, PublicArticleList, MyArticleList};
use crate::components::input::CustomInput;
use crate::api::{can_edit_article, get_blog_article};
use crate::page::prelude::*;

#[component]
pub fn BlogPage() -> impl IntoView {
    let location = use_location();
    let params = use_params_map();
    
    let is_write_page = move || location.pathname.get().contains("/write");
    let is_edit_page = move || location.pathname.get().contains("/edit");
    
    // Access control for edit page
    let (can_edit, set_can_edit) = create_signal(None::<bool>);
    let (access_error, set_access_error) = create_signal(None::<String>);
    let (is_checking_access, set_is_checking_access) = create_signal(false);
    
    // Article data for editing
    let (article_data, set_article_data) = create_signal(None::<crate::api::BlogArticle>);
    let (is_loading_article, set_is_loading_article) = create_signal(false);
    
    // Check access when on edit page
    Effect::new(move |_| {
        if is_edit_page() {
            if let Some(id_str) = params.get().get("id") {
                if let Ok(article_id) = id_str.parse::<i64>() {
                    set_is_checking_access.set(true);
                    set_access_error.set(None);
                    
                    spawn_local(async move {
                        match can_edit_article(article_id).await {
                            Ok(can_edit_result) => {
                                set_can_edit.set(Some(can_edit_result));
                                if !can_edit_result {
                                    set_access_error.set(Some("You don't have permission to edit this article".to_string()));
                                } else {
                                    // Load article data for editing
                                    set_is_loading_article.set(true);
                                    match get_blog_article(article_id).await {
                                        Ok(article) => {
                                            set_article_data.set(Some(article));
                                        }
                                        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("PT404") => "Article not found.",
                                                crate::api::AuthError::Other(msg) if msg.contains("authentication") => "Please log in to edit articles.",
                                                _ => "Failed to load article. Please try again later.",
                                            };
                                            set_access_error.set(Some(error_msg.to_string()));
                                        }
                                    }
                                    set_is_loading_article.set(false);
                                }
                            }
                            Err(e) => {
                                set_can_edit.set(Some(false));
                                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("PT404") => "Article not found.",
                                    crate::api::AuthError::Other(msg) if msg.contains("authentication") => "Please log in to edit articles.",
                                    _ => "Failed to check article access. Please try again later.",
                                };
                                set_access_error.set(Some(error_msg.to_string()));
                            }
                        }
                        set_is_checking_access.set(false);
                    });
                } else {
                    set_access_error.set(Some("Invalid article ID".to_string()));
                }
            }
        } else {
            // Reset state when not on edit page
            set_can_edit.set(None);
            set_access_error.set(None);
            set_is_checking_access.set(false);
            set_article_data.set(None);
            set_is_loading_article.set(false);
        }
    });
    
    let (search_query, set_search_query) = create_signal(String::new());
    
    view! {
        <PageContent>
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8" id="blog-content">
                {move || {
                    if is_write_page() {
                        // Write page - no access check needed
                        view! {
                            <ArticleForm
                                on_save=Callback::new(move |_article| {
                                    // Navigate back to blog list after saving
                                    let navigate = leptos_router::hooks::use_navigate();
                                    navigate(t8s!("/en/blog"), Default::default());
                                })
                                on_cancel=Callback::new(move |_| {
                                    // Navigate back to blog list
                                    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());
                                })
                            />
                        }.into_any()
                    } else if is_edit_page() {
                        // Edit page - check access first
                        if is_checking_access.get() {
                            view! {
                                <div class="flex justify-center items-center py-12" id="access-checking">
                                    <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!("Checking access...")}</span>
                                </div>
                            }.into_any()
                        } else if let Some(error) = access_error.get() {
                            view! {
                                <div class="max-w-2xl mx-auto text-center py-12" id="access-denied">
                                    <div class="p-6 bg-red-500/10 border border-red-500/30 rounded-2xl">
                                        <h2 class="text-xl font-semibold text-red-400 mb-4">{t8s!("Access Denied")}</h2>
                                        <p class="text-red-300 mb-6">{error}</p>
                                        <a
                                            href="/en/blog"
                                            class="inline-flex items-center px-6 py-3 bg-[var(--accent-primary-gradient)] text-white rounded-xl font-medium transition-all duration-300 hover:opacity-80 no-underline"
                                        >
                                            {t8s!("Back to Articles")}
                                        </a>
                                    </div>
                                </div>
                            }.into_any()
                        } else if can_edit.get() == Some(true) {
                            if is_loading_article.get() {
                                view! {
                                    <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>
                                }.into_any()
                            } else if let Some(article) = article_data.get() {
                                view! {
                                    <ArticleForm
                                        article=article
                                        on_save=Callback::new(move |_article| {
                                            // Navigate back to blog list after saving
                                            let navigate = leptos_router::hooks::use_navigate();
                                            navigate(t8s!("/en/blog"), Default::default());
                                        })
                                        on_cancel=Callback::new(move |_| {
                                            // Navigate back to blog list
                                            let navigate = leptos_router::hooks::use_navigate();
                                            navigate(t8s!("/en/blog"), Default::default());
                                        })
                                    />
                                }.into_any()
                            } else {
                                view! {
                                    <div class="flex justify-center items-center py-12" id="article-loading">
                                        <span class="text-[var(--text-muted)]">{t8s!("Loading...")}</span>
                                    </div>
                                }.into_any()
                            }
                        } else {
                            view! {
                                <div class="flex justify-center items-center py-12" id="access-loading">
                                    <span class="text-[var(--text-muted)]">{t8s!("Loading...")}</span>
                                </div>
                            }.into_any()
                        }
                    } else {
                            view! {
                                <div class="space-y-6" id="blog-main-content">
                                    <div class="flex flex-col sm:flex-row sm:justify-center sm:items-center gap-4" id="blog-header">
                                        <div class="w-full max-w-md">
                                            <CustomInput
                                                placeholder=t8s!("Search articles...")
                                                value=search_query
                                                on_change=set_search_query
                                                class="w-full".to_string()
                                            />
                                        </div>
                                        <WriteArticleButton />
                                    </div>
                                
                                    <MyArticleList />
                                    <PublicArticleList search_query=search_query.get() />
                            </div>
                        }.into_any()
                    }
                }}
            </div>
        </PageContent>
    }
}
