use leptos::*;
use crate::backend::data::User;
use crate::backend::user::{ChangePwd, get_user};
use crate::components::data_form::DataForm;
use crate::components::modal_box::DialogOpener;
use crate::locales::trl;

#[component]
pub fn change_password(user: ReadSignal<User>, opener: DialogOpener) -> impl IntoView {
    let change_pwd = create_server_action::<ChangePwd>();
    let logged_in = create_resource(||(), move |_| get_user());

    view! {
        <DataForm opener=opener action=change_pwd title="Change password">
        <input type="hidden" value={move || user.get().login} name="new_pw[login]"/>
        <Suspense fallback=move || view! {<div></div>}>
        <div class="row">
            <div class="col mb-3" style={move || {
                logged_in.get().map(|u| { match u {
                    Ok(u) => {
                        if let Some(u) = u {
                            if u.login != user.get().login && u.admin { "display: none" } else { "" }
                        } else { "" }
                    }
                    Err(_) => ""
                }})
            }}>
                <label  for="oldPw" class="form-label">{trl("Old password")}</label>
                <input
                    type="password"
                    id="oldPw"
                    class="form-control"
                    name="new_pw[old_password]"
                    prop:value={move || opener.empty()}
                />
            </div>
        </div>
        </Suspense>
        <div class="row">
            <div class="col mb-3">
                <label  for="newPw" class="form-label">{trl("New password")}</label>
                <input
                    type="password"
                    id="newPw"
                    class="form-control"
                    name="new_pw[password]"
                    prop:value={move || opener.empty()}
                />
            </div>
        </div>
        <div class="row">
            <div class="col mb-3">
                <label  for="verPw" class="form-label">{trl("Verify password")}</label>
                <input
                    type="password"
                    id="verPw"
                    class="form-control"
                    name="new_pw[password_ver]"
                    prop:value={move || opener.empty()}
                />
            </div>
        </div>
        </DataForm>
    }
}