use serde::{Deserialize, Serialize};
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::spawn_local;
use web_sys::{window, MouseEvent, ScrollBehavior, ScrollToOptions};
use yew::prelude::*;

// Tauri 'invoke' Funktion deklarieren
#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_namespace = ["window", "__TAURI__", "core"], catch)]
    async fn invoke(cmd: &str, args: JsValue) -> Result<JsValue, JsValue>;
}

// Wir definieren Post lokal, damit Yew weiß, wie die JSON-Daten vom Backend aussehen
// In src/pages/home.rs
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub struct Post {
    pub content: String,
    pub author: String,
    pub created_at: u64,
}

#[function_component(Home)]
pub fn home() -> Html {
    let posts = use_state(|| None::<Vec<Post>>);
    let error = use_state(|| false);
    let hashtag_input = use_state(|| String::new());
    let active_tags = use_state(Vec::<String>::new);

    let load_posts = {
        let posts = posts.clone();
        let error = error.clone();
        let active_tags = active_tags.clone();
        Callback::from(move |_e: MouseEvent| {
            let posts = posts.clone();
            let error = error.clone();
            let tags = (*active_tags).clone();

            // UI zurücksetzen & Scrollen
            posts.set(None);
            error.set(false);
            if let Some(win) = window() {
                let options = ScrollToOptions::new();
                options.set_top(0.0);
                options.set_behavior(ScrollBehavior::Smooth);
                let _ = win.scroll_to_with_scroll_to_options(&options);
            }

            spawn_local(async move {
                #[derive(Serialize)]
                struct HashtagArgs {
                    hashtags: Vec<String>,
                }
                let args = serde_wasm_bindgen::to_value(&HashtagArgs { hashtags: tags }).unwrap();

                // Daten vom Rust-Backend anfordern
                match invoke("fetch_nostr_posts", args).await {
                    Ok(res) => {
                        // JSON-Resultat in Vec<Post> umwandeln
                        if let Ok(new_posts) = serde_wasm_bindgen::from_value::<Vec<Post>>(res) {
                            posts.set(Some(new_posts));
                        } else {
                            error.set(true);
                        }
                    }
                    Err(_) => {
                        error.set(true);
                    }
                }
            });
        })
    };

    // Initiales Laden beim Start
    {
        let load_posts = load_posts.clone();
        use_effect_with((), move |_| {
            load_posts.emit(MouseEvent::new("click").unwrap());
            || ()
        });
    }

    html! {
        <div class="feed-container">
            <div class="feed-header">
                <div class="header-main">
                    <h1 class="feed-title">{"✨ Entdecken"}</h1>
                    <button class="reload-btn" onclick={load_posts.clone()}>
                        {"🔄"}
                    </button>
                </div>
            </div>

            <div class="hashtag-section">
                <div class="hashtag-input-row">
                    <input
                        type="text"
                        class="hashtag-input"
                        placeholder="Tags hinzufügen (z.B. bitcoin, rust)..."
                        value={(*hashtag_input).clone()}
                        oninput={
                            let hashtag_input = hashtag_input.clone();
                            move |e: InputEvent| {
                                let target: web_sys::HtmlInputElement = e.target_unchecked_into();
                                hashtag_input.set(target.value());
                            }
                        }
                        onkeydown={
                            let hashtag_input = hashtag_input.clone();
                            let active_tags = active_tags.clone();
                            let load_posts = load_posts.clone();
                            move |e: KeyboardEvent| {
                                if e.key() == "Enter" {
                                    let val = (*hashtag_input).trim().to_string();
                                    if !val.is_empty() {
                                        let mut tags = (*active_tags).clone();
                                        // Mehrere Tags per Komma trennen
                                        for t in val.split(',').map(|s| s.trim()).filter(|s| !s.is_empty()) {
                                            if !tags.contains(&t.to_string()) {
                                                tags.push(t.to_string());
                                            }
                                        }
                                        active_tags.set(tags);
                                        hashtag_input.set(String::new());
                                        load_posts.emit(MouseEvent::new("click").unwrap());
                                    }
                                }
                            }
                        }
                    />
                </div>
                if !active_tags.is_empty() {
                    <div class="tag-chips">
                        { for active_tags.iter().map(|t| {
                            let t_clone = t.clone();
                            let active_tags = active_tags.clone();
                            let load_posts = load_posts.clone();
                            let remove = move |_| {
                                let mut tags = (*active_tags).clone();
                                tags.retain(|x| x != &t_clone);
                                active_tags.set(tags);
                                load_posts.emit(MouseEvent::new("click").unwrap());
                            };
                            html! {
                                <span class="tag-chip" onclick={remove}>
                                    { format!("#{}", t) }
                                    <span class="tag-remove">{"×"}</span>
                                </span>
                            }
                        }) }
                    </div>
                }
            </div>

            {
                if *error {
                    html! { <p class="status-msg">{"Fehler beim Laden der Posts."}</p> }
                } else if let Some(ref posts_list) = *posts {
                    html! {
                        <div class="posts-list">
                            { for posts_list.iter().map(|p| html! { <PostCard post={p.clone()} /> }) }
                            <div class="footer-action">
                                <button class="reload-btn-large" onclick={load_posts}>
                                    {"Nach oben & Neu laden"}
                                </button>
                            </div>
                        </div>
                    }
                } else {
                    html! { <p class="status-msg">{"Verbinde mit Nostr über Tauri..."}</p> }
                }
            }
        </div>
    }
}

#[derive(Properties, PartialEq)]
pub struct PostProps {
    pub post: Post,
}

#[function_component(PostCard)]
pub fn post_card(props: &PostProps) -> Html {
    let post = &props.post;
    html! {
        <div class="post-card">
            <div class="post-header">
                <span class="post-author">{ format!("{:.8}...", post.author) }</span>
                <span class="post-date">{ post.created_at }</span>
            </div>
            <div class="post-content">{ &post.content }</div>
        </div>
    }
}
