pub mod migration;

use dioxus::prelude::*;

use crate::util::model::member::Member;

pub fn Members() -> Element {
    let members = use_resource(fetch_members);

    rsx! {
        div {
            class: "flex justify-center",
            div {
                class: "max-w-4xl w-full",
                h2 { class: "font-bold text-lg", "Leden" },
                match &*members.read_unchecked() {
                    Some(Ok(res)) => rsx! {
                        div {
                            class: "overflow-x-auto",
                            table {
                                class: "table table-zebra table-pin-rows",
                                thead {
                                    tr {
                                        th { "Relatiecode" }
                                        th { "Naam" }
                                        th { "Registratiecode" }
                                    }
                                }
                                tbody {
                                    for member in res {
                                        MemberRow { member: member.clone() }
                                    }
                                }
                            }
                        }
                    },
                    Some(Err(_)) => rsx! { div { "Error while loading members" } },
                    None => rsx! { div { "Loading..." } },
                }
            }
        }
    }
}

#[derive(Props, Clone, PartialEq)]
struct MemberRowProps {
    member: Member,
}

fn MemberRow(props: MemberRowProps) -> Element {
    let registration_token = props
        .member
        .registration_token
        .unwrap_or("None".to_string());

    rsx! {
        tr {
            class: "hover hover:cursor-pointer",
            th { "{props.member.id}" }
            td { "{props.member.name.full}" }
            td { "{registration_token}" }
        }
    }
}

#[server]
async fn fetch_members() -> Result<Vec<Member>, ServerFnError> {
    let members = Member::fetch_all().await?;
    Ok(members)
}
