/* global React, lecygne, printDocument */
// Factures & BL — génération depuis commande, paiements, impression.

function PaiementModal({ facture, onClose, onSaved }) {
  const reste = Number(facture.reste_a_payer != null ? facture.reste_a_payer : facture.montant_ttc);
  const [montant, setMontant] = React.useState(reste > 0 ? reste : 0);
  const [mode, setMode] = React.useState("especes");
  const [err, setErr] = React.useState("");
  const [busy, setBusy] = React.useState(false);

  async function save() {
    if (!(Number(montant) > 0)) { setErr("Montant invalide."); return; }
    setBusy(true); setErr("");
    const res = await lecygne.factures.addPayment(facture.id, montant, mode);
    setBusy(false);
    if (res.error) setErr(res.error.message);
    else { window.lcToast("Paiement enregistré", "success"); onSaved(); onClose(); }
  }

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <h2>Encaisser — {facture.no_facture}</h2>
        <p className="hint" style={{ marginBottom: 12 }}>Reste à payer : <b>{lecygne.fmtAmount(reste)}</b></p>
        <div className="grid2">
          <div><label>Montant</label><input className="field num" type="number" value={montant} onChange={(e) => setMontant(e.target.value)} /></div>
          <div><label>Mode</label>
            <select className="field" value={mode} onChange={(e) => setMode(e.target.value)}>
              {lecygne.MODES_PAIEMENT.map((m) => <option key={m} value={m}>{m}</option>)}
            </select></div>
        </div>
        {err && <div className="auth-err">{err}</div>}
        <div className="actions">
          <button className="btn" onClick={onClose}>Annuler</button>
          <button className="btn primary" onClick={save} disabled={busy}>{busy ? "…" : "Enregistrer le paiement"}</button>
        </div>
      </div>
    </div>
  );
}

function NewFactureModal({ ctx, onClose, onSaved }) {
  // Commandes facturables : non encore facturées
  const cmds = lecygne.useCommandes({});
  const [codeClient, setCodeClient] = React.useState("");
  const [sel, setSel] = React.useState({}); // { no_commande: true }
  const [err, setErr] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const name = (c) => (c.client && (c.client.societe || c.client.nom_client)) || `#${c.code_client}`;

  const facturables = (cmds.data || []).filter((c) => !c.no_facture);
  // Clients distincts ayant des commandes facturables
  const clients = [];
  const seen = {};
  facturables.forEach((c) => { if (!seen[c.code_client]) { seen[c.code_client] = true; clients.push({ code: c.code_client, name: name(c) }); } });
  const mine = facturables.filter((c) => String(c.code_client) === String(codeClient));
  const selectedNos = Object.keys(sel).filter((k) => sel[k]).map(Number);

  function toggle(no) { setSel((s) => ({ ...s, [no]: !s[no] })); }

  async function gen() {
    if (!selectedNos.length) { setErr("Sélectionnez au moins une commande."); return; }
    setBusy(true); setErr("");
    const res = await lecygne.factures.generateFromCommandes(selectedNos, ctx.company);
    setBusy(false);
    if (res.error) setErr(res.error.message);
    else { window.lcToast("Facture " + res.data.no_facture + " générée", "success"); onSaved(); onClose(); }
  }

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <h2>Générer une facture</h2>
        <label>Client</label>
        <select className="field" value={codeClient} onChange={(e) => { setCodeClient(e.target.value); setSel({}); }}>
          <option value="">— Sélectionner —</option>
          {clients.map((c) => <option key={c.code} value={c.code}>{c.name}</option>)}
        </select>

        {codeClient && (
          <div style={{ marginTop: 14 }}>
            <label>Commandes à regrouper sur la facture ({mine.length})</label>
            <div className="tbl-wrap" style={{ maxHeight: 240, overflowY: "auto", border: "1px solid var(--line)", borderRadius: "var(--radius-sm)" }}>
              <table>
                <tbody>
                  {mine.map((c) => (
                    <tr key={c.no_commande} className="row-click" onClick={() => toggle(c.no_commande)}>
                      <td style={{ width: 36 }}><input type="checkbox" checked={!!sel[c.no_commande]} onChange={() => toggle(c.no_commande)} onClick={(e) => e.stopPropagation()} /></td>
                      <td>#{c.no_commande}</td>
                      <td>{lecygne.fmtDate(c.date_commande)}</td>
                      <td><span className={"pill " + ((lecygne.STATUTS[c.statut] || {}).cls || "gray")}>{(lecygne.STATUTS[c.statut] || {}).fr || c.statut}</span></td>
                    </tr>
                  ))}
                  {!mine.length && <tr><td className="empty">Aucune commande facturable pour ce client.</td></tr>}
                </tbody>
              </table>
            </div>
            <p className="hint" style={{ marginTop: 8 }}>
              {selectedNos.length} commande(s) sélectionnée(s). HT, TVA et TTC sont calculés depuis les lignes et le taux de TVA de la société.
            </p>
          </div>
        )}
        {err && <div className="auth-err">{err}</div>}
        <div className="actions">
          <button className="btn" onClick={onClose}>Annuler</button>
          <button className="btn primary" onClick={gen} disabled={busy || !selectedNos.length}>{busy ? "…" : `Générer (${selectedNos.length})`}</button>
        </div>
      </div>
    </div>
  );
}

