// C2 (end-customer) views: Saldi + Movimenti

const { useState: useStateC2, useMemo: useMemoC2 } = React;

function C2Saldi({ tenant, c2 }) {
  const [q, setQ] = useStateC2("");
  const [desc, setDesc] = useStateC2("");
  const [lotto, setLotto] = useStateC2("");
  const [includeZero, setIncludeZero] = useStateC2(false);
  const [page, setPage] = useStateC2(1);
  const pageSize = 14;

  const all = MOCK.articles;
  const filtered = useMemoC2(() => {
    return all.filter(a => {
      if (!includeZero && a.qty === 0) return false;
      if (q && !a.codice.toLowerCase().includes(q.toLowerCase())) return false;
      if (desc && !a.desc.toLowerCase().includes(desc.toLowerCase())) return false;
      if (lotto && !(a.lotto || "").toLowerCase().includes(lotto.toLowerCase())) return false;
      return true;
    });
  }, [q, desc, lotto, includeZero]);

  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
  const pageItems = filtered.slice((page - 1) * pageSize, page * pageSize);
  const total = filtered.reduce((s, a) => s + a.qty, 0);

  const showLotto = c2.showLotto;

  return (
    <div>
      <SectionH>Criteri di selezione</SectionH>
      <div className="panel mb-16">
        <div className="panel-body">
          <div className="filter-bar">
            <div className="field">
              <label>Articolo</label>
              <input type="text" value={q} onChange={(e) => { setQ(e.target.value); setPage(1); }}/>
            </div>
            <div className="field">
              <label>Descrizione</label>
              <input type="text" value={desc} onChange={(e) => { setDesc(e.target.value); setPage(1); }}/>
            </div>
            {showLotto && (
              <div className="field">
                <label>Lotto</label>
                <input type="text" value={lotto} onChange={(e) => { setLotto(e.target.value); setPage(1); }}/>
              </div>
            )}
            <Checkbox checked={includeZero} onChange={setIncludeZero} label="Includere saldi nulli"/>
            <button className="btn btn-primary">
              <span className="icon">{Icon.search}</span>Ricerca
            </button>
          </div>
        </div>
      </div>

      <SectionH>Saldi di magazzino <span style={{color: "var(--text-3)", fontWeight: 400, fontSize: 13}}>· Aggiornato {c2.lastImport}</span></SectionH>

      <div className="table-wrap">
        <table className="data">
          <thead>
            <tr>
              <th style={{width: "20%"}}>Articolo</th>
              <th>Descrizione</th>
              {showLotto && <th style={{width: "12%"}}>Lotto</th>}
              <th className="num" style={{width: "10%"}}>Pezzi</th>
            </tr>
          </thead>
          <tbody>
            {pageItems.map(a => (
              <tr key={a.codice}>
                <td className="mono"><strong>{a.codice}</strong></td>
                <td>{a.desc}</td>
                {showLotto && <td className="mono muted">{a.lotto || "—"}</td>}
                <td className="num"><strong>{a.qty.toLocaleString("it-CH")}</strong></td>
              </tr>
            ))}
            {pageItems.length === 0 && (
              <tr><td colSpan={5} className="empty">Nessun risultato per i criteri impostati</td></tr>
            )}
          </tbody>
        </table>
        <Pagination page={page} totalPages={totalPages} onChange={setPage} total={total} totalLabel="Totale"/>
      </div>

      <div style={{marginTop: 14, display: "flex", justifyContent: "flex-start"}}>
        <a className="export-link"><span className="icon">{Icon.download}</span> Esporta in Excel</a>
      </div>
    </div>
  );
}

