use dioxus::prelude::*;

use crate::auth::{ToastState, broadcast_sign_out, logout_url};
use crate::session::SessionIdentity;

#[component]
pub(crate) fn SessionControl(session: Signal<SessionIdentity>, toasts: Signal<ToastState>) -> Element {
    let identity = session.read().clone();

    match identity {
        SessionIdentity::Anonymous => rsx! {
            form {
                class: "session-control",
                action: "/oauth/start",
                method: "get",
                input {
                    r#type: "text",
                    name: "identifier",
                    placeholder: "handle.test",
                    aria_label: "ATProto handle",
                }
                button { class: "button button-primary", r#type: "submit", "Sign in" }
            }
        },
        SessionIdentity::Authenticated(identity) => {
            let label = SessionIdentity::Authenticated(identity).label();
            rsx! {
                div { class: "session-control session-control-authenticated",
                    span { class: "status-pill", "{label}" }
                    form {
                        method: "post",
                        action: "{logout_url()}",
                        button {
                            class: "button button-secondary",
                            r#type: "submit",
                            onclick: move |_| {
                                broadcast_sign_out();
                                session.set(SessionIdentity::Anonymous);
                                toasts.write().push("Signing out…");
                            },
                            "Sign out"
                        }
                    }
                }
            }
        }
    }
}

#[component]
pub(crate) fn ToastShelf(toasts: Signal<ToastState>) -> Element {
    let items = toasts.read().items().to_vec();

    rsx! {
        div { class: "toast-shelf", aria_live: "polite",
            for toast in items {
                div { key: "toast-{toast.id}", class: "toast blueprint-panel",
                    span { "{toast.message}" }
                    button {
                        class: "toast-dismiss",
                        aria_label: "Dismiss notification",
                        onclick: move |_| toasts.write().dismiss(toast.id),
                        "×"
                    }
                }
            }
        }
    }
}
