import { LitElement, html, css } from 'https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js';

export class PartsTable extends LitElement {
  static properties = {
    items: { type: Array },
    _fPartnum: { state: true },
    _fDesc: { state: true },
  };

  constructor() {
    super();
    this.items = [];
    this._fPartnum = '';
    this._fDesc = '';
    this._debounceId = null;
  }

  // 👉 Si quieres heredar estilos de Bootstrap, descomenta:
  // createRenderRoot() { return this; }

  static styles = css`
    :host { display: block; }
    section { padding: .5rem; }
    table { width:100%; border-collapse: collapse; }
    thead th { text-align:left; border-bottom: 1px solid #ccc; padding:.5rem; }
    tbody td { border-bottom: 1px solid #eee; padding:.5rem; }
    tbody tr:nth-child(odd){ background: rgba(0,0,0,.03); }
    input[type="text"]{ width:100%; padding:.35rem .5rem; box-sizing:border-box; }
    button{ padding:.25rem .6rem; border:1px solid #ccc; border-radius:.375rem;
            background:#f8f9fa; cursor:pointer; }
    button + button { margin-left:.35rem; }
  `;

  // helpers para tu data
  _getPartnum(it){ return it.PartNum ?? it.partnum ?? ''; }
  _getDesc(it){ return it.PartDescription ?? it.descripcion ?? ''; }
  _getPrecio(it){
    const v = it.LastPrice ?? it.precioUnitario ?? null;
    return v == null ? null : Number(v);
  }
  _fmtMoney(v){
    const n = Number(v ?? 0);
    return n.toLocaleString(undefined, { minimumFractionDigits:2, maximumFractionDigits:2 });
  }

  get _filtered(){
    const fpn = this._fPartnum.trim().toLowerCase();
    const fds = this._fDesc.trim().toLowerCase();
    return this.items.filter(it => {
      const pn = this._getPartnum(it).toLowerCase();
      const ds = this._getDesc(it).toLowerCase();
      return (!fpn || pn.includes(fpn)) && (!fds || ds.includes(fds));
    });
  }

  _onFilter(e, key){
    const val = e.target.value ?? '';
    clearTimeout(this._debounceId);
    this._debounceId = setTimeout(()=>{
      if (key === 'pn') this._fPartnum = val;
      if (key === 'ds') this._fDesc = val;
    }, 100);
  }

  render(){
    const rows = this._filtered;
    return html`
      <section>
        <table class="table table-striped">
          <thead>
            <tr>
              <th>No</th>
              <th>Partnum</th>
              <th>Descripción</th>
              <th>Precio</th>
              <th>Acciones</th>
            </tr>
            <tr>
              <th></th>
              <th><input type="text" placeholder="Buscar Partnum"
                         @input=${e=>this._onFilter(e,'pn')}></th>
              <th><input type="text" placeholder="Buscar Descripción"
                         @input=${e=>this._onFilter(e,'ds')}></th>
              <th></th><th></th>
            </tr>
          </thead>
          <tbody>
            ${rows.length === 0 ? html`
              <tr><td colspan="5">Sin resultados…</td></tr>
            ` : rows.map((it,i)=> html`
              <tr>
                <td>${i+1}</td>
                <td>${this._getPartnum(it)}</td>
                <td>${this._getDesc(it)}</td>
                <td>${this._fmtMoney(this._getPrecio(it))}</td>
                <td>
                  <button @click=${()=>this.dispatchEvent(new CustomEvent('edit-item',
                    { detail:{item:it,index:i}, bubbles:true, composed:true }))}>Editar</button>
                  <button @click=${()=>this.dispatchEvent(new CustomEvent('delete-item',
                    { detail:{index:i}, bubbles:true, composed:true }))}>Eliminar</button>
                </td>
              </tr>
            `)}
          </tbody>
        </table>
      </section>
    `;
  }
}

customElements.define('parts-table', PartsTable);