function RelanceModal({ ctx, onClose }) {
  const data = lecygne.useAsync(() => lecygne.factures.relances(), []);
  const groups = data.data || [];
  const cur = (ctx.company && ctx.company.currency) || "XOF";

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" style={{ width: 620 }} onClick={(e) => e.stopPropagation()}>
        <h2>Relances impayés
          {!!groups.length && <button className="btn sm primary" onClick={() => window.printRelances({ company: ctx.company, groups })}>Imprimer toutes</button>}
        </h2>
        {data.loading ? <div className="spinner">Chargement…</div> :
          !groups.length ? <div className="empty">Aucun impayé. 🎉</div> : (
            <div className="tbl-wrap"><table>
              <thead><tr><th>Client</th><th className="right">Factures</th><th className="right">Total dû</th><th></th></tr></thead>
              <tbody>
                {groups.map((g) => (
                  <tr key={g.client ? g.client.code_client : Math.random()}>
                    <td>{g.client ? (g.client.societe || g.client.nom_client) : "—"}</td>
                    <td className="num">{g.factures.length}</td>
                    <td className="num"><b>{lecygne.fmtAmount(g.total, cur)}</b></td>
                    <td><button className="btn sm" onClick={() => window.printRelances({ company: ctx.company, groups: [g] })}>Imprimer</button></td>
                  </tr>
                ))}
              </tbody>
            </table></div>
          )}
        <div className="actions"><button className="btn" onClick={onClose}>Fermer</button></div>
      </div>
    </div>
  );
}

function ScreenFactures({ ctx }) {
  const [statut, setStatut] = React.useState("");
  const [search, setSearch] = React.useState("");
  const [paying, setPaying] = React.useState(null);
  const [creating, setCreating] = React.useState(false);
  const [relancing, setRelancing] = React.useState(false);
  React.useEffect(() => { if (ctx.seed && ctx.seed.route === "factures") setSearch(ctx.seed.term); }, [ctx.seed]);
  const list = lecygne.useFactures({ statut: statut || undefined, search });
  const name = (f) => (f.client && (f.client.societe || f.client.nom_client)) || `#${f.code_client}`;

  async function print(f) {
    const cmds = await lecygne.commandes.byFacture(f.no_facture);
    const lignes = cmds.flatMap((c) => c.lignes || []);
    const port = cmds.reduce((s, c) => s + Number(c.port || 0), 0);
    const client = await lecygne.clients.get(f.code_client);
    printDocument({ kind: "facture", company: ctx.company, client, lignes, port, facture: f });
  }

  return (
    <div>
      <div className="topbar"><h1>Factures &amp; BL</h1>
        <input className="search" placeholder="Rechercher n° facture, client…"
          value={search} onChange={(e) => setSearch(e.target.value)} /></div>

      <div className="card">
        <div className="toolbar">
          <select className="field" style={{ width: 220 }} value={statut} onChange={(e) => setStatut(e.target.value)}>
            <option value="">Tous les statuts</option>
            {Object.entries(lecygne.STATUTS_FACTURE).map(([k, v]) => <option key={k} value={k}>{v.fr}</option>)}
          </select>
          <div className="grow" />
          <button className="btn" onClick={() => setRelancing(true)}>Relances impayés</button>
          <button className="btn" onClick={() => window.exportCsv("factures.csv", list.data || [], [
            { key: "no_facture", label: "N° facture" },
            { label: "Client", map: name },
            { label: "Date", map: (f) => lecygne.fmtDate(f.date_facture) },
            { key: "montant_ttc", label: "TTC" },
            { key: "reste_a_payer", label: "Reste" },
            { label: "Statut", map: (f) => (lecygne.STATUTS_FACTURE[f.statut] || {}).fr || f.statut },
          ])}>⤓ Exporter</button>
          <button className="btn primary" onClick={() => setCreating(true)}>＋ Générer une facture</button>
        </div>

        {list.loading ? <div className="spinner">Chargement…</div> : (
          <div className="tbl-wrap"><table>
            <thead><tr>
              <th>N° facture</th><th>Client</th><th>Date</th>
              <th className="right">TTC</th><th className="right">Reste</th><th>Statut</th><th>Actions</th>
            </tr></thead>
            <tbody>
              {(list.data || []).map((f) => {
                const st = lecygne.STATUTS_FACTURE[f.statut] || {};
                return (
                  <tr key={f.id}>
                    <td>{f.no_facture}</td>
                    <td>{name(f)}</td>
                    <td>{lecygne.fmtDate(f.date_facture)}</td>
                    <td className="num">{lecygne.fmtAmount(f.montant_ttc)}</td>
                    <td className="num">{lecygne.fmtAmount(f.reste_a_payer)}</td>
                    <td><span className={"pill " + (st.cls || "gray")}>{st.fr || f.statut}</span></td>
                    <td>
                      <div className="row-flex" style={{ gap: 6 }}>
                        {f.reste_a_payer > 0 && <button className="btn sm" onClick={() => setPaying(f)}>Encaisser</button>}
                        <button className="btn sm" onClick={() => print(f)}>Imprimer</button>
                      </div>
                    </td>
                  </tr>
                );
              })}
              {!(list.data || []).length &&
                <tr><td colSpan="7" className="empty">Aucune facture. Générez-en une depuis une commande.</td></tr>}
            </tbody>
          </table></div>
        )}
      </div>

      {paying && <PaiementModal facture={paying} onClose={() => setPaying(null)} onSaved={() => list.reload()} />}
      {creating && <NewFactureModal ctx={ctx} onClose={() => setCreating(false)} onSaved={() => list.reload()} />}
      {relancing && <RelanceModal ctx={ctx} onClose={() => setRelancing(false)} />}
    </div>
  );
}
