use log::info;
//use std::env;
//use log::Level;
use reqwasm::http::Request;
use serde::{Deserialize, Serialize};
use serde_json;
use sycamore::futures::spawn_local;
use sycamore::prelude::*;
//use sycamore::suspense::Suspense;
//use sycamore_router::Route;
use dotenv_codegen::dotenv;
use itertools::Itertools;
use std::collections::HashMap;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::JsCast;
use web_sys::{Event, EventTarget, HtmlInputElement, KeyboardEvent}; // 0.3.5
                                                                    //use gloo_timers::future::TimeoutFuture;
                                                                    //#[macro_use]
                                                                    //extern crate dotenv_codegen;

#[derive(Deserialize, Serialize, Debug, Default, Clone, PartialEq, Hash, Eq)]
pub struct BookUI {
    id: i32,
    open_library_key: Option<String>,
    title: String,
    edition_count: Option<i32>,
    first_publish_year: Option<i32>,
    median_page_count: Option<i32>,
    goodread_id: Option<String>,
    description: Option<String>,
    cover: Option<String>,
    location: Option<String>,
    time_added: Option<String>,
    rating: Option<i32>,
    comments: Option<String>,
    author_name: Option<Vec<String>>,
    person: Option<Vec<String>>,
    place: Option<Vec<String>>,
    subject: Option<Vec<String>>,
    time: Option<Vec<String>>,
    isbn: Option<Vec<String>>,
}

#[derive(Prop, Debug)]
pub struct BookUIProp {
    bookitem: BookUI,
}

#[derive(Prop, Debug, Clone, PartialEq, Hash, Eq)]
pub struct StringProp {
    value: String,
}

