use leptos::*;
use crate::backend::data::{ApiResponse, User};
use crate::backend::user::get_users;
use crate::components::modal_box::DialogOpener;
use crate::components::user_menu::MenuOpener;
use crate::locales::trl;
use crate::pages::change_pwd::ChangePassword;
use crate::pages::profile_edit::ProfileEdit;
use crate::pages::user_delete::UserDelete;
use crate::pages::user_edit::UserEdit;
use leptos_use::use_media_query;

#[component]
pub fn users() -> impl IntoView {
    let editor = DialogOpener::new();
    let profile_editor = DialogOpener::new();
    let pwd_dialog = DialogOpener::new();
    let delete_dialog = DialogOpener::new();
    let users = create_blocking_resource(
        move || editor.visible() || profile_editor.visible() || delete_dialog.visible(), move |_| {get_users()});
    let (usr, set_usr) = create_signal::<Vec<User>>(vec![]);
    let (profile, set_profile) = create_signal(User::default());
    let is_wide = use_media_query("(min-width: 500px)");

    view! {
        <UserEdit opener=editor/>
        <ProfileEdit user=profile opener=profile_editor/>
        <ChangePassword opener=pwd_dialog user=profile/>
        <UserDelete opener=delete_dialog user=profile/>
        <div class="card mb-3">
        <div class="card-body">
            <h5 class="card-title"><i class="bx bx-user"></i>" "{trl("Users")}</h5>
            <Transition fallback=move || view! {<p>{trl("Loading...")}</p> }>
            <table class="table card-table">
                <thead>
                    <tr>
                        <th>{trl("Username")}</th>
                        {move || if is_wide.get() {view! {<th>{trl("Full name")}</th>}}
                            else {view! {<th></th>}} }
                        <th>{trl("Admin")}</th>
                        <th>{trl("Actions")}</th>
                    </tr>
                </thead>
            {move || {
                users.get().map(|u| match u {
                    Err(e) => {
                        let err = if e.to_string().contains("403") {
                            "Only admin can edit users".to_string()
                        } else {
                            e.to_string()
                        };
                        view! {<tbody class="table-border-bottom-0">
                        <tr><td colspan=4>{trl(&err)}</td></tr></tbody>}}
                    Ok(u) => {
                        match u {
                            ApiResponse::Data(u) => {
                                set_usr.update(|users| *users = u.clone());
                                view! {<tbody class="table-border-bottom-0">
                                    <For each=move || usr.get()
                                        key=|user| user.id()
                                        children=move |user: User| {
                                        let menu = MenuOpener::new();
                                        let user_profile = user.clone();
                                        let user_passwd = user.clone();
                                        let user_delete = user.clone();
                                        let full_name = user.full_name.clone().unwrap_or("".to_string());
                                        view! {
                                            <tr>
                                                <td>{&user.login}</td>
                                                {move || if is_wide.get() {view! {<td>{full_name.clone()}</td>}}
                                                    else {view! {<td></td>}} }
                                                <td>{if user.admin {view! {<i class="bx bx-check"></i>}}
                                                    else {view! {<i></i>}}}</td>
                                                <td>
                                                <div class="dropdown">
                                                    <button type="button" class="btn p-0 dropdown-toggle hide-arrow"
                                                        on:click=move |_| menu.toggle()>
                                                        <i class="bx bx-dots-vertical-rounded"></i>
                                                    </button>
                                                    <div class={move || if menu.visible() {"dropdown-menu show"} else {"dropdown-menu"} }
                                                    style="position: absolute; insert: 0px 0px auto; margin: 0px; transform: translate3d(-160px, 0px, 0px);"
                                                    on:mouseleave=move |_| menu.toggle()>
                                                        <a class="dropdown-item" href="javascript:void(0);" on:click=move |_| {
                                                                set_profile.set(user_profile.clone());
                                                                profile_editor.show();
                                                            }>
                                                            <i class="bx bx-edit-alt me-1"></i> {trl("Edit")}</a>
                                                        <a class="dropdown-item" href="javascript:void(0);" on:click=move |_| {
                                                                set_profile.set(user_passwd.clone());
                                                                pwd_dialog.show();
                                                            }>
                                                            <i class="bx bx-lock me-1"></i> {trl("Change password")}</a>
                                                        <a class="dropdown-item text-danger" href="javascript:void(0);" on:click=move |_| {
                                                                set_profile.set(user_delete.clone());
                                                                delete_dialog.show();
                                                            }>
                                                            <i class="bx bx-trash me-1"></i> {trl("Delete")}</a>
                                                    </div>
                                                </div>
                                                </td>
                                            </tr>
                                        }
                                    }/></tbody>
                                }
                            }
                            ApiResponse::Error(e) => {view! {<tbody class="table-border-bottom-0">
                                <tr><td colspan=4>{trl(&e)}</td></tr></tbody>}}
                        }
                    }
                })
            }}
            </table>
            </Transition>
            <a href="#" class="card-link" on:click=move |_| editor.show()>
                <i class="bx bx-plus-circle fs-4 lh-0"></i>
            </a>

        </div>
        </div>
    }
}