function C2Movimenti({ tenant, c2 }) {
  const [q, setQ] = useStateC2("");
  const [from, setFrom] = useStateC2("2026-04-12");
  const [to, setTo] = useStateC2("2026-05-12");
  const [tipo, setTipo] = useStateC2("");
  const [page, setPage] = useStateC2(1);
  const pageSize = 16;

  const filtered = useMemoC2(() => {
    return MOCK.movements.filter(m => {
      if (q && !(m.codice.toLowerCase().includes(q.toLowerCase()) || m.desc.toLowerCase().includes(q.toLowerCase()))) return false;
      if (from && m.date < from) return false;
      if (to && m.date > to) return false;
      if (tipo && m.type !== tipo) return false;
      return true;
    });
  }, [q, from, to, tipo]);

  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
  const pageItems = filtered.slice((page - 1) * pageSize, page * pageSize);
  const totalIn = filtered.filter(m => m.type === "in").reduce((s, m) => s + m.qty, 0);
  const totalOut = filtered.filter(m => m.type === "out").reduce((s, m) => s + m.qty, 0);

  return (
    <div>
      <SectionH>Criteri di selezione</SectionH>
      <div className="panel mb-16">
        <div className="panel-body">
          <div className="filter-bar" style={{gridTemplateColumns: "1.4fr 1fr 1fr 1fr auto"}}>
            <div className="field">
              <label>Articolo o descrizione</label>
              <input type="text" value={q} onChange={(e) => { setQ(e.target.value); setPage(1); }}/>
            </div>
            <div className="field">
              <label>Dal</label>
              <input type="date" value={from} onChange={(e) => setFrom(e.target.value)}/>
            </div>
            <div className="field">
              <label>Al</label>
              <input type="date" value={to} onChange={(e) => setTo(e.target.value)}/>
            </div>
            <div className="field">
              <label>Tipo</label>
              <select value={tipo} onChange={(e) => setTipo(e.target.value)}>
                <option value="">Tutti</option>
                <option value="in">Solo carichi</option>
                <option value="out">Solo scarichi</option>
              </select>
            </div>
            <button className="btn btn-primary">
              <span className="icon">{Icon.search}</span>Ricerca
            </button>
          </div>
        </div>
      </div>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="label">Movimenti nel periodo</div>
          <div className="value">{filtered.length.toLocaleString("it-CH")}</div>
          <div className="delta">tra {from} e {to}</div>
        </div>
        <div className="stat-card">
          <div className="label">Pezzi in entrata</div>
          <div className="value" style={{color: "var(--ok)"}}>+{totalIn.toLocaleString("it-CH")}</div>
          <Sparkline values={[12, 18, 14, 22, 28, 24, 32, 30, 38, 36, 42, 48]} color="var(--ok)"/>
        </div>
        <div className="stat-card">
          <div className="label">Pezzi in uscita</div>
          <div className="value" style={{color: "var(--err)"}}>−{Math.abs(totalOut).toLocaleString("it-CH")}</div>
          <Sparkline values={[8, 14, 10, 16, 20, 18, 24, 28, 26, 30, 28, 34]} color="var(--err)"/>
        </div>
        <div className="stat-card">
          <div className="label">Bilancio netto</div>
          <div className="value">{(totalIn + totalOut).toLocaleString("it-CH")}</div>
          <div className="delta">pezzi · solo periodo</div>
        </div>
      </div>

      <SectionH>Movimenti di magazzino</SectionH>
      <div className="table-wrap">
        <table className="data">
          <thead>
            <tr>
              <th style={{width: "9%"}}>Data</th>
              <th style={{width: "5%"}}>Ora</th>
              <th style={{width: "14%"}}>Articolo</th>
              <th>Descrizione</th>
              {c2.showLotto && <th style={{width: "10%"}}>Lotto</th>}
              <th style={{width: "13%"}}>Causale</th>
              <th style={{width: "12%"}}>Riferimento</th>
              <th className="num" style={{width: "8%"}}>Quantità</th>
            </tr>
          </thead>
          <tbody>
            {pageItems.map(m => (
              <tr key={m.id}>
                <td className="mono">{m.date}</td>
                <td className="mono muted">{m.time}</td>
                <td className="mono"><strong>{m.codice}</strong></td>
                <td>{m.desc}</td>
                {c2.showLotto && <td className="mono muted">{m.lotto || "—"}</td>}
                <td><Badge type={m.type === "in" ? "ok" : "err"} dot>{m.causaleLabel}</Badge></td>
                <td className="mono muted">{m.ddt}</td>
                <td className={"num " + (m.type === "in" ? "mvt-in" : "mvt-out")}>
                  {m.type === "in" ? "+" : ""}{m.qty.toLocaleString("it-CH")}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        <Pagination page={page} totalPages={totalPages} onChange={setPage}/>
      </div>

      <div style={{marginTop: 14}}>
        <a className="export-link"><span className="icon">{Icon.download}</span> Esporta in Excel</a>
      </div>
    </div>
  );
}

window.C2Saldi = C2Saldi;
window.C2Movimenti = C2Movimenti;