#[derive(Deserialize, Serialize, Debug, Clone)]
struct PaginatedBookUIList {
    num_pages: u32,
    books: Vec<BookUI>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AxumUser {
    pub id: i32,
    pub password_hash: String,
    pub name: String,
}

#[derive(Debug, Default, Clone)]
pub struct AppState {
    pub books: RcSignal<Vec<BookUI>>,
    pub search: RcSignal<String>,
    pub openlibrary: RcSignal<bool>,
    pub internalsearch: RcSignal<bool>,
    pub pagedisplay: RcSignal<u32>,
    pub pagenum: RcSignal<u32>,
    pub maxpage: RcSignal<u32>,
    pub adding: RcSignal<bool>,
    pub updating: RcSignal<bool>,
    pub displaying: RcSignal<bool>,
    pub addingbook: RcSignal<BookUI>,
    pub displayingbook: RcSignal<BookUI>,
    pub refreshing: RcSignal<bool>,
    pub apibook: RcSignal<BookUI>,
    pub updatingrequest: RcSignal<bool>,
    pub addingrequest: RcSignal<bool>,
    pub deleteid: RcSignal<i32>,
    pub deleterequest: RcSignal<bool>,
    pub userlist: RcSignal<HashMap<String, i32>>,
    pub userid: RcSignal<i32>,
    pub selectedusername: RcSignal<String>,
    pub loggedusername: RcSignal<String>,
    pub useridloggedin: RcSignal<i32>,
    pub userscreen: RcSignal<bool>,
    pub loggedin: RcSignal<bool>,
    pub editmode: RcSignal<bool>,
    pub dropdownselect: RcSignal<bool>,
    pub scrolling: RcSignal<bool>,
    pub scrollevent: RcSignal<bool>,
    pub menuexpand: RcSignal<bool>,
    pub warningmsg: RcSignal<String>,
}

async fn login_user(user: AxumUser) -> Result<reqwasm::http::Response, reqwasm::Error> {
    let backend_url: &'static str = dotenv!("BACKEND_URL");
    let url = format!("{}/api/login", backend_url);
    let resp = Request::post(&url)
        .body(serde_wasm_bindgen::to_value(&serde_json::to_string(&user).unwrap()).unwrap())
        .header("content-type", "application/json")
        .send()
        .await?;
    Ok(resp)
}

async fn register_user(user: AxumUser) -> Result<reqwasm::http::Response, reqwasm::Error> {
    let backend_url: &'static str = dotenv!("BACKEND_URL");
    let url = format!("{}/api/register", backend_url);
    let resp = Request::post(&url)
        .body(serde_wasm_bindgen::to_value(&serde_json::to_string(&user).unwrap()).unwrap())
        .header("content-type", "application/json")
        .send()
        .await?;
    Ok(resp)
}

async fn logout_user() -> Result<reqwasm::http::Response, reqwasm::Error> {
    let backend_url: &'static str = dotenv!("BACKEND_URL");
    let url = format!("{}/api/logout", backend_url);
    let resp = Request::post(&url).send().await?;
    Ok(resp)
}

async fn list_users() -> Result<HashMap<String, i32>, reqwasm::Error> {
    let backend_url: &'static str = dotenv!("BACKEND_URL");
    let url = format!("{}/api/list_users", backend_url);
    let resp = Request::get(&url).send().await?;
    let users = resp.json::<Vec<AxumUser>>().await?;
    let mut res = HashMap::new();
    for user in users {
        res.insert(user.name, user.id);
    }
    Ok(res)
}
/*
async fn refresh_index() -> Result<reqwasm::http::Response, reqwasm::Error> {
    let backend_url: &'static str = dotenv!("BACKEND_URL");
    let url = format!("{}/api/refresh_search_index", backend_url);
    let resp = Request::get(&url).send().await?;
    Ok(resp)
}
*/
async fn authentication_check() -> Result<bool, reqwasm::Error> {
    let backend_url: &'static str = dotenv!("BACKEND_URL");
    let url = format!("{}/api/authentication_check", backend_url);
    let resp = Request::get(&url).send().await?;
    if resp.status() == 200 {
        Ok(true)
    } else {
        Ok(false)
    }
}

async fn fetch_books(search: String) -> Result<Vec<BookUI>, reqwasm::Error> {
    //dotenvy::dotenv().ok();
    let backend_url: &'static str = dotenv!("BACKEND_URL");
    //env::var("BACKEND_URL").expect("BACKEND_URL is not set in .env file");
    let url = format!("{}/api/search_openlibrary?search={}", backend_url, search);
    let resp = Request::get(&url).send().await?;
    println!("Fetching books\n");
    if resp.status() == 200 {
        let body = resp.json::<Vec<BookUI>>().await?;
        Ok(body)
    } else {
        Ok(Vec::new())
    }
}

async fn search_books(
    search: String,
    page: u32,
    userid: i32,
) -> Result<PaginatedBookUIList, reqwasm::Error> {
    let backend_url: &'static str = dotenv!("BACKEND_URL");
    //"http://localhost:8081";
    //env::var("BACKEND_URL").expect("BACKEND_URL is not set in .env file");
    let url = format!(
        "{}/api/list_search?search={}&page={}&userid={}",
        backend_url, search, page, userid
    );
    let resp = Request::get(&url).send().await?;
    println!("Fetching books\n");
    let body = resp.json::<PaginatedBookUIList>().await?;
    Ok(body)
}

async fn add_book(record: BookUI) -> Result<reqwasm::http::Response, reqwasm::Error> {
    let backend_url: &'static str = dotenv!("BACKEND_URL");
    //env::var("BACKEND_URL").expect("BACKEND_URL is not set in .env file");
    let url = format!("{}/api/create", backend_url);
    let resp = Request::post(&url)
        .body(serde_wasm_bindgen::to_value(&serde_json::to_string(&record).unwrap()).unwrap())
        .header("content-type", "application/json")
        .send()
        .await?;
    Ok(resp)
}
/*
async fn add_books_isbns(isbns: String) -> Result<reqwasm::http::Response,  reqwasm::Error> {
    let backend_url : &'static str = dotenv!("BACKEND_URL");
    //env::var("BACKEND_URL").expect("BACKEND_URL is not set in .env file");
    let url = format!("{}/api/create_by_isbn?isbns={}", backend_url, isbns);
    let resp = Request::get(&url).send().await?;
    println!("Adding multiple books\n");
    Ok(resp)
}
*/

async fn update_book(record: BookUI) -> Result<reqwasm::http::Response, reqwasm::Error> {
    let backend_url: &'static str = dotenv!("BACKEND_URL");
    //env::var("BACKEND_URL").expect("BACKEND_URL is not set in .env file");
    let url = format!("{}/api/update", backend_url);
    let resp = Request::post(&url)
        .body(serde_wasm_bindgen::to_value(&serde_json::to_string(&record).unwrap()).unwrap())
        .header("content-type", "application/json")
        .send()
        .await?;
    Ok(resp)
}

async fn delete_book(id: i32) -> Result<reqwasm::http::Response, reqwasm::Error> {
    let backend_url: &'static str = dotenv!("BACKEND_URL");
    //env::var("BACKEND_URL").expect("BACKEND_URL is not set in .env file");
    let url = format!("{}/api/delete/{}", backend_url, id);
    let resp = Request::get(&url).send().await?;
    Ok(resp)
}

async fn list_books(
    page: u32,
    userid: i32,
    sort: String,
) -> Result<PaginatedBookUIList, reqwasm::Error> {
    let backend_url: &'static str = dotenv!("BACKEND_URL");
    //env::var("BACKEND_URL").expect("BACKEND_URL is not set in .env file");
    let url = format!(
        "{}/api/list?page={}&userid={}&sort={}",
        backend_url, page, userid, sort
    );
    let resp = Request::get(&url).send().await?;
    println!("Fetching books\n");
    //info!("BACKEND{}",backend_url);

    let body = resp.json::<PaginatedBookUIList>().await?;
    Ok(body)
}

#[component]
pub fn Header<G: Html>(cx: Scope) -> View<G> {
    let app_state = use_context::<AppState>(cx);
    let value = create_signal(cx, String::new());
    let input_ref = create_node_ref(cx);

    let value2 = create_signal(cx, String::new());
    let input_ref2 = create_node_ref(cx);

    //let value3 = create_signal(cx, String::new());
    //let input_ref3 = create_node_ref(cx);

    let completed = create_selector(cx, || *app_state.editmode.get());
    let editchecked = create_signal(cx, false);

    let handle_submit = |event: Event| {
        let event: KeyboardEvent = event.unchecked_into();

        if event.key() == "Enter" {
            let mut task = value.get().as_ref().clone();
            task = task.trim().to_string();

            if !task.is_empty() {
                app_state.search.set(task.clone());
                app_state.openlibrary.set(true);
                app_state.internalsearch.set(false);
                app_state.refreshing.set(false);

                info!("Fetching search {}\n", task.clone());
                app_state.books.set(Vec::new());
                value.set("".to_string());
                input_ref
                    .get::<DomNode>()
                    .unchecked_into::<HtmlInputElement>()
                    .set_value("");
            }
        }
    };

    let handle_submit_seachall = |event: Event| {
        let event: KeyboardEvent = event.unchecked_into();

        if event.key() == "Enter" {
            let mut task = value2.get().as_ref().clone();
            task = task.trim().to_string();

            if !task.is_empty() {
                app_state.search.set(task);
                app_state.openlibrary.set(false);
                app_state.internalsearch.set(true);
                app_state.pagenum.set(1);
                app_state.pagedisplay.set(1);
                app_state.refreshing.set(true);
                info!("Fetching search 2\n");
            }
        }
    };

    let click_listall = |_| {
        app_state.openlibrary.set(false);
        app_state.internalsearch.set(false);
        app_state.pagenum.set(1);
        app_state.pagedisplay.set(1);
        app_state.refreshing.set(true);
    };

    let click_addbook = |_| {
        app_state.adding.set(true);
        app_state.updating.set(false);
        app_state.addingbook.set(BookUI::default());
    };

    /*let handle_submit_addbulk = |event: Event| {
        let event: KeyboardEvent = event.unchecked_into();

        if event.key() == "Enter" {
            let mut task = value3.get().as_ref().clone();
            task = task.trim().to_string();

            if !task.is_empty() {

            spawn_local(async move {
                    let _temp = add_books_isbns(task).await.unwrap();
            });
            }
        }
    };*/

    let click_logout = |_| {
        spawn_local(async move {
            logout_user().await.unwrap();
        });
        app_state.loggedin.set(false);
        app_state.editmode.set(false);
    };

    let click_userscreen = |_| {
        app_state.userscreen.set(true);
    };

    let toggle_editmode = |_| {
        //app_state.editmode.set(*editchecked.get());
        app_state.editmode.set(!(*app_state.editmode.get()));
        app_state.userid.set(*app_state.useridloggedin.get());
        app_state
            .selectedusername
            .set((*app_state.loggedusername.get()).clone());
    };

    let dropdown_userselect = |_| {
        let app_state = app_state.clone();
        spawn_local(async move {
            app_state
                .userlist
                .set(list_users().await.expect("Couldn't list user"));
        });
        app_state.dropdownselect.set(true);
    };

    let click_menu_expand = |_| {
        let app_state = app_state.clone();
        app_state.menuexpand.set(!(*app_state.menuexpand.get()));
    };

    create_effect(cx, || {
        // Calling checked.set will also update the `checked` property on the input element.
        editchecked.set(*completed.get())
    });

    //    let users = create_memo(cx, || app_state.userlist.get().keys().cloned().map(|x| StringProp{value: x}).collect::<Vec<StringProp>>());
    let users = create_memo(cx, || {
        app_state
            .userlist
            .get()
            .keys()
            .cloned()
            .collect::<Vec<String>>()
    });

    view! { cx,
        header(class="sticky top-0 z-50 flex bg-slate-400 gap-x-4") {
        div(class="w-1/10 flex mb-2"){
            (if *app_state.loggedin.get() == false {
              view!{ cx,
                    button(on:click=click_userscreen, class="bg-gray-300 hover:bg-gray-200 text-gray-800 font-bold py-2 px-4 rounded inline-flex items-center w-full") { i(class="fa-solid fa-user") }
                }
            } else {
                view!{cx,
                div(class="flex gap-x-1"){
                    button(on:click=click_logout, class="bg-gray-300 hover:bg-gray-200 text-gray-800 font-bold py-2 px-4 rounded inline-flex items-center w-1/2") { i(class="fa-solid fa-right-from-bracket") }
                    label(class="inline-flex relative items-center cursor-pointer w-1/2"){
                    input(
                        class="sr-only peer",
                        type="checkbox",
                        on:input=toggle_editmode,
                        bind:checked=editchecked
                    )
                    div(class="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[10px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"){}
                    //p(class="ml-3 text-sm font-medium"){"EDIT"}
                    }
                    }
                }
            })
        }

        div(class="w-4/5 md:w-4/5 flex mb-2"){

        div(class="hidden md:flex md:w-full"){

            div(class="w-1/5 flex"){
                (if *app_state.editmode.get() == false {
                    view!{ cx,
                        div(class="flex"){
                            select(class="bg-gray-300 hover:bg-gray-200 text-gray-800 font-bold rounded inline-flex items-center w-max", on:click=dropdown_userselect) {
                                option(disabled=true, selected=true, hidden=true, value="", class="w-max"){("?")}
                                Keyed(
                                    iterable=users,
                                    view=move |cx, x| view! { cx,
                                        DropDownUser(value=x)
                                    },
                                    key =|x| x.clone() )
                            }
                        }

                    } }
                    else {
                        view!{cx,
                            div(class="bg-gray-300 text-gray-800 font-bold rounded inline-flex items-center px-2"){(format!(" {} ", *app_state.selectedusername.get()))}
                        }
                    })
            }

            (if *app_state.editmode.get() == true {
              view!{ cx,

            div(class="w-2/5 flex"){
              (if *app_state.userid.get() != 0 {
                view!{ cx,
                button(on:click=click_listall, class="bg-gray-300 hover:bg-gray-200 text-gray-800 font-bold py-2 px-4 rounded inline-flex items-center") { i(class="fa-solid fa-layer-group") span(class="inline-block"){"All" }}
                div(class="min-w-40 inline-flex"){
                input(ref=input_ref2,
                    class = "inline-flex h-full m-0 p-1 w-full",
                    placeholder="🔍 Search",
                    bind:value=value2,
                    on:keyup=handle_submit_seachall,
                )}
                }} else {
                view!{cx, ""}
                })
                }
            div(class="w-2/5 flex"){
            button(on:click=click_addbook, class="bg-gray-300 hover:bg-gray-200 text-gray-800 font-bold py-2 px-4 rounded inline-flex items-center") { i(class="fa-solid fa-circle-plus") span(class="inline-block"){"Add" }}
            //button(on:click=click_addbook) { "+ Add New" }
            //input(ref=input_ref3,
            //    class="new-todo",
            //    placeholder="Add bulk ISBNs",
            //    bind:value=value3,
            //    on:keyup=handle_submit_addbulk,
            //)
            div(class="min-w-40 inline-flex"){
                input(ref=input_ref,
                    class = "inline-flex h-full m-0 p-1 w-full",
                    placeholder="🔍 Internet",
                    bind:value=value,
                    on:keyup=handle_submit,
                )}
            }

            }} else {
                view!{cx,
                (if *app_state.userid.get() != 0 {
                    view!{ cx,
                        div(class="w-4/5 flex"){
                    button(on:click=click_listall, class="bg-gray-300 hover:bg-gray-200 text-gray-800 font-bold py-2 px-4 rounded inline-flex items-center") { i(class="fa-solid fa-layer-group") span(class="inline-block"){"All" }}
                    div(class="min-w-100 inline-flex"){
                    input(ref=input_ref2,
                        class = "inline-flex h-full m-0 p-1 w-full",
                        placeholder="🔍 Search",
                        bind:value=value2,
                        on:keyup=handle_submit_seachall,
                    )}
                    }
                    }
                    } else {
                    view!{cx, ""}
                    })
                    }
            })
        }
        div(class="inline-flex w-full md:hidden md:w-0"){
            button(on:click=click_menu_expand, class="bg-gray-300 hover:bg-gray-200 text-gray-800 font-bold py-2 px-4 rounded inline-flex items-center") { i(class="fa-solid fa-bars") }
        }
    }

            div(class="grow flex mb-2 gap-x-1 ml-auto") {
            PageBar{}
            }
        }
    }
}

#[component]
pub fn MenuExpanded<G: Html>(cx: Scope) -> View<G> {
    let app_state = use_context::<AppState>(cx);
    let value = create_signal(cx, String::new());
    let input_ref = create_node_ref(cx);

    let value2 = create_signal(cx, String::new());
    let input_ref2 = create_node_ref(cx);

    let users = create_memo(cx, || {
        app_state
            .userlist
            .get()
            .keys()
            .cloned()
            .collect::<Vec<String>>()
    });

    let handle_submit = |event: Event| {
        let event: KeyboardEvent = event.unchecked_into();

        if event.key() == "Enter" {
            let mut task = value.get().as_ref().clone();
            task = task.trim().to_string();

            if !task.is_empty() {
                app_state.search.set(task.clone());
                app_state.openlibrary.set(true);
                app_state.internalsearch.set(false);
                app_state.refreshing.set(false);

                info!("Fetching search {}\n", task.clone());
                app_state.books.set(Vec::new());
                value.set("".to_string());
                input_ref
                    .get::<DomNode>()
                    .unchecked_into::<HtmlInputElement>()
                    .set_value("");
            }
            app_state.menuexpand.set(!(*app_state.menuexpand.get()));
        }
    };

    let handle_submit_seachall = |event: Event| {
        let event: KeyboardEvent = event.unchecked_into();

        if event.key() == "Enter" {
            let mut task = value2.get().as_ref().clone();
            task = task.trim().to_string();

            if !task.is_empty() {
                app_state.search.set(task);
                app_state.openlibrary.set(false);
                app_state.internalsearch.set(true);
                app_state.refreshing.set(true);
                info!("Fetching search 2\n");
            }
            app_state.menuexpand.set(!(*app_state.menuexpand.get()));
        }
    };

    let click_listall = |_| {
        app_state.openlibrary.set(false);
        app_state.internalsearch.set(false);
        app_state.refreshing.set(true);
        app_state.menuexpand.set(!(*app_state.menuexpand.get()));
    };

    let click_addbook = |_| {
        app_state.adding.set(true);
        app_state.updating.set(false);
        app_state.addingbook.set(BookUI::default());
        app_state.menuexpand.set(!(*app_state.menuexpand.get()));
    };

    let dropdown_userselect = |_| {
        let app_state = app_state.clone();
        spawn_local(async move {
            app_state
                .userlist
                .set(list_users().await.expect("Couldn't list user"));
        });
        app_state.dropdownselect.set(true);
    };

    view! { cx,
            (if *app_state.menuexpand.get() == true {
                view!{cx,
                    header(class="sticky top-50 z-50 flex flex-col bg-slate-400 gap-x-4") {
                    div(class="w-full flex flex-row mb-4"){
                        (if *app_state.editmode.get() == false {
                            view!{ cx,
                                div(class="inline-flex"){
                                    select(class="bg-gray-300 hover:bg-gray-200 text-gray-800 font-bold rounded inline-flex items-center w-40", on:click=dropdown_userselect) {
                                        option(disabled=true, selected=true, hidden=true, value="", class="w-max"){("?")}
                                        Keyed(
                                            iterable=users,
                                            view=move |cx, x| view! { cx,
                                                DropDownUser(value=x)
                                            },
                                            key =|x| x.clone() )
                                    }
                                }

                            } }
                            else {
                                view!{cx,
                                    div(class="bg-gray-300 text-gray-800 font-bold rounded inline-flex items-center px-2"){(format!(" {} ", *app_state.selectedusername.get()))}
                                }
                            })
                    }
                    (if *app_state.editmode.get() == true {
                    view!{ cx,



                    div(class="w-full flex flex-row mb-4"){
                    (if *app_state.userid.get() != 0 {
                        view!{ cx,
                        button(on:click=click_listall, class="bg-gray-300 hover:bg-gray-200 text-gray-800 font-bold py-2 px-4 rounded inline-flex items-center w-40") { i(class="fa-solid fa-layer-group") span(class="inline-block"){"All" }}
                        div(class="min-w-40 inline-flex"){
                        input(ref=input_ref2,
                            class = "inline-flex h-full m-0 p-1 w-full",
                            placeholder="🔍 Search",
                            bind:value=value2,
                            on:keyup=handle_submit_seachall,
                        )}
                        }} else {
                        view!{cx, ""}
                        })
                        }
                        br{}
                    div(class="w-full flex flex-row mb-4"){
                    button(on:click=click_addbook, class="bg-gray-300 hover:bg-gray-200 text-gray-800 font-bold py-2 px-4 rounded inline-flex items-center  w-40") { i(class="fa-solid fa-circle-plus") span(class="inline-block"){"Add" }}
                    div(class="min-w-40 inline-flex"){
                        input(ref=input_ref,
                            class = "inline-flex h-full m-0 p-1 w-full",
                            placeholder="🔍 Internet",
                            bind:value=value,
                            on:keyup=handle_submit,
                        )}
                    }

                    }} else {
                        view!{cx,
                        (if *app_state.userid.get() != 0 {
                            view!{ cx,
                            div(class="w-full flex mb-4"){

                            button(on:click=click_listall, class="bg-gray-300 hover:bg-gray-200 text-gray-800 font-bold py-2 px-4 rounded inline-flex items-center w-40") { i(class="fa-solid fa-layer-group") span(class="inline-block"){"All" }}
                            div(class="min-w-40 inline-flex"){
                            input(ref=input_ref2,
                                class = "inline-flex h-full m-0 p-1 w-full",
                                placeholder="🔍 Search",
                                bind:value=value2,
                                on:keyup=handle_submit_seachall,
                            )}
                            }}} else {
                            view!{cx, ""}
                            })
                            }
                    })
                }
            }
        } else {
            view!{cx, ""}
        })
    }
}

#[component(inline_props)]
pub fn DropDownUser<G: Html>(cx: Scope, value: StringProp) -> View<G> {
    let app_state = use_context::<AppState>(cx);
    let buttontext = value.clone().value.clone();
    let valueclosure = value.clone();

    let handle_select_user = move |_| {
        app_state.userid.set(
            *(*app_state.userlist.get())
                .get(&(valueclosure.value).clone())
                .unwrap_or(&0),
        );
        app_state.selectedusername.set(valueclosure.value.clone());
        app_state.dropdownselect.set(false);
        app_state.menuexpand.set(false);
    };

    view! { cx,
        //div( class="py-1", role="none") {}
        option(on:click=handle_select_user,class="w-max"){ (format!("{}",buttontext)) }
    }
}

#[component]
async fn WarningMessageBar<G: Html>(cx: Scope<'_>) -> View<G> {
    let app_state = use_context::<AppState>(cx);

    let handle_clear_warning = move |_| {
        app_state.warningmsg.set("".to_string());
    };

    view! {cx,
        (if *app_state.warningmsg.get() != "".to_string() {
            view!{ cx,
            div(on:click=handle_clear_warning){ (*app_state.warningmsg.get()) }
        }} else {
            view!{cx, ""}
        })
    }
}

#[component]
async fn ListDB<G: Html>(cx: Scope<'_>) -> View<G> {
    let app_state = use_context::<AppState>(cx);
    let app_state2 = app_state.clone();

    //provide_context(cx, false);
    //let callback_signal = use_context::<RcSignal<bool>>(cx);
    //let csignal = callback_signal.clone();
    //let csignal2 = callback_signal.clone();

    create_effect(cx, || {
        let app_state = app_state.clone();
        if *app_state.userid.get() != 0 {
            app_state.openlibrary.set(false);
            app_state.internalsearch.set(false);
            app_state.pagenum.set(1);
            app_state.pagedisplay.set(1);
            app_state.refreshing.set(true);
        }
    });

    create_effect(cx, || {
        let app_state = app_state.clone();
        //let csignal2 = csignal2.clone();
        if *app_state.scrollevent.get() == true {
            app_state.scrollevent.set(false);
            info!(
                "Scroll event result {}{}",
                *app_state.pagedisplay.get(),
                *app_state.maxpage.get()
            );
            if *app_state.pagedisplay.get() < *app_state.maxpage.get() {
                app_state.pagedisplay.set(*app_state.pagedisplay.get() + 1);
                app_state.scrolling.set(true);
                info!("Scroll update needed");
            }
        }
    });

    create_effect(cx, || {
        let app_state = app_state.clone();
        let app_state_scr = app_state.clone();
        app_state.search.track();
        app_state.scrolling.track();
        app_state.pagenum.track();
        app_state.openlibrary.track();
        app_state.internalsearch.track();
        app_state.refreshing.track();
        //let csignal = csignals2.clone();
        //info!("Something triggered{}",*app_state.clone().search.clone());

        //let tempb = app_state.books.get();
        //spawn_local( async move { info!(
        //    "The state changed. Old value: {:?}",
        //    app_state.books.get()
        //)});

        if *app_state.openlibrary.get() == false {
            if *app_state.refreshing.get() == true {
                app_state.books.set(Vec::new());
                //TimeoutFuture::new(1000).await;
                //info!("Refresh triggered");

                if *app_state.internalsearch.get() == false {
                    info!("DB triggered");
                    spawn_local(async move {
                        let res = list_books(
                            *app_state.pagenum.get(),
                            *app_state.userid.get(),
                            "desc".to_string(),
                        )
                        .await
                        .unwrap();
                        app_state.books.set(res.books);
                        app_state.maxpage.set(res.num_pages)
                    });
                } else {
                    info!("IntSearch triggered");

                    spawn_local(async move {
                        let res = search_books(
                            app_state.search.get().to_string(),
                            *app_state.pagenum.get(),
                            *app_state.userid.get(),
                        )
                        .await
                        .unwrap();
                        app_state.books.set(res.books);
                        app_state.maxpage.set(res.num_pages)
                    });
                }
                app_state.refreshing.set(false);
            } else if *app_state.scrolling.get() == true {
                if *app_state.internalsearch.get() == false {
                    info!("DB triggered2");
                    spawn_local(async move {
                        let res = list_books(
                            *app_state_scr.pagedisplay.get(),
                            *app_state_scr.userid.get(),
                            "desc".to_string(),
                        )
                        .await
                        .unwrap();
                        let mut currbooks = (*app_state_scr.clone().books.get()).clone();
                        currbooks.extend(res.books.iter().cloned());
                        app_state_scr.books.set(currbooks);
                        app_state_scr.maxpage.set(res.num_pages);
                        app_state_scr.scrolling.set(false);
                    });
                } else {
                    info!("IntSearch triggered2");

                    spawn_local(async move {
                        let res = search_books(
                            app_state_scr.search.get().to_string(),
                            *app_state_scr.pagedisplay.get(),
                            *app_state_scr.userid.get(),
                        )
                        .await
                        .unwrap();
                        let mut currbooks = (*app_state_scr.clone().books.get()).clone();
                        currbooks.extend(res.books.iter().cloned());
                        app_state_scr.books.set(currbooks);
                        app_state_scr.maxpage.set(res.num_pages);
                        app_state_scr.scrolling.set(false);
                    });
                }
            }
        } else {
            //info!("LibrarySearch triggered?");
            if *app_state.refreshing.get() == false {
                info!("LibrarySearch triggered");
                spawn_local(async move {
                    if *app_state.search.get() != "" {
                        if *app_state.openlibrary.get() == true {
                            app_state.books.set(
                                fetch_books(app_state.search.get().to_string())
                                    .await
                                    .unwrap(),
                            );
                            if (*app_state.books.get()).len() == 0  {
                                //let current_warning = *app_state.warningmsg.get().to_string();
                                app_state.warningmsg.set(app_state.warningmsg.get().to_string() + " ** Failed to find books for " + &*app_state.search.get() + " ** ");
                            }
                        }
                    }
                });
            }
        }
        info!("List Refreshing Done");
    });

    let handle_load_more = move |_| {
        let app_state = app_state.clone();
        if *app_state.scrolling.get() == false {
            app_state.scrollevent.set(true);
        }
    };

    let window = web_sys::window().expect("Failed to get window");
    let window_cl = window.clone();
    let callback: Closure<dyn FnMut()> = Closure::new(move || {
        //let csignal = csignal.clone();
        //csignal.set(true);
        let app_state2 = app_state2.clone();
        if *app_state2.scrolling.get() == false && *app_state2.openlibrary.get() == false {
            if window_cl.inner_height().unwrap().as_f64().unwrap() + window_cl.scroll_y().unwrap() >= window_cl.document().unwrap().body().unwrap().offset_height().into() {
                app_state2.scrollevent.set(true);
            }
        }
        info!("Got scroll event");
    });

    window
        .add_event_listener_with_callback_and_bool(
            "scroll",
            callback.as_ref().unchecked_ref(),
            false, // Changing this to true does not help :/
        )
        .expect("Failed to set listener");
    callback.forget();

    let docs = create_memo(cx, || {
        app_state.books.get().iter().cloned().collect::<Vec<_>>()
    });
    view! {cx,
                (if *app_state.openlibrary.get() == false &&  *app_state.editmode.get() == false {
              view!{ cx,
                      div(class="grid gap-2 grid-cols-1 md:grid-cols-4") {


            Keyed(
             iterable=docs,
             view=|cx, x| view! { cx,
                BookDB_View(bookitem=x)
             },
              key =|x| x.id )
              }
              br{}
              (if *app_state.scrolling.get() == true  {
                  view!{ cx,
                      div(class="flex flex-col items-center m-5"){
                          div(class="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded inline-flex items-center"){ "Loading ..." }
                      }
                  }} else {
                      view!{ cx,
                          (if *app_state.maxpage.get() > 1 && *app_state.maxpage.get() > *app_state.pagedisplay.get()  {
                              view!{ cx,
                                  div(class="flex flex-col items-center m-5"){
                                      button(class="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded inline-flex items-center",on:click=handle_load_more){ "Load More" }
                                  }
                              }} else {
                                  view!{ cx, ""}
                              })}
                  })
             }

                } else if *app_state.openlibrary.get() == false &&  *app_state.editmode.get() == true {
              view!{ cx,
                      div(class="grid grid-cols-1 md:grid-cols-4 gap-2 ") {

            Keyed(
             iterable=docs,
             view=|cx, x| view! { cx,
                BookDB(bookitem=x)
             },
              key =|x| x.id )
              }
              br{}

              (if *app_state.scrolling.get() == true  {
                  view!{ cx,
                      div(class="flex flex-col items-center m-5"){
                          div(class="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded inline-flex items-center"){ "Loading ..." }
                      }
                  }} else {
                      view!{ cx,
                          (if *app_state.maxpage.get() > 1 && *app_state.maxpage.get() > *app_state.pagedisplay.get()  {
                          view!{ cx,
                              div(class="flex flex-col items-center m-5"){
                                  button(class="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded inline-flex items-center",on:click=handle_load_more){ "Load More" }
                              }
                          }} else {
                              view!{ cx, ""}
                          })}
                  })
             }

                } else {
                    view!{cx, ""}
                }
              )


    }
}

#[component(inline_props)]
pub fn BookDB<G: Html>(cx: Scope, bookitem: BookUIProp) -> View<G> {
    let app_state = use_context::<AppState>(cx);
    let bookdelete = bookitem.bookitem.clone();
    let bookupdate = bookitem.bookitem.clone();
    let bookdisplay = bookitem.bookitem.clone();
    let bookdisplay_div = bookitem.bookitem.clone();
    let loctitle = bookitem.bookitem.clone().title.clone();
    let locauthors = bookitem
        .bookitem
        .clone()
        .author_name
        .clone()
        .unwrap_or(vec!["".to_string()])
        .join(", ");
    let mut locdesc = bookitem
        .bookitem
        .clone()
        .description
        .unwrap_or("".to_string());
    let locloc = bookitem.bookitem.clone().location.unwrap_or("".to_string());
    if locdesc.clone().chars().count() > 200 {
        locdesc = format!("{:.200}...", locdesc.clone())
    }
    //let locref = create_rc_signal(false);

    let coverurl = bookdisplay
        .clone()
        .cover
        .clone()
        .unwrap_or("None".to_string());
    let handle_delete = move |_| {
        app_state.deleteid.set(bookdelete.id);
        app_state.deleterequest.set(true);
    };

    create_effect(cx, || {
        let app_state = app_state.clone();
        if *app_state.deleterequest.get() == true {
            spawn_local(async move {
                let temp = delete_book(*app_state.deleteid.get()).await.unwrap();
                println!("{}", temp.status());
                app_state.refreshing.set(true);
            });
        }

        app_state.deleterequest.set(false);
    });

    let handle_update = move |_| {
        app_state.adding.set(false);
        app_state.updating.set(true);
        app_state.addingbook.set(bookupdate.clone());
    };

    let handle_display = move |_| {
        app_state.displaying.set(true);
        app_state.updating.set(false);
        //info!("Setting displaying book {:?}",bookdisplay);
        app_state.displayingbook.set(bookdisplay.clone());
    };
    let handle_display_div = move |_| {
        app_state.displaying.set(true);
        app_state.updating.set(false);
        //info!("Setting displaying book {:?}",bookdisplay);
        app_state.displayingbook.set(bookdisplay_div.clone());
    };
    view! { cx,
         div(class="column px-4 py-4 bg-gray-200 border-2 border-gray-400 rounded  m-3 hover:scale-110"){

                    div(class="card-buttons flex gap-x-3"){
                    button( class="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 border-black-500  rounded inline-flex items-center", on:click=handle_display){ i(class="fa-solid fa-circle-info") }
                    button( class="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 border-black-500  rounded inline-flex items-center", on:click=handle_update){ i(class="fa-solid fa-pen-to-square") }
                    button( class="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 border-black-500  rounded inline-flex items-center", on:click=handle_delete){ i(class="fa-solid fa-trash") }
                }
    div(class="card-main",on:click=handle_display_div){
    img(class="float-right m-1",src=coverurl,width="100")

    div(class="card-title font-bold text-lg"){
    (format!("{}",loctitle))
    }
    div(class="card-authors text-lg"){
    (format!("{}",locauthors))
    }
    div(class="card-desc"){
    (format!("{}",locloc))
    br{}br{}
    (format!("{}",locdesc.clone()))

    }
    }



    }

    }
}

#[component(inline_props)]
pub fn BookDB_View<G: Html>(cx: Scope, bookitem: BookUIProp) -> View<G> {
    let app_state = use_context::<AppState>(cx);
    let bookdisplay = bookitem.bookitem.clone();
    let bookdisplay_div = bookitem.bookitem.clone();
    let loctitle = bookitem.bookitem.clone().title.clone();
    let locauthors = bookitem
        .bookitem
        .clone()
        .author_name
        .clone()
        .unwrap_or(vec!["".to_string()])
        .join(", ");
    let mut locdesc = bookitem
        .bookitem
        .clone()
        .description
        .unwrap_or("".to_string());
    let locloc = bookitem.bookitem.clone().location.unwrap_or("".to_string());
    if locdesc.clone().chars().count() > 200 {
        locdesc = format!("{:.200}...", locdesc.clone())
    }

    let coverurl = bookdisplay
        .clone()
        .cover
        .clone()
        .unwrap_or("None".to_string());
    let handle_display = move |_| {
        app_state.displaying.set(true);
        app_state.updating.set(false);
        //info!("Setting displaying book {:?}",bookdisplay);
        app_state.displayingbook.set(bookdisplay.clone());
    };
    let handle_display_div = move |_| {
        app_state.displaying.set(true);
        app_state.updating.set(false);
        //info!("Setting displaying book {:?}",bookdisplay);
        app_state.displayingbook.set(bookdisplay_div.clone());
    };
    view! { cx,
         div(class="col-span-1 px-4 py-4 bg-gray-200 border-2 border-gray-400 rounded m-3 hover:scale-110", on:click=handle_display_div){


                    div(class="card-buttons"){

                    button( class="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 border-black-500  rounded inline-flex items-center", on:click=handle_display){ i(class="fa-solid fa-circle-info") }

                }
    div(class="card-main"){
    img(class="float-right m-1",src=coverurl,width="100")

    div(class="card-title font-bold text-lg"){
    (format!("{}",loctitle))
    }
    div(class="card-authors text-lg"){
    (format!("{}",locauthors))
    }

    div(class="card-desc"){
    (format!("{}",locloc))
    br{}br{}
    (format!("{:.100}...",locdesc.clone()))
    }
    }



    }

    }
}

#[component]
async fn ListOL<G: Html>(cx: Scope<'_>) -> View<G> {
    let app_state = use_context::<AppState>(cx);

    /*
    create_effect(cx, || {
    app_state.search.track();

    info!(
        "The state changed B. New value: {}",
        app_state.search.get(),
    );
    });
    */

    let docs = create_memo(cx, || {
        app_state.books.get().iter().cloned().collect::<Vec<_>>()
    });
    view! {cx,

            (if *app_state.openlibrary.get() == true {
                view!{ cx,
                     div(class="grid space-x-1 grid-cols-4 md:grid-cols-4") {
            Keyed(
             iterable=docs,
             view=move |cx, x| view! { cx,
                 BookOL(bookitem=x)

             },
              key =|x| x.id )
              }
             }
            } else {
                view!{cx,""}
            }
            )
    }
}

#[component(inline_props)]
pub fn BookOL<G: Html>(cx: Scope, bookitem: BookUIProp) -> View<G> {
    let book = bookitem.bookitem.clone();
    let book_div = book.clone();
    let bookdisp = book.clone();
    let loctitle = bookitem.bookitem.clone().title.clone();
    let locauthors = bookitem
        .bookitem
        .clone()
        .author_name
        .clone()
        .unwrap_or(vec!["".to_string()])
        .join(", ");
    let backend_url: &'static str = dotenv!("BACKEND_URL");
    let mut coverurl = bookdisp.cover.clone().unwrap_or("NONE".to_string());
    if coverurl == "NONE".to_string() {
        coverurl = format!("{}/images/placeholder.jpg", backend_url);
    }

    let app_state = use_context::<AppState>(cx);
    let handle_add = move |_| {
        app_state.adding.set(true);
        app_state.addingbook.set(book.clone());
    };
    let handle_add_div = move |_| {
        app_state.adding.set(true);
        app_state.addingbook.set(book_div.clone());
    };
    view! { cx,
                div(class="column px-4 py-4 bg-gray-200 border-2 border-gray-400 rounded  m-3 hover:scale-110",on:click=handle_add_div){
                    button( class="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 border-black-500  rounded inline-flex items-center", on:click=handle_add){ i(class="fa-solid fa-plus") }

       div(class="card-main"){
    img(class="float-right m-1",src=coverurl,width="100")

    div(class="card-title font-bold text-lg"){
    (format!("{}",loctitle))
    }
    div(class="card-authors text-lg"){
    (format!("{}",locauthors))
    }
    //div(class="card-image"){
    //}
    }
    }

    }
}

#[component]
async fn AddingUI<G: Html>(cx: Scope<'_>) -> View<G> {
    let app_state = use_context::<AppState>(cx);

    let node_ref = create_node_ref(cx);

    let inp_title = create_signal(cx, (*app_state.addingbook.get()).clone().title);
    let inp_olkey = create_signal(
        cx,
        (*app_state.addingbook.get())
            .clone()
            .open_library_key
            .unwrap_or("".to_string()),
    );
    let inp_editioncount = create_signal(
        cx,
        (*app_state.addingbook.get())
            .clone()
            .edition_count
            .unwrap_or(0)
            .to_string(),
    );
    let inp_publishyear = create_signal(
        cx,
        (*app_state.addingbook.get())
            .clone()
            .first_publish_year
            .unwrap_or(0)
            .to_string(),
    );
    let inp_medianpage = create_signal(
        cx,
        (*app_state.addingbook.get())
            .clone()
            .median_page_count
            .unwrap_or(0)
            .to_string(),
    );
    let inp_goodread = create_signal(
        cx,
        (*app_state.addingbook.get())
            .clone()
            .goodread_id
            .unwrap_or("".to_string()),
    );
    let inp_desc = create_signal(
        cx,
        (*app_state.addingbook.get())
            .clone()
            .description
            .unwrap_or("".to_string()),
    );
    let inp_cover = create_signal(
        cx,
        (*app_state.addingbook.get())
            .clone()
            .cover
            .unwrap_or("".to_string()),
    );
    let inp_location = create_signal(
        cx,
        (*app_state.addingbook.get())
            .clone()
            .location
            .unwrap_or("".to_string()),
    );
    let inp_rating = create_signal(
        cx,
        (*app_state.addingbook.get())
            .clone()
            .location
            .unwrap_or("".to_string()),
    );
    let inp_comments = create_signal(
        cx,
        (*app_state.addingbook.get())
            .clone()
            .comments
            .unwrap_or("".to_string()),
    );
    let inp_author = create_signal(
        cx,
        (*app_state.addingbook.get())
            .clone()
            .author_name
            .unwrap_or(vec!["".to_string()])
            .join(", "),
    );
    let inp_person = create_signal(
        cx,
        (*app_state.addingbook.get())
            .clone()
            .person
            .unwrap_or(vec!["".to_string()])
            .join(", "),
    );
    let inp_place = create_signal(
        cx,
        (*app_state.addingbook.get())
            .clone()
            .place
            .unwrap_or(vec!["".to_string()])
            .join(", "),
    );
    let inp_subject = create_signal(
        cx,
        (*app_state.addingbook.get())
            .clone()
            .subject
            .unwrap_or(vec!["".to_string()])
            .join(", "),
    );
    let inp_time = create_signal(
        cx,
        (*app_state.addingbook.get())
            .clone()
            .time
            .unwrap_or(vec!["".to_string()])
            .join(", "),
    );
    let inp_isbn = create_signal(
        cx,
        (*app_state.addingbook.get())
            .clone()
            .isbn
            .unwrap_or(vec!["".to_string()])
            .join(", "),
    );
    create_effect(cx, || {
        //    info!("{:?}",*app_state.addingbook.get());
        inp_title.set((*app_state.addingbook.get()).clone().title);
        inp_olkey.set(
            (*app_state.addingbook.get())
                .clone()
                .open_library_key
                .unwrap_or("".to_string()),
        );
        inp_editioncount.set(
            (*app_state.addingbook.get())
                .clone()
                .edition_count
                .unwrap_or(0)
                .to_string(),
        );
        inp_publishyear.set(
            (*app_state.addingbook.get())
                .clone()
                .first_publish_year
                .unwrap_or(0)
                .to_string(),
        );
        inp_medianpage.set(
            (*app_state.addingbook.get())
                .clone()
                .median_page_count
                .unwrap_or(0)
                .to_string(),
        );
        inp_goodread.set(
            (*app_state.addingbook.get())
                .clone()
                .goodread_id
                .unwrap_or("".to_string()),
        );
        inp_desc.set(
            (*app_state.addingbook.get())
                .clone()
                .description
                .unwrap_or("".to_string()),
        );
        inp_cover.set(
            (*app_state.addingbook.get())
                .clone()
                .cover
                .unwrap_or("".to_string()),
        );
        inp_location.set(
            (*app_state.addingbook.get())
                .clone()
                .location
                .unwrap_or("".to_string()),
        );
        inp_rating.set(
            (*app_state.addingbook.get())
                .clone()
                .location
                .unwrap_or("".to_string()),
        );
        inp_comments.set(
            (*app_state.addingbook.get())
                .clone()
                .comments
                .unwrap_or("".to_string()),
        );
        inp_author.set(
            (*app_state.addingbook.get())
                .clone()
                .author_name
                .unwrap_or(vec!["".to_string()])
                .join(", "),
        );
        inp_person.set(
            (*app_state.addingbook.get())
                .clone()
                .person
                .unwrap_or(vec!["".to_string()])
                .join(", "),
        );
        inp_place.set(
            (*app_state.addingbook.get())
                .clone()
                .place
                .unwrap_or(vec!["".to_string()])
                .join(", "),
        );
        inp_subject.set(
            (*app_state.addingbook.get())
                .clone()
                .subject
                .unwrap_or(vec!["".to_string()])
                .join(", "),
        );
        inp_time.set(
            (*app_state.addingbook.get())
                .clone()
                .time
                .unwrap_or(vec!["".to_string()])
                .join(", "),
        );
        inp_isbn.set(
            (*app_state.addingbook.get())
                .clone()
                .isbn
                .unwrap_or(vec!["".to_string()])
                .join(", "),
        );
    });

    let handle_cancel = |_| {
        app_state.updating.set(false);
        app_state.adding.set(false);

        let dom_node = node_ref.try_get::<DomNode>();
        if dom_node.is_some() {
            dom_node.unwrap().set_attribute("popup-display", "false");
        }
    };

    let handle_add = |_| {
        info!("Adding book");
        let authors: Vec<String> = (*inp_author.get())
            .clone()
            .split(",")
            .map(str::to_string)
            .collect::<Vec<String>>();
        let persons: Vec<String> = (*inp_person.get())
            .clone()
            .split(",")
            .map(str::to_string)
            .collect::<Vec<String>>();
        let places: Vec<String> = (*inp_place.get())
            .clone()
            .split(",")
            .map(|x| x.to_string())
            .collect::<Vec<String>>();
        let subjects: Vec<String> = (*inp_subject.get())
            .clone()
            .split(",")
            .map(|x| x.to_string())
            .collect::<Vec<String>>();
        let times: Vec<String> = (*inp_time.get())
            .clone()
            .split(",")
            .map(|x| x.to_string())
            .collect::<Vec<String>>();
        let isbns: Vec<String> = (*inp_isbn.get())
            .clone()
            .split(",")
            .map(|x| x.to_string())
            .collect::<Vec<String>>();
        let record: BookUI = BookUI {
            id: app_state.addingbook.get().id.clone(),
            title: (*inp_title.get()).clone(),
            open_library_key: Some((*inp_olkey.get()).clone()),
            edition_count: Some(inp_editioncount.get().parse::<i32>().unwrap_or(0)),
            first_publish_year: Some(inp_publishyear.get().parse::<i32>().unwrap_or(0)),
            median_page_count: Some(inp_medianpage.get().parse::<i32>().unwrap_or(0)),
            goodread_id: Some((*inp_goodread.get()).clone()),
            description: Some((*inp_desc.get()).clone()),
            cover: Some((*inp_cover.get()).clone()),
            location: Some((*inp_location.get()).clone()),
            time_added: Some("NA".to_string()),
            rating: Some(inp_rating.get().parse::<i32>().unwrap_or(0)),
            comments: Some((*inp_comments.get()).clone()),
            author_name: Some(authors),
            person: Some(persons),
            place: Some(places),
            subject: Some(subjects),
            time: Some(times),
            isbn: Some(isbns),
        };

        app_state.apibook.set(record);

        app_state.addingbook.set(BookUI::default());
        if *app_state.updating.get() == true {
            app_state.updatingrequest.set(true);
        }
        if *app_state.adding.get() == true {
            app_state.addingrequest.set(true);
        }
        app_state.updating.set(false);
        app_state.adding.set(false);
        //app_state.books.set(vec![BookUI::default()]);
    };

    create_effect(cx, || {
        app_state.apibook.track();
        let app_state = app_state.clone();
        let record = (*app_state.apibook.get()).clone();
        spawn_local(async move {
            info!("Adding effect startedDone");

            if *app_state.addingrequest.get() == true {
                let temp = add_book(record.clone()).await.unwrap();
                if temp.status() != 200 {
                    app_state.warningmsg.set(app_state.warningmsg.get().to_string() + " ** Failed to create book " + &(record.clone().title) + " ** ");
                }
                info!("Adding Done{}", temp.status());
                app_state.refreshing.set(true);
                app_state.addingrequest.set(false);
            } else if *app_state.updatingrequest.get() == true {
                let temp = update_book(record.clone()).await.unwrap();
                if temp.status() != 200 {
                    app_state.warningmsg.set(app_state.warningmsg.get().to_string() + " ** Failed to update book " + &(record.clone().title) + " ** ");

                }
                info!("Updating Done{}", temp.status());
                app_state.refreshing.set(true);
                app_state.updatingrequest.set(false);
            }
        });
    });

    create_effect(cx, || {
        if *app_state.updating.get() == true || *app_state.adding.get() == true {
            let dom_node = node_ref.try_get::<DomNode>();
            if dom_node.is_some() {
                dom_node.unwrap().set_attribute("popup-display", "true");
            }
        } else {
            let dom_node = node_ref.try_get::<DomNode>();
            if dom_node.is_some() {
                dom_node.unwrap().set_attribute("popup-display", "false");
            }
        }
    });

    let handle_click_close = |event: Event| {
        let target: EventTarget = event.target().unwrap();
        let element: web_sys::Element = target.unchecked_into();
        if element.has_attribute("closable") {
            app_state.displaying.set(false);

            let dom_node = node_ref.try_get::<DomNode>();
            if dom_node.is_some() {
                dom_node.unwrap().set_attribute("popup-display", "false");
            }
        }
    };

    view! {cx,
             div(class="modal-box",ref=node_ref, on:click=handle_click_close, closable="true"){

    (if *app_state.adding.get() == true || *app_state.updating.get() == true {
                    view!{ cx,
            div(class="modal-content"){
                    div(class="input-buttons flex gap-x-3"){
                    button( class="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded inline-flex items-center", on:click=handle_add){ "Add/Update" }
                      button( class="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded inline-flex items-center", on:click=handle_cancel){ "Cancel" }
                      }
            p {
             div(class="flex flex-wrap w-full"){

                div(class="grid grid-cols-1 md:grid-cols-3 lg:grid=cols-4 gap-x-4"){

                    div(class="input-field grid grid-row-2"){
                    label{"Title"}
                    textarea(bind:value=inp_title, placeholder="Title" )
                    }
                    div(class="input-field grid grid-row-2"){
                    label{"OpenLib Key"}
                        textarea(bind:value=inp_olkey, placeholder="OpenLibrary Key"  )
                    }
                    div(class="input-field grid grid-row-2"){
                    label{"Editions"}
                            textarea(bind:value=inp_editioncount, placeholder="Number of editions" )
                    }
                    div(class="input-field grid grid-row-2"){
                    label{"Publish year"}
                            textarea(bind:value=inp_publishyear, placeholder="First publish year" )
                    }
                    div(class="input-field grid grid-row-2"){
                    label{"Pages"}
                            textarea(bind:value=inp_medianpage, placeholder="Page count" )
                    }
                    div(class="input-field grid grid-row-2"){
                    label{"GoodreadID"}
                            textarea(bind:value=inp_goodread, placeholder="GoodRead ID" )
                    }
                    div(class="input-field grid grid-row-2"){
                    label{"Description"}
                            textarea(bind:value=inp_desc, placeholder="Description" )
                    }
                    div(class="input-field grid grid-row-2"){
                    label{"Cover"}
                            textarea(bind:value=inp_cover, placeholder="Cover URL" )
                    }
                    div(class="input-field grid grid-row-2"){
                    label{"Location"}
                            textarea(bind:value=inp_location, placeholder="Location" )
                    }
                    div(class="input-field grid grid-row-2"){
                    label{"Rating"}
                            textarea(bind:value=inp_rating, placeholder="Rating (/10)" )
                    }
                    div(class="input-field grid grid-row-2"){
                    label{"Comments"}
                            textarea(bind:value=inp_comments, placeholder="Comments" )
                    }
                    div(class="input-field grid grid-row-2"){
                    label{"Authors"}
                            textarea(bind:value=inp_author, placeholder="Authors")
                    }
                    div(class="input-field grid grid-row-2"){
                    label{"Persons"}
                            textarea(bind:value=inp_person, placeholder="Persons" )
                    }
                    div(class="input-field grid grid-row-2"){
                    label{"Places"}
                            textarea(bind:value=inp_place, placeholder="Places" )
                    }
                    div(class="input-field grid grid-row-2"){
                    label{"Subjects"}
                            textarea(bind:value=inp_subject, placeholder="Subjects" )
                    }
                    div(class="input-field grid grid-row-2"){
                    label{"Times"}
                            textarea(bind:value=inp_time, placeholder="Times" )
                    }
                    div(class="input-field grid grid-row-2"){
                    label{"ISBNs"}
                            textarea(bind:value=inp_isbn, placeholder="ISBNs" )
                    }
                }
                }

            }
                }

            }
            }
             else {
                    view!{cx,""}
                })
            }

        }
}

#[component]
async fn SelectedUI<G: Html>(cx: Scope<'_>) -> View<G> {
    let app_state = use_context::<AppState>(cx);
    let displaybook = create_memo(cx, || app_state.displayingbook.get());

    let coverurl = create_memo(cx, || {
        app_state
            .displayingbook
            .get()
            .clone()
            .cover
            .clone()
            .unwrap_or("NONE".to_string())
            .to_string()
            .clone()
    });
    let node_ref = create_node_ref(cx);

    let dtitle = create_memo(cx, || app_state.displayingbook.get().title.clone());
    let dollink = create_memo(cx, || {
        let olkey = app_state
            .displayingbook
            .get()
            .open_library_key
            .clone()
            .unwrap_or("".to_string());
        format!("https://openlibrary.org{}", olkey)
    });
    let deditions = create_memo(cx, || {
        app_state.displayingbook.get().edition_count.unwrap_or(0)
    });
    let dpubyr = create_memo(cx, || {
        app_state
            .displayingbook
            .get()
            .first_publish_year
            .unwrap_or(0)
    });
    let dpages = create_memo(cx, || {
        app_state
            .displayingbook
            .get()
            .median_page_count
            .unwrap_or(0)
    });
    let dgoodread = create_memo(cx, || {
        let goodreadid = app_state
            .displayingbook
            .get()
            .goodread_id
            .clone()
            .unwrap_or("".to_string());
        format!("https://goodreads.com/en/book/show/{}", goodreadid)
    });
    let ddesc = create_memo(cx, || {
        app_state
            .displayingbook
            .get()
            .description
            .clone()
            .unwrap_or("".to_string())
    });
    let dlocation = create_memo(cx, || {
        app_state
            .displayingbook
            .get()
            .location
            .clone()
            .unwrap_or("".to_string())
    });
    let dcomments = create_memo(cx, || {
        app_state
            .displayingbook
            .get()
            .comments
            .clone()
            .unwrap_or("".to_string())
    });
    let dtags = create_memo(cx, || {
        let persons = app_state
            .displayingbook
            .get()
            .person
            .clone()
            .unwrap_or(vec!["".to_string()])
            .iter()
            .filter(|word| !word.is_empty())
            .map(|s| format!("#{}", s.clone()))
            .collect::<Vec<String>>()
            .join(", ");
        let places = app_state
            .displayingbook
            .get()
            .place
            .clone()
            .unwrap_or(vec!["".to_string()])
            .iter()
            .filter(|word| !word.is_empty())
            .map(|s| format!("#{}", s.clone()))
            .collect::<Vec<String>>()
            .join(", ");
        let subjects = app_state
            .displayingbook
            .get()
            .subject
            .clone()
            .unwrap_or(vec!["".to_string()])
            .iter()
            .filter(|word| !word.is_empty())
            .map(|s| format!("#{}", s.clone()))
            .collect::<Vec<String>>()
            .join(", ");
        let times = app_state
            .displayingbook
            .get()
            .time
            .clone()
            .unwrap_or(vec!["".to_string()])
            .iter()
            .filter(|word| !word.is_empty())
            .map(|s| format!("#{}", s.clone()))
            .collect::<Vec<String>>()
            .join(", ");
        let alltags = vec![persons, places, subjects, times]
            .iter()
            .filter(|word| !word.is_empty())
            .join(", ");
        format!("{}", alltags)
    });
    let disbn = create_memo(cx, || {
        app_state
            .displayingbook
            .get()
            .isbn
            .clone()
            .unwrap_or(vec!["".to_string()])[0]
            .clone()
    });
    let dauthors = create_memo(cx, || {
        app_state
            .displayingbook
            .get()
            .author_name
            .clone()
            .unwrap_or(vec!["".to_string()])
            .join(", ")
    });

    let handle_close = move |_| {
        app_state.displaying.set(false);

        let dom_node = node_ref.try_get::<DomNode>();
        if dom_node.is_some() {
            dom_node.unwrap().set_attribute("popup-display", "false");
        }
    };

    let handle_edit = move |_| {
        app_state.displaying.set(false);
        let dom_node = node_ref.try_get::<DomNode>();
        if dom_node.is_some() {
            dom_node.unwrap().set_attribute("popup-display", "false");
        }

        app_state.addingbook.set((*(*displaybook.get())).clone());
        app_state.updating.set(true);
    };

    create_effect(cx, || {
        if *app_state.displaying.get() == true {
            let dom_node = node_ref.try_get::<DomNode>();
            if dom_node.is_some() {
                dom_node.unwrap().set_attribute("popup-display", "true");
            }
        } else {
            let dom_node = node_ref.try_get::<DomNode>();
            if dom_node.is_some() {
                dom_node.unwrap().set_attribute("popup-display", "false");
            }
        }
    });

    let handle_click_close = |event: Event| {
        let target: EventTarget = event.target().unwrap();
        let element: web_sys::Element = target.unchecked_into();
        if element.has_attribute("closable") {
            app_state.displaying.set(false);

            let dom_node = node_ref.try_get::<DomNode>();
            if dom_node.is_some() {
                dom_node.unwrap().set_attribute("popup-display", "false");
            }
        }
    };

    view! {cx,
         div(class="modal-box", ref=node_ref, on:click=handle_click_close, closable="true"){

       (if *app_state.displaying.get() == true  {
                view!{ cx,

        div(class="modal-content"){

        div(class="more-info"){
                div(class="more-info-buttons gap-x-3"){

                button( class="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 border-black-500  rounded inline-flex items-center", on:click=handle_close){ i(class="fa-solid fa-xmark") }
                (if *app_state.editmode.get() == true  {
                view!{ cx,
                button( class="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 border-black-500  rounded inline-flex items-center", on:click=handle_edit){ i(class="fa-solid fa-pen-to-square") }}
                } else {
                view!{cx, ""}
                })
                }
                div(class="flex flex-wrap w-full"){

                div(class="flex w-4/5"){
                    div(class="grid grid-cols-4 md:grid-cols-4 gap-x-3"){
                    label(class="font-bold col-start-1"){"Title: "}
                    p(class="col-span-3"){
                    (format!("{}",dtitle.get()))
                    }
                    label(class="font-bold col-start-1"){"Authors: "}
                    p(class="col-span-3"){
                    (format!("{}",dauthors.get()))
                    }
                    label(class="font-bold col-start-1"){"Location: "}
                    p(class="col-span-3"){
                    (format!("{}",dlocation.get()))
                    }
                    label(class="font-bold col-start-1"){"Editions: "}
                    p(class="col-span-3"){
                    (format!("{}",deditions.get()))
                    }
                    label(class="font-bold col-start-1"){"Publish Year: "}
                    p(class="col-span-3"){
                    (format!("{}",dpubyr.get()))
                    }
                    label(class="font-bold col-start-1"){"Page Count: "}
                    p(class="col-span-3"){
                    (format!("{}",dpages.get()))
                    }
                    label(class="font-bold col-start-1"){"Openlibrary Link: "}
                    p(class="col-span-3 text-blue-800"){
                    a(href=dollink.get().clone()){(format!("{}",dollink.get()))}
                    }
                    label(class="font-bold col-start-1"){"GoodReads Link: "}
                    p(class="col-span-3 text-blue-800"){
                    a(href=dgoodread.get().clone()){(format!("{}",dgoodread.get()))}
                    }
                    label(class="font-bold col-start-1"){"ISBN: "}
                    p(class="col-span-3"){
                    (format!("{}",disbn.get()))
                    }
                    label(class="font-bold col-start-1"){"Comments: "}
                    p(class="col-span-3"){
                    (format!("{}",dcomments.get()))
                    }
                    }
                }
                div(class="flex w-1/5"){
                    img(class="float-right m-1",src=coverurl.get(),width="200")
                }

                div(class="grid grid-cols-5 md:grid-cols-5 gap-x-3"){
                label(class="font-bold col-start-1"){"Description: "}
                p(class="col-span-4"){
                (format!("{}",ddesc.get()))
                }
                label(class="font-bold col-start-1"){"Tags: "}
                p(class="col-span-4 italic"){
                (format!("{}",dtags.get()))
                }
                }
                }
            }
    }
    }}
    else {
                view!{cx,""}
            })
    }
    }
}

#[component]
async fn PageBar<G: Html>(cx: Scope<'_>) -> View<G> {
    let app_state = use_context::<AppState>(cx);
    let currpg = create_signal(cx, (*app_state.pagenum.get()).to_string());
    let input_ref = create_node_ref(cx);

    create_effect(cx, || {
        // Calling checked.set will also update the `checked` property on the input element.
        currpg.set( (*app_state.pagenum.get()).to_string())
    });

    let handle_add = move |_| {
        if *app_state.pagenum.get() < *app_state.maxpage.get() {
            app_state.pagenum.set(*app_state.pagenum.get() + 1);
            app_state.pagedisplay.set(*app_state.pagenum.get() + 1);
            app_state.refreshing.set(true);
            currpg.set((*app_state.pagenum.get()).to_string());
        }
    };

    let handle_sub = move |_| {
        if *app_state.pagenum.get() > 1 {
            app_state.pagenum.set(*app_state.pagenum.get() - 1);
            app_state.pagedisplay.set(*app_state.pagenum.get() - 1);
            app_state.refreshing.set(true);
            currpg.set((*app_state.pagenum.get()).to_string());
        }
    };

    let handle_submit = |event: Event| {
        let event: KeyboardEvent = event.unchecked_into();

        if event.key() == "Enter" {
            let pg = currpg.get().as_ref().clone().parse::<u32>().unwrap_or(1);
            if pg > 0 && pg <= *app_state.maxpage.get() {
                app_state.pagenum.set(pg);
                app_state.pagedisplay.set(pg);
                app_state.refreshing.set(true);
            } else {
                currpg.set((*app_state.pagenum.get()).to_string());
            }
        }
    };

    /*
    let handle_refresh = move |_| {
        spawn_local(async move {
            refresh_index().await.expect("Couldn't refresh index");
        });
    };*/

    view! {cx,
        //button( class="bg-gray-300 hover:bg-gray-200 text-gray-800 font-bold px-4 rounded inline-flex items-center", on:click=handle_refresh) {"REFRESH"}

       (if (*app_state.openlibrary.get() == false || *app_state.internalsearch.get() == true) && !app_state.books.get().is_empty() {
                view!{ cx,
                div(class="bg-gray-300 text-gray-800 font-bold px-1 rounded inline-flex items-center w-max"){
                i(class="fa-solid fa-file") span(class="hidden md:block-inline"){p{"#"}}
                input(type="number", ref=input_ref,bind:value=currpg,on:keyup=handle_submit,class="page-input [appearance:textfield] mx-1 my-0 px-1 min-w-30 w-30 max-w-40", size="1")
                div(class="flex-inline"){(format!(" / {}",*app_state.maxpage.get()))}
                }
                (if *app_state.pagenum.get()>1 {
                view!{cx, button( class="bg-gray-300 hover:bg-gray-200 text-gray-800 font-bold px-4 rounded inline-flex items-center", on:click=handle_sub){ "-" }}
                } else {
                view!{cx,""}
                })
                (if *app_state.pagenum.get()<*app_state.maxpage.get() {
                view!{cx, button( class="bg-gray-300 hover:bg-gray-200 text-gray-800 font-bold px-4 rounded inline-flex items-center", on:click=handle_add){ "+" }}
                } else {
                view!{cx,""}
                })
                }
        }else {
                view!{cx,
                div(class="bg-gray-300 text-gray-800 font-bold px-1 rounded inline-flex items-center w-max"){
                ("Zero Pages")
                }
                }
            })


    }
}

#[component]
async fn LoginScreenUI<G: Html>(cx: Scope<'_>) -> View<G> {
    let app_state = use_context::<AppState>(cx);
    let userval = create_signal(cx, String::new());
    let input_refU = create_node_ref(cx);
    let passval = create_signal(cx, String::new());
    let input_refP = create_node_ref(cx);
    let node_ref = create_node_ref(cx);

    let handle_register = move |_| {
        let app_state = app_state.clone();
        let user = AxumUser {
            id: 0,
            name: (*userval.get()).clone(),
            password_hash: (*passval.get()).clone(),
        };
        spawn_local(async move {
            let resp = register_user(user).await;
            //.expect("Couldn't register user");
            if resp.is_err() {
                app_state
                    .warningmsg
                    .set("Failed to register user".to_string());
            } else {
                app_state
                    .warningmsg
                    .set("Successfully registered user".to_string());
            }
        });
        spawn_local(async move {
            app_state
                .userlist
                .set(list_users().await.expect("Couldn't list user"));
        });
        //app_state.userscreen.set(false);
    };

    let handle_login = move |_| {
        let app_state = app_state.clone();
        let userstr = (*userval.get()).clone();
        let user = AxumUser {
            id: 0,
            name: (*userval.get()).clone(),
            password_hash: (*passval.get()).clone(),
        };

        spawn_local(async move {
            app_state
                .userlist
                .set(list_users().await.expect("Couldn't list user"));
            login_user(user).await.expect("Couldn't login user");
            let auth = authentication_check().await.unwrap_or(false);
            app_state.loggedin.set(auth);
            if auth == true {
                app_state.loggedusername.set(userstr.clone());
                app_state.selectedusername.set(userstr.clone());
                app_state
                    .useridloggedin
                    .set(*(*app_state.userlist.get()).get(&userstr).unwrap_or(&0));
                app_state
                    .userid
                    .set(*(*app_state.userlist.get()).get(&userstr).unwrap_or(&0));
                app_state.userscreen.set(false);
                app_state.warningmsg.set("".to_string());
            } else {
                app_state.warningmsg.set("Failed to login".to_string());
            }
        });
    };

    let handle_submit_login = |event: Event| {
        let event: KeyboardEvent = event.unchecked_into();

        if event.key() == "Enter" {
            let app_state = app_state.clone();
            let userstr = (*userval.get()).clone();
            let user = AxumUser {
                id: 0,
                name: (*userval.get()).clone(),
                password_hash: (*passval.get()).clone(),
            };
            spawn_local(async move {
                app_state
                    .userlist
                    .set(list_users().await.expect("Couldn't list user"));
                login_user(user).await.expect("Couldn't login user");
                let auth = authentication_check().await.unwrap_or(false);
                app_state.loggedin.set(auth);
                if auth == true {
                    app_state.loggedusername.set(userstr.clone());
                    app_state.selectedusername.set(userstr.clone());
                    app_state
                        .useridloggedin
                        .set(*((*app_state.userlist.get()).get(&userstr).unwrap_or(&0)));
                    app_state
                        .userid
                        .set(*(*app_state.userlist.get()).get(&userstr).unwrap_or(&0));
                    app_state.userscreen.set(false);
                    app_state.warningmsg.set("".to_string());
                } else {
                    app_state.warningmsg.set("Failed to login".to_string());
                }
            });
        }
    };

    create_effect(cx, || {
        if *app_state.userscreen.get() == true {
            let dom_node = node_ref.try_get::<DomNode>();
            if dom_node.is_some() {
                dom_node.unwrap().set_attribute("popup-display", "true");
            }
        } else {
            let dom_node = node_ref.try_get::<DomNode>();
            if dom_node.is_some() {
                dom_node.unwrap().set_attribute("popup-display", "false");
            }
        }
    });
    let handle_close = move |_| {
        app_state.userscreen.set(false);

        let dom_node = node_ref.try_get::<DomNode>();
        if dom_node.is_some() {
            dom_node.unwrap().set_attribute("popup-display", "false");
        }
    };

    let handle_click_close = |event: Event| {
        let target: EventTarget = event.target().unwrap();
        let element: web_sys::Element = target.unchecked_into();
        if element.has_attribute("closable") {
            app_state.userscreen.set(false);

            let dom_node = node_ref.try_get::<DomNode>();
            if dom_node.is_some() {
                dom_node.unwrap().set_attribute("popup-display", "false");
            }
        }
    };

    view! {cx,
        div(class="modal-box mt-100", ref=node_ref, on:click=handle_click_close, closable="true"){

       (if *app_state.userscreen.get() == true {
                view!{cx,
        div(class="mt-100 bg-white shadow-md rounded px-8 pt-8 pb-8 m-4"){
                label{"Username : "}
                input(ref=input_refU,bind:value=userval, placeholder="Username", class="text-sm sm:text-base placeholder-gray-500 pl-10 pr-4 rounded-lg border border-gray-400 w-full py-2 focus:outline-none focus:border-blue-400")
                br{}
                label{"Password : "}
                input(ref=input_refP,bind:value=passval,type="password", placeholder="*****",
                on:keyup=handle_submit_login, class="text-sm sm:text-base placeholder-gray-500 pl-10 pr-4 rounded-lg border border-gray-400 w-full py-2 focus:outline-none focus:border-blue-400")
                br{}br{}
                div(class="w-full flex gap-1"){
                button( class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 inline-flex items-center  border-b-4  border-blue-700 hover:border-blue-500 w-full",on:click=handle_login){ "LOGIN" }

                button( class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 inline-flex items-center  border-b-4  border-blue-700 hover:border-blue-500 w-full",on:click=handle_register){ "REGISTER" }
                }
                br{}
                div(class="w-full flex flex-col gap-1 items-center"){
                button( class="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded inline-flex items-center w-1/3 gap-x-1", on:click=handle_close){ i(class="fa-solid fa-xmark") span(class="inline-flex"){"CLOSE"} }
                }

                (if *app_state.warningmsg.get() != "".to_string() {
                    view!{cx, (*app_state.warningmsg.get())}
                } else {
                    view!{cx, ""}
                })

                }
                }
        }else {
                view!{cx,""}
            })
        }

    }
}

#[component]
fn App<G: Html>(cx: Scope) -> View<G> {
    let app_state = AppState {
        books: create_rc_signal(Vec::new()),
        search: create_rc_signal(String::default()),
        openlibrary: create_rc_signal(bool::default()),
        internalsearch: create_rc_signal(bool::default()),
        pagedisplay: create_rc_signal(1),
        pagenum: create_rc_signal(1),
        maxpage: create_rc_signal(1),
        adding: create_rc_signal(bool::default()),
        updating: create_rc_signal(bool::default()),
        addingbook: create_rc_signal(BookUI::default()),
        displaying: create_rc_signal(bool::default()),
        displayingbook: create_rc_signal(BookUI::default()),
        refreshing: create_rc_signal(true),
        apibook: create_rc_signal(BookUI::default()),
        updatingrequest: create_rc_signal(bool::default()),
        addingrequest: create_rc_signal(bool::default()),
        deleteid: create_rc_signal(-1),
        deleterequest: create_rc_signal(bool::default()),
        userlist: create_rc_signal(HashMap::new()),
        userid: create_rc_signal(1),
        selectedusername: create_rc_signal(String::new()),
        loggedusername: create_rc_signal(String::new()),
        useridloggedin: create_rc_signal(0),
        userscreen: create_rc_signal(bool::default()),
        loggedin: create_rc_signal(false),
        editmode: create_rc_signal(bool::default()),
        dropdownselect: create_rc_signal(bool::default()),
        scrolling: create_rc_signal(bool::default()),
        scrollevent: create_rc_signal(bool::default()),
        menuexpand: create_rc_signal(bool::default()),
        warningmsg: create_rc_signal("".to_string()),
    };
    provide_context(cx, app_state);

    view! {
        cx,
        div {
            Header {}
            MenuExpanded {}
            main(class="relative"){
            WarningMessageBar{}
            LoginScreenUI{}
            AddingUI{}
            SelectedUI{}
            ListOL {}
            ListDB{}
            }
            }
    }
}

fn main() {
    console_error_panic_hook::set_once();
    console_log::init_with_level(log::Level::Debug).unwrap();

    sycamore::render(|cx| view! { cx, App {} });
}
