/* Comptes ouverts — Soldes & échéances par fournisseur (vue CFO) */

// Standalone accounts the user creates manually (separate from SUPPLIERS)
const EXTRA_ACCOUNTS = [];
const ACCOUNT_DELETIONS = new Set();

const OpenAccounts = ({ onNavigate }) => {
  const [sortBy, setSortBy] = useState("openBalance");
  const [filter, setFilter] = useState("all"); // all | due | clean
  const [payOpen, setPayOpen] = useState(null); // supplier being paid
  const [payAmount, setPayAmount] = useState("");
  const [payMethod, setPayMethod] = useState("Virement");
  const [payNote, setPayNote] = useState("");
  const [, force] = useState(0);
  const toast = (window.useToast || (() => () => {}))();
  const trashHook = (window.useKCCTrash || (() => ({ items: [], send: async () => {} })))();

  const [newOpen, setNewOpen] = useState(false);
  const [draft, setDraft] = useState({ supplier: "", balance: 0, term: "Net 30", dueDate: "" });

  const create = async () => {
    if (!draft.supplier?.trim()) return;
    const id = "acc-" + Date.now().toString(36);
    const fresh = {
      id,
      supplier: draft.supplier.trim(),
      name: draft.supplier.trim(),
      balance: Number(draft.balance) || 0,
      openBalance: Number(draft.balance) || 0,
      term: draft.term || "Net 30",
      terms: draft.term || "Net 30",
      dueDate: draft.dueDate.trim() || "—",
      region: "—",
      cat: "—",
      contact: "",
      email: "",
    };
    EXTRA_ACCOUNTS.push(fresh);
    SUPPLIERS.push(fresh);
    setNewOpen(false);
    setDraft({ supplier: "", balance: 0, term: "Net 30", dueDate: "" });
    force(x => x + 1);
    try {
      await fetch("/api/sync", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ col: "accounts", items: [fresh] }),
      });
    } catch (_) {}
    toast?.({ message: `Compte "${fresh.supplier}" créé`, tone: "green" });
  };

  const deleteAccount = async (target) => {
    if (!target) return;
    if (!window.confirm(`Mettre le compte "${target.name || target.supplier}" à la corbeille ?`)) return;
    ACCOUNT_DELETIONS.add(target.id);
    const sidx = SUPPLIERS.findIndex(s => s.id === target.id);
    if (sidx >= 0) SUPPLIERS.splice(sidx, 1);
    const eidx = EXTRA_ACCOUNTS.findIndex(a => a.id === target.id);
    if (eidx >= 0) EXTRA_ACCOUNTS.splice(eidx, 1);
    await trashHook.send("accounts", target);
    force(x => x + 1);
    toast?.({ message: `Compte → corbeille`, tone: "muted" });
  };

  const persistSupplier = async (sup, patch) => {
    Object.assign(sup, patch);
    force(x => x + 1);
    try {
      await fetch("/api/sync", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ col: "suppliers", items: [{ ...sup }] }),
      });
    } catch (_) {}
  };

  const openPay = (s) => {
    setPayOpen(s);
    setPayAmount(String(s.openBalance));
    setPayMethod("Virement");
    setPayNote("");
  };

  const confirmPay = () => {
    if (!payOpen) return;
    const amt = Math.max(0, Number(payAmount) || 0);
    const newBalance = Math.max(0, payOpen.openBalance - amt);
    persistSupplier(payOpen, {
      openBalance: newBalance,
      lastPayment: { amount: amt, method: payMethod, note: payNote, date: new Date().toISOString() },
    });
    toast?.({ message: `Paiement de $${amt.toLocaleString()} enregistré pour ${payOpen.name}`, tone: "green" });
    setPayOpen(null);
  };

  const enriched = SUPPLIERS.map(s => {
    // Synthetic due date based on terms & lead days
    const daysUntilDue = s.terms.includes("Net 30") ? 12 :
                         s.terms.includes("Net 45") ? -3 :
                         s.terms.includes("50% / 50%") ? 5 :
                         s.terms.includes("30% / 70%") ? 18 :
                         0;
    const overdue = daysUntilDue < 0;
    return { ...s, daysUntilDue, overdue };
  });

  const filtered = enriched
    .filter(s => {
      if (filter === "all") return true;
      if (filter === "due") return s.openBalance > 0;
      if (filter === "clean") return s.openBalance === 0;
      if (filter === "overdue") return s.overdue && s.openBalance > 0;
      return true;
    })
    .sort((a, b) => b[sortBy] - a[sortBy]);

  const totalOpen = SUPPLIERS.reduce((a, b) => a + b.openBalance, 0);
  const overdueCount = enriched.filter(s => s.overdue && s.openBalance > 0).length;
  const overdueAmt = enriched.filter(s => s.overdue && s.openBalance > 0).reduce((a, b) => a + b.openBalance, 0);

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Comptes ouverts</div>
          <div className="page-sub">
            ${totalOpen.toLocaleString()} dus à {SUPPLIERS.filter(s => s.openBalance > 0).length} fournisseurs ·
            {" "}{overdueCount} échéance{overdueCount > 1 ? "s" : ""} dépassée{overdueCount > 1 ? "s" : ""}
          </div>
        </div>
        <div className="row" style={{ gap: 6 }}>
          <button className="btn" data-variant="primary" onClick={() => setNewOpen(true)}><Icon name="plus" size={12}/> Nouveau compte</button>
          <button className="btn"><Icon name="dollar" size={12} /> Enregistrer paiement</button>
        </div>
      </div>

      {/* KPI */}
      <div className="grid" style={{ gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 14 }}>
        <div className="card" style={{ padding: 14 }}>
          <div style={{ fontSize: 10.5, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Total dû</div>
          <div className="mono" style={{ fontSize: 22, fontWeight: 600, marginTop: 4 }}>${totalOpen.toLocaleString()}</div>
        </div>
        <div className="card" style={{ padding: 14 }}>
          <div style={{ fontSize: 10.5, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Retards</div>
          <div className="mono" style={{ fontSize: 22, fontWeight: 600, marginTop: 4, color: overdueAmt > 0 ? "var(--red)" : "var(--text)" }}>
            ${overdueAmt.toLocaleString()}
          </div>
          <div className="mono" style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 2 }}>{overdueCount} fournisseur{overdueCount > 1 ? "s" : ""}</div>
        </div>
        <div className="card" style={{ padding: 14 }}>
          <div style={{ fontSize: 10.5, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Avg solde</div>
          <div className="mono" style={{ fontSize: 22, fontWeight: 600, marginTop: 4 }}>
            ${Math.round(totalOpen / SUPPLIERS.filter(s => s.openBalance > 0).length).toLocaleString()}
          </div>
        </div>
        <div className="card" style={{ padding: 14 }}>
          <div style={{ fontSize: 10.5, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Soldes clean</div>
          <div className="mono" style={{ fontSize: 22, fontWeight: 600, marginTop: 4, color: "var(--green)" }}>
            {SUPPLIERS.filter(s => s.openBalance === 0).length}
          </div>
          <div className="mono" style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 2 }}>fournisseurs</div>
        </div>
      </div>

      <div className="row" style={{ gap: 6, marginBottom: 12 }}>
        <button className="btn" data-variant={filter === "all" ? "primary" : "ghost"} onClick={() => setFilter("all")}>Tous · {SUPPLIERS.length}</button>
        <button className="btn" data-variant={filter === "due" ? "primary" : "ghost"} onClick={() => setFilter("due")}>Avec solde · {SUPPLIERS.filter(s => s.openBalance > 0).length}</button>
        <button className="btn" data-variant={filter === "overdue" ? "primary" : "ghost"} onClick={() => setFilter("overdue")}>En retard · {overdueCount}</button>
        <button className="btn" data-variant={filter === "clean" ? "primary" : "ghost"} onClick={() => setFilter("clean")}>À jour · {SUPPLIERS.filter(s => s.openBalance === 0).length}</button>
      </div>

      <div className="card" style={{ padding: 0, overflow: "auto" }}>
        <table className="table">
          <thead>
            <tr>
              <th>Fournisseur</th>
              <th>Termes</th>
              <th style={{ textAlign: "right", cursor: "pointer" }} onClick={() => setSortBy("openBalance")}>
                Solde ouvert {sortBy === "openBalance" && "↓"}
              </th>
              <th style={{ textAlign: "right", cursor: "pointer" }} onClick={() => setSortBy("daysUntilDue")}>
                Échéance {sortBy === "daysUntilDue" && "↓"}
              </th>
              <th>Catégorie</th>
              <th>Contact</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(s => (
              <tr key={s.id}>
                <td>
                  <div style={{ fontWeight: 550 }}>
                    <EditableField value={s.name} onSave={(v) => persistSupplier(s, { name: v })} width={180}/>
                  </div>
                  <div className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)" }}>
                    <EditableField value={s.region} onSave={(v) => persistSupplier(s, { region: v })} width={120}/>
                  </div>
                </td>
                <td>
                  <EditableField value={s.terms} onSave={(v) => persistSupplier(s, { terms: v })} width={140}/>
                </td>
                <td className="mono" style={{ textAlign: "right", fontWeight: 600, color: s.openBalance === 0 ? "var(--text-faint)" : "var(--text)" }}>
                  <EditableField value={s.openBalance} onSave={(v) => persistSupplier(s, { openBalance: Number(v) || 0 })} type="number" format={(v) => "$" + Number(v).toLocaleString()} width={100}/>
                </td>
                <td className="mono" style={{ textAlign: "right", color: s.overdue ? "var(--red)" : s.daysUntilDue < 7 ? "var(--amber)" : "var(--text-dim)" }}>
                  {s.openBalance === 0 ? "—" : s.overdue ? `+${Math.abs(s.daysUntilDue)}j retard` : `dans ${s.daysUntilDue}j`}
                </td>
                <td className="muted" style={{ fontSize: 11.5 }}>
                  <EditableField value={s.cat} onSave={(v) => persistSupplier(s, { cat: v })} width={120}/>
                </td>
                <td>
                  <div style={{ fontSize: 12 }}>
                    <EditableField value={s.contact} onSave={(v) => persistSupplier(s, { contact: v })} width={140}/>
                  </div>
                  <div className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)" }}>
                    <EditableField value={s.email} onSave={(v) => persistSupplier(s, { email: v })} type="email" width={180}/>
                  </div>
                </td>
                <td>
                  <div className="row" style={{ gap: 4 }}>
                    {s.openBalance > 0 && (
                      <button className="btn" data-variant="ghost" data-size="sm" onClick={() => openPay(s)}>
                        <Icon name="dollar" size={11} /> Payer
                      </button>
                    )}
                    <button
                      className="btn" data-variant="ghost" data-size="sm"
                      title="Mettre à la corbeille"
                      onClick={() => deleteAccount(s)}
                      style={{ color: "var(--red)" }}
                    >
                      <Icon name="x" size={11}/>
                    </button>
                  </div>
                </td>
              </tr>
            ))}
            {filtered.length === 0 && (
              <tr><td colSpan={7} style={{ textAlign: "center", padding: 30, color: "var(--text-faint)" }}>
                Aucun compte — clique « + Nouveau compte » pour en créer un.
              </td></tr>
            )}
          </tbody>
        </table>
      </div>

      {newOpen && (
        <div onClick={() => setNewOpen(false)} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.55)", zIndex: 9999, display: "grid", placeItems: "center" }}>
          <div className="card" onClick={(e) => e.stopPropagation()} style={{ width: 480, padding: 20 }}>
            <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 14 }}>Nouveau compte ouvert</div>
            <div className="stack" style={{ gap: 10 }}>
              <div>
                <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Fournisseur *</div>
                <div className="input" style={{ height: 32, padding: "0 10px" }}>
                  <input autoFocus value={draft.supplier} onChange={(e) => setDraft(d => ({ ...d, supplier: e.target.value }))} placeholder="Nom du fournisseur" style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
                </div>
              </div>
              <div>
                <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Solde $</div>
                <div className="input" style={{ height: 32, padding: "0 10px" }}>
                  <input type="number" value={draft.balance} onChange={(e) => setDraft(d => ({ ...d, balance: e.target.value }))} style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
                </div>
              </div>
              <div>
                <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Termes</div>
                <select value={draft.term} onChange={(e) => setDraft(d => ({ ...d, term: e.target.value }))} className="input" style={{ height: 32, width: "100%" }}>
                  <option>Net 30</option>
                  <option>Net 45</option>
                  <option>Net 60</option>
                  <option>50% / 50%</option>
                  <option>30% / 70%</option>
                  <option>Comptant</option>
                </select>
              </div>
              <div>
                <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Échéance</div>
                <div className="input" style={{ height: 32, padding: "0 10px" }}>
                  <input value={draft.dueDate} onChange={(e) => setDraft(d => ({ ...d, dueDate: e.target.value }))} placeholder="ex: 15 juin" style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
                </div>
              </div>
            </div>
            <div className="row" style={{ marginTop: 16, justifyContent: "flex-end", gap: 8 }}>
              <button className="btn" onClick={() => setNewOpen(false)}>Annuler</button>
              <button className="btn" data-variant="primary" onClick={create} disabled={!draft.supplier.trim()}>Créer</button>
            </div>
          </div>
        </div>
      )}

      {/* Payment modal */}
      <Modal open={!!payOpen} onClose={() => setPayOpen(null)} width={420}>
        {payOpen && (
          <div style={{ padding: 18 }}>
            <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 4 }}>Enregistrer un paiement</div>
            <div style={{ fontSize: 12, color: "var(--text-dim)", marginBottom: 14 }}>
              {payOpen.name} · solde actuel : <b>${payOpen.openBalance.toLocaleString()}</b>
            </div>
            <div className="stack" style={{ gap: 10 }}>
              <label style={{ fontSize: 11, color: "var(--text-dim)" }}>Montant ($)</label>
              <input className="input" type="number" value={payAmount} onChange={(e) => setPayAmount(e.target.value)} autoFocus/>

              <label style={{ fontSize: 11, color: "var(--text-dim)" }}>Méthode</label>
              <select className="input" value={payMethod} onChange={(e) => setPayMethod(e.target.value)}>
                <option>Virement</option>
                <option>Chèque</option>
                <option>Carte</option>
                <option>PayPal</option>
                <option>Wise</option>
                <option>Autre</option>
              </select>

              <label style={{ fontSize: 11, color: "var(--text-dim)" }}>Note (optionnel)</label>
              <input className="input" value={payNote} onChange={(e) => setPayNote(e.target.value)} placeholder="Référence facture, etc."/>

              <div className="row" style={{ gap: 6, justifyContent: "flex-end", marginTop: 8 }}>
                <button className="btn" data-variant="ghost" onClick={() => setPayOpen(null)}>Annuler</button>
                <button className="btn" data-variant="primary" onClick={confirmPay}>
                  <Icon name="check" size={12}/> Confirmer paiement
                </button>
              </div>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

window.OpenAccounts = OpenAccounts;
