// invoice-editor.jsx — Create / edit invoice with live preview

const InvoiceEditor = ({ t, lang, invoiceId, onBack }) => {
  const original = INVOICES.find(i => i.id === invoiceId) || INVOICES[0];
  const [clientId, setClientId] = React.useState(original.clientId);
  const [project, setProject] = React.useState(original.project);
  const [number, setNumber] = React.useState(invoiceId ? original.number : "BES-2026-0143");
  const [issued, setIssued] = React.useState(invoiceId ? original.issued : "2026-04-27");
  const [due, setDue] = React.useState(invoiceId ? original.due : "2026-05-27");
  const [period, setPeriod] = React.useState(original.period || "biweekly");
  const [items, setItems] = React.useState(original.items.map((it, i) => ({ ...it, id: `it-${i}` })));
  const [taxRate, setTaxRate] = React.useState(original.taxRate || 0);
  const [notes, setNotes] = React.useState(original.notes || "Net 30. Wire transfer preferred. Thank you for partnering with BIM Edge Solutions.");

  const client = CLIENTS.find(c => c.id === clientId);
  const sub = items.reduce((s, it) => s + (Number(it.qty) || 0) * (Number(it.rate) || 0), 0);
  const tax = sub * (taxRate / 100);
  const total = sub + tax;

  const updateItem = (id, key, val) => setItems(items.map(it => it.id === id ? { ...it, [key]: val } : it));
  const removeItem = id => setItems(items.filter(it => it.id !== id));
  const addItem = () => setItems([...items, { id: `it-${Date.now()}`, desc: "", qty: 1, rate: 0, type: "hr" }]);
  const addTime = () => setItems([...items, { id: `it-${Date.now()}`, desc: lang === "es" ? "Horas trabajadas — periodo" : "Hours worked — period", qty: 8, rate: 165, type: "hr" }]);

  const handleSend = async () => {
    if (!confirm(lang === "es" ? "¿Enviar esta factura por email?" : "Send this invoice via email?")) return;
    
    try {
      // Generar PDF
      const paperEl = document.querySelector('.paper');
      const pdfBlob = await html2pdf().from(paperEl).outputPdf('blob');
      
      // Enviar email
      const html = buildInvoiceEmail({ 
        invoice: { number, issued, due, items }, 
        client, 
        total, 
        lang 
      });
      
      await sendEmail({
        to: client.email,
        subject: `Invoice ${number}`,
        html,
        pdfBlob,
      });
      
      // Marcar como enviada en DB
      if (invoiceId) {
        await markInvoiceSent(invoiceId);
      }
      
      alert(lang === "es" ? "✅ Factura enviada" : "✅ Invoice sent");
      onBack();
    } catch (error) {
      console.error(error);
      alert(`Error: ${error.message}`);
    }
  };

  const handleDownloadPDF = async () => {
    const paperEl = document.querySelector('.paper');
    await html2pdf().from(paperEl).save(`${number}.pdf`);
  };

  return (
    <div className="editor-split">
      <div className="editor-pane">
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 18 }}>
          <button className="btn ghost icon" onClick={onBack}><Icon name="arrowLeft"/></button>
          <h2 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>{t("editor")}</h2>
          <span className="pill draft" style={{ marginLeft: 8 }}><span className="dot"/>{t("draft")}</span>
          <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
            <button className="btn" onClick={handleDownloadPDF}><Icon name="download" size={13}/> {t("download")}</button>
            <button className="btn"><Icon name="copy" size={13}/> {t("duplicate")}</button>
            <button className="btn">{t("saveDraft")}</button>
            <button className="btn primary" onClick={handleSend}><Icon name="send" size={13}/> {t("send")}</button>
          </div>
        </div>

        {/* Client + project */}
        <div className="card" style={{ marginBottom: 14 }}>
          <div className="card-hd"><h3>{t("billTo")}</h3></div>
          <div className="card-body">
            <div className="form-grid cols-2">
              <div className="form-row">
                <label>{t("client")}</label>
                <select className="select" value={clientId} onChange={e => setClientId(e.target.value)}>
                  {CLIENTS.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
              </div>
              <div className="form-row">
                <label>{t("project")}</label>
                <input className="input" value={project} onChange={e => setProject(e.target.value)}/>
              </div>
            </div>
          </div>
        </div>

        {/* Meta */}
        <div className="card" style={{ marginBottom: 14 }}>
          <div className="card-body">
            <div className="form-grid cols-3">
              <div className="form-row">
                <label>{t("invoiceNumber")}</label>
                <input className="input" value={number} onChange={e => setNumber(e.target.value)} style={{ fontFamily: "var(--font-mono)" }}/>
              </div>
              <div className="form-row">
                <label>{t("issueDate")}</label>
                <input className="input" type="date" value={issued} onChange={e => setIssued(e.target.value)}/>
              </div>
              <div className="form-row">
                <label>{t("dueDate")}</label>
                <input className="input" type="date" value={due} onChange={e => setDue(e.target.value)}/>
              </div>
            </div>
            <div style={{ marginTop: 14 }}>
              <label style={{ fontSize: 11, color: "var(--fg-2)", fontWeight: 500, display: "block", marginBottom: 6 }}>{t("billingPeriod")}</label>
              <div className="seg">
                {[
                  { k: "weekly", l: t("weekly") },
                  { k: "biweekly", l: t("biweekly") },
                  { k: "monthly", l: t("monthly") },
                  { k: "custom", l: t("custom") },
                ].map(o => (
                  <button key={o.k} className={period === o.k ? "on" : ""} onClick={() => setPeriod(o.k)}>{o.l}</button>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* Line items */}
        <div className="card" style={{ marginBottom: 14 }}>
          <div className="card-hd">
            <h3>{lang === "es" ? "Líneas de factura" : "Line items"}</h3>
            <span className="subtitle">{items.length} {lang === "es" ? "líneas" : "items"}</span>
          </div>
          <div className="card-body flush">
            <div style={{ display: "grid", gridTemplateColumns: "14px 1fr 70px 90px 90px 24px", gap: 8, padding: "8px 10px 6px", fontSize: 10.5, fontWeight: 600, letterSpacing: 0.06, textTransform: "uppercase", color: "var(--fg-3)", borderBottom: "1px solid var(--line-soft)" }}>
              <div></div>
              <div>{t("description")}</div>
              <div className="right" style={{ textAlign: "right" }}>{t("qty")}</div>
              <div className="right" style={{ textAlign: "right" }}>{t("rate")}</div>
              <div className="right" style={{ textAlign: "right" }}>{t("total")}</div>
              <div></div>
            </div>
            {items.map(it => (
              <div key={it.id} className="line-item">
                <div className="line-handle"><Icon name="drag" size={12}/></div>
                <input className="input sm" value={it.desc} onChange={e => updateItem(it.id, "desc", e.target.value)} placeholder={t("description")}/>
                <input className="input sm" type="number" value={it.qty} onChange={e => updateItem(it.id, "qty", e.target.value)} style={{ textAlign: "right", fontFamily: "var(--font-mono)" }}/>
                <input className="input sm" type="number" value={it.rate} onChange={e => updateItem(it.id, "rate", e.target.value)} style={{ textAlign: "right", fontFamily: "var(--font-mono)" }}/>
                <div className="num right" style={{ textAlign: "right", fontWeight: 600, paddingRight: 4 }}>{fmtMoney((Number(it.qty) || 0) * (Number(it.rate) || 0))}</div>
                <button className="btn ghost icon sm" onClick={() => removeItem(it.id)}><Icon name="x" size={12}/></button>
              </div>
            ))}
            <div style={{ padding: "10px", display: "flex", gap: 8 }}>
              <button className="btn sm" onClick={addItem}><Icon name="plus" size={12}/> {t("addLine")}</button>
              <button className="btn sm" onClick={addTime}><Icon name="clock" size={12}/> {t("addTimeEntry")}</button>
            </div>
          </div>
        </div>

        {/* Totals */}
        <div className="card" style={{ marginBottom: 14 }}>
          <div className="card-body">
            <div style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", fontSize: 12.5 }}>
              <span style={{ color: "var(--fg-2)" }}>{t("subtotal")}</span>
              <span className="num">{fmtMoney(sub)}</span>
            </div>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "6px 0", fontSize: 12.5 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ color: "var(--fg-2)" }}>{t("tax")}</span>
                <input className="input sm" type="number" value={taxRate} onChange={e => setTaxRate(Number(e.target.value))} style={{ width: 60, height: 24, textAlign: "right", fontFamily: "var(--font-mono)" }}/>
                <span style={{ color: "var(--fg-2)" }}>%</span>
              </div>
              <span className="num">{fmtMoney(tax)}</span>
            </div>
            <div style={{ borderTop: "1px solid var(--line)", marginTop: 6, paddingTop: 10, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <span style={{ fontWeight: 600 }}>{t("total")}</span>
              <span className="num" style={{ fontSize: 20, fontWeight: 600 }}>{fmtMoney(total)}</span>
            </div>
          </div>
        </div>

        {/* Notes */}
        <div className="card">
          <div className="card-hd"><h3>{t("notes")}</h3></div>
          <div className="card-body">
            <textarea className="textarea" value={notes} onChange={e => setNotes(e.target.value)}/>
          </div>
        </div>
      </div>

      {/* Preview pane */}
      <div className="preview-pane">
        <InvoicePaper invoice={{ number, issued, due, items, taxRate, notes }} client={client} project={project} totals={{ sub, tax, total }} t={t} lang={lang}/>
      </div>
    </div>
  );
};

const InvoicePaper = ({ invoice, client, project, totals, t, lang }) => (
  <div className="paper">
    <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 28 }}>
      <div>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
          <div style={{ width: 32, height: 32, borderRadius: 6, background: "linear-gradient(135deg, oklch(0.45 0.14 195), oklch(0.32 0.14 215))", color: "white", display: "grid", placeItems: "center", fontFamily: "var(--font-mono)", fontWeight: 700 }}>B</div>
          <div>
            <div style={{ fontWeight: 600, letterSpacing: -0.01 }}>{COMPANY.name}</div>
            <div className="paper-mono" style={{ color: "oklch(0.45 0 0)" }}>{COMPANY.tagline}</div>
          </div>
        </div>
        <div style={{ color: "oklch(0.35 0 0)", fontSize: 10.5, lineHeight: 1.6 }}>
          {COMPANY.address}<br/>{COMPANY.city}<br/>{COMPANY.email} · {COMPANY.phone}
        </div>
      </div>
      <div style={{ textAlign: "right" }}>
        <h1>{lang === "es" ? "FACTURA" : "INVOICE"}</h1>
        <div className="paper-mono" style={{ color: "oklch(0.35 0 0)", marginTop: 4 }}>{invoice.number}</div>
        <div style={{ marginTop: 18, fontSize: 10.5, lineHeight: 1.7 }}>
          <div><span style={{ color: "oklch(0.5 0 0)" }}>{t("issued")}:</span> <b className="paper-mono">{invoice.issued}</b></div>
          <div><span style={{ color: "oklch(0.5 0 0)" }}>{t("due")}:</span> <b className="paper-mono">{invoice.due}</b></div>
        </div>
      </div>
    </div>

    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 28, marginBottom: 24 }}>
      <div>
        <div className="paper-mono" style={{ color: "oklch(0.5 0 0)", marginBottom: 6 }}>{t("billTo")}</div>
        <div style={{ fontWeight: 600 }}>{client.name}</div>
        <div style={{ fontSize: 10.5, color: "oklch(0.35 0 0)", lineHeight: 1.6 }}>
          {client.contact}<br/>{client.email}<br/>{client.city}
        </div>
      </div>
      <div>
        <div className="paper-mono" style={{ color: "oklch(0.5 0 0)", marginBottom: 6 }}>{t("project")}</div>
        <div style={{ fontWeight: 600 }}>{project}</div>
      </div>
    </div>

    <table className="paper-tbl">
      <thead>
        <tr>
          <th>{t("description")}</th>
          <th className="right" style={{ width: 60 }}>{t("qty")}</th>
          <th className="right" style={{ width: 80 }}>{t("rate")}</th>
          <th className="right" style={{ width: 90 }}>{t("total")}</th>
        </tr>
      </thead>
      <tbody>
        {invoice.items.map(it => (
          <tr key={it.id}>
            <td>{it.desc || <span style={{ color: "oklch(0.7 0 0)" }}>—</span>}</td>
            <td className="right">{it.qty}{it.type === "hr" ? " hr" : ""}</td>
            <td className="right">${Number(it.rate).toFixed(2)}</td>
            <td className="right">{fmtMoney((Number(it.qty) || 0) * (Number(it.rate) || 0))}</td>
          </tr>
        ))}
      </tbody>
    </table>

    <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 18 }}>
      <div style={{ width: 240 }}>
        <div style={{ display: "flex", justifyContent: "space-between", padding: "4px 0" }}>
          <span style={{ color: "oklch(0.45 0 0)" }}>{t("subtotal")}</span>
          <span className="paper-mono">{fmtMoney(totals.sub)}</span>
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", padding: "4px 0" }}>
          <span style={{ color: "oklch(0.45 0 0)" }}>{t("tax")} ({invoice.taxRate}%)</span>
          <span className="paper-mono">{fmtMoney(totals.tax)}</span>
        </div>
        <div style={{ borderTop: "2px solid oklch(0.18 0 0)", marginTop: 6, paddingTop: 8, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
          <span style={{ fontWeight: 700 }}>{t("total")}</span>
          <span className="paper-mono" style={{ fontSize: 16, fontWeight: 700 }}>{fmtMoney(totals.total)}</span>
        </div>
      </div>
    </div>

    <hr className="paper-rule"/>
    <div style={{ fontSize: 10.5, color: "oklch(0.35 0 0)", lineHeight: 1.6 }}>
      <div className="paper-mono" style={{ color: "oklch(0.5 0 0)", marginBottom: 4 }}>{t("notes")}</div>
      {invoice.notes}
    </div>
    <div style={{ marginTop: 18, paddingTop: 14, borderTop: "1px solid oklch(0.85 0 0)", display: "flex", justifyContent: "space-between", fontSize: 9.5, color: "oklch(0.5 0 0)" }} className="paper-mono">
      <span>{COMPANY.ein}</span>
      <span>{lang === "es" ? "Página 1 de 1" : "Page 1 of 1"}</span>
    </div>
  </div>
);

window.InvoiceEditor = InvoiceEditor;
window.InvoicePaper = InvoicePaper;
