use leptos::*;
use crate::backend::company::get_company;
use crate::backend::data::{ApiResponse, 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_blocking_resource(move|| editor.visible(), move |_| { get_company() });
    let (cmp, set_cmp) = create_signal(Company::default());

    view! {
        <CompanyEdit company={cmp} opener=editor/>
      <div class="card mb-3">
        <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.get().map(|c| match c {
                        Err(e) => {view! {<div><p>{trl("Error loading data")}</p>
                            <p>{e.to_string()}</p></div>
                        }}
                        Ok(c) => {
                            match c {
                                ApiResponse::Data(d) => {set_cmp.update(|cmp| *cmp = d.clone());
                                    view! {<div>
                                    <p><b>{d.name}</b></p>
                                    <p>{d.street}" "{d.house_number}<br/>
                                    {d.zip_code}" "{d.city}
                                    </p></div>}
                                }
                                ApiResponse::Error(_) => {view! {<div><p>{trl("Error loading data")}</p></div>}}
                            }

                        }
                    })
                }}
            </Transition>
          </p>
          <a href="javascript:void(0)" class="card-link" on:click = move |_| editor.show()>
                <i class="bx bx-edit-alt fs-4 lh-0"></i></a>
        </div>
      </div>
    }
}