use leptos::*;
use crate::backend::customer::get_customers;
use crate::backend::data::ApiResponse;
use crate::locales::trl;

#[component]
pub fn customers() -> impl IntoView {
    let customers = create_blocking_resource(||(), |_| get_customers());

    view! {
        <h1>{trl("Customers")}</h1>
        <div class="row mb-3">
            <div class="card">
            <div class="card-body">
                <Transition fallback=move || view! {<div>"Loading"</div>}>
                    <table class="table card-table">
                        <thead>
                            <tr>
                                <th>{trl("Full name")}</th>
                                <th>{trl("E-mail")}</th>
                                <th>{trl("Phone")}</th>
                            </tr>
                        </thead>
                {
                    customers.get().map(|c| match c {
                        Ok(c) => {match c {
                            ApiResponse::Data(c) => {
                                view! {
                                <tbody>
                                <For each=move || c.clone() key=|i| i.id() let:data>
                                    <tr>
                                        <td>{data.full_name}</td>
                                        <td>{data.email}</td>
                                        <td>{data.phone}</td>
                                    </tr>
                                </For>
                                </tbody>
                                }
                            }
                            ApiResponse::Error(e) => {
                                view! {<tbody class="table-border-bottom-0">
                                <tr><td colspan=3>{trl("Something went wrong")}<br/>{e.to_string()}</td></tr></tbody>}
                            }
                        }
                        }
                        Err(e) => {
                            view! {<tbody class="table-border-bottom-0">
                            <tr><td colspan=3>{trl("Something went wrong")}<br/>{e.to_string()}</td></tr></tbody>}
                        }
                    })
                }
                    </table>
                </Transition>
            </div>
            </div>
        </div>
    }
}