use crate::locales::trl;
use leptos::*;

#[derive(Copy, Clone)]
pub struct DialogOpener {
    visible: ReadSignal<bool>,
    set_visible: WriteSignal<bool>,
}

impl DialogOpener {
    pub fn new() -> Self {
        let (visible, set_visible) = create_signal(false);
        DialogOpener {
            visible,
            set_visible,
        }
    }

    pub fn visible(&self) -> bool {
        self.visible.get()
    }

    pub fn show(&self) {
        self.set_visible.update(|state| *state = true);
    }

    pub fn hide(&self) {
        self.set_visible.update(|state| *state = false);
    }
}

#[component]
pub fn ModalDialog(
    opener: DialogOpener,
    title: &'static str,
    children: Children,
) -> impl IntoView {
    view! {
        <div class={ move || if opener.visible() {"modal fade show"} else {"modal fade"}}
            style={ move || if opener.visible() {"display: block;"} else {""}}
            id="modalCenter" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalCenterTitle">{trl(title)}</h5>
                        <button
                            type="button"
                            class="btn-close"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                            on:click=move |_| opener.hide()/>
                        </div>
                        {children()}
                    </div>
                </div>
            </div>
    }
}

#[component]
pub fn ModalBody(children: Children) -> impl IntoView {
    view! {
        <div class="modal-body">
            {children()}
        </div>
    }
}

#[component]
pub fn ModalFooter(children: Children) -> impl IntoView {
    view! {
        <div class="modal-footer">
           {children()}
        </div>
    }
}

#[component]
pub fn DlgNotLoaded(opener: DialogOpener, title: &'static str) -> impl IntoView {
    view! {
        <ModalDialog opener=opener title=title>
        <ModalBody>
            <div>{trl("Entity not loaded")}</div>
        </ModalBody>
        <ModalFooter>
            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal" on:click=move |_| opener.hide()>
                {trl("Close")}
            </button>
        </ModalFooter>
        </ModalDialog>
    }
}
