use leptos::*;
use serde::de::Unexpected::Option;
use crate::backend::company::get_company;
use crate::backend::data::Company;
use crate::components::modal_box::DialogOpener;
use crate::locales::trl;
use crate::pages::company_edit::CompanyEdit;

#[component]
pub fn CompanyInfo() -> impl IntoView {
    let editor = DialogOpener::new();
    let company = create_resource(move|| editor.visible(), move |_| { get_company() });
    let (cmp, set_cmp) = create_signal(Company::default());

    view! {
        <CompanyEdit company={cmp} opener=editor/>
      <div class="card">
        <div class="card-body">
          <h5 class="card-title"><i class="bx bx-buildings"></i>" "{trl("Company info")}</h5>
          <p class="card-text">
            <Transition fallback=move || view! {<p>{trl("Loading...")}</p> }>
                {move || {
                    company.read().map(|c| match c {
                        Err(e) => {view! {<p>{trl("Error loading data")}</p>
                            <p>{e.to_string()}</p>
                        }}
                        Ok(c) => {
                            set_cmp.update(|cmp| *cmp = c.clone());
                            view! {
                            <p><b>{c.name}</b></p>
                            <p>{c.street}" "{c.house_number}<br/>
                            {c.zip_code}" "{c.city}
                            </p>
                        }}
                    })
                }}
            </Transition>
          </p>
          <a href="javascript:void(0)" class="card-link" on:click = move |_| editor.show()>
                <i class="bx bx-pencil fs-4 lh-0"></i></a>
        </div>
      </div>
    }
}