/* forms-opex.jsx — Payment Voucher (cash OPEX, no bill).
   Rules: WHT prompt when a line >= 1,000; per-doc OPEX upper bound from company setup. */

const WHT_THRESHOLD = 1000;
const WHT_RATES = [1, 2, 3, 5];

function OPEXLineSheet({ company, lang, inputMode, whtEnabled = true, initial, onSave, onClose, onDelete }) {
  const [ln, setLn] = useState(initial || { expenseId: "", gross: "", wht: null });
  const [step, setStep] = useState(0);
  const exp = company.expenses.find((x) => x.id === ln.expenseId);
  const gross = parseFloat(ln.gross) || 0;
  const overThreshold = whtEnabled && gross >= WHT_THRESHOLD;
  const set = (k, v) => setLn((p) => ({ ...p, [k]: v }));

  function setWht(deduct, rate) {
    if (!deduct) set("wht", { deduct: false });
    else {
      const r = rate || (ln.wht && ln.wht.rate) || 3;
      set("wht", { deduct: true, rate: r, amount: gross * r / 100 });
    }
  }
  // if line not over threshold, no WHT needed
  const needsWhtAnswer = overThreshold && (ln.wht == null);
  const complete = ln.expenseId && gross > 0 && !needsWhtAnswer;

  function finish() {
    onSave({ ...ln, desc: exp ? exp.th : "", en: exp ? exp.en : "", gross });
  }

  const fExp = (
    <Field label={window.t(lang, "expenseDesc")} required>
      <Select value={ln.expenseId || ""} onChange={(v) => set("expenseId", v)}>
        <option value="" disabled>{window.t(lang, "selectExpense")}</option>
        {company.expenses.map((e) => <option key={e.id} value={e.id}>{e.th} · {e.en}</option>)}
      </Select>
    </Field>
  );
  const fGross = (
    <Field label={window.t(lang, "grossPrice")} required>
      <div className="input-suffix">
        <input className="control big-num" type="number" inputMode="decimal" value={ln.gross}
          placeholder="0.00" onChange={(e) => { set("gross", e.target.value); if (parseFloat(e.target.value) < WHT_THRESHOLD) set("wht", null); }} />
        <span className="suffix" style={{ fontSize: 16 }}>฿</span>
      </div>
    </Field>
  );
  const fWht = overThreshold && (
    <div className="card" style={{ borderColor: "rgba(251,191,36,0.35)", background: "rgba(251,191,36,0.06)" }}>
      <div className="row" style={{ background: "transparent", border: "none", padding: 0, alignItems: "flex-start", gap: 10 }}>
        <Icon name="warn" size={20} style={{ color: "var(--warn)", flex: "0 0 auto", marginTop: 1 }} />
        <div className="grow">
          <div style={{ fontWeight: 600, fontSize: 14 }}>{window.t(lang, "whtTitle")}</div>
          <div className="hint" style={{ marginTop: 3, textWrap: "pretty" }}>{window.t(lang, "whtPrompt")}</div>
        </div>
      </div>
      <div className="seg-ctrl" style={{ marginTop: 12 }}>
        <button className={ln.wht && ln.wht.deduct ? "on" : ""} onClick={() => setWht(true)}>{window.t(lang, "whtYes")}</button>
        <button className={ln.wht && !ln.wht.deduct ? "on" : ""} onClick={() => setWht(false)}>{window.t(lang, "whtNo")}</button>
      </div>
      {ln.wht && ln.wht.deduct && (
        <div className="stack" style={{ marginTop: 12 }}>
          <Field label={window.t(lang, "whtRate")}>
            <div className="seg-ctrl">
              {WHT_RATES.map((r) => <button key={r} className={ln.wht.rate === r ? "on" : ""} onClick={() => setWht(true, r)}>{r}%</button>)}
            </div>
          </Field>
          <dl className="dl" style={{ margin: 0 }}>
            <dt>{window.t(lang, "whtAmount")} ({ln.wht.rate}%)</dt>
            <dd className="num" style={{ color: "var(--warn)" }}>− ฿{window.fmtMoney(ln.wht.amount)}</dd>
          </dl>
          <dl className="dl" style={{ margin: 0, fontWeight: 700 }}>
            <dt style={{ color: "var(--text)" }}>{window.t(lang, "netPay")}</dt>
            <dd className="num" style={{ color: "var(--accent)" }}>฿{window.fmtMoney(gross - ln.wht.amount)}</dd>
          </dl>
        </div>
      )}
    </div>
  );

  return (
    <Sheet onClose={onClose}>
      {inputMode === "guided" ? (
        <div className="stack-lg">
          <Steps total={overThreshold ? 3 : 2} current={step} />
          <div className="slide-in" key={step} style={{ minHeight: 110 }}>
            {step === 0 && fExp}
            {step === 1 && fGross}
            {step === 2 && fWht}
          </div>
          <div className="btn-row">
            {step > 0 && <Button variant="ghost" onClick={() => setStep(step - 1)} icon="back">{window.t(lang, "back")}</Button>}
            {(step === 0 || (step === 1 && overThreshold))
              ? <Button onClick={() => setStep(step + 1)} disabled={step === 0 ? !ln.expenseId : gross <= 0} icon="fwd">{window.t(lang, "next")}</Button>
              : <Button onClick={finish} disabled={!complete} icon="check">{window.t(lang, "done")}</Button>}
          </div>
        </div>
      ) : (
        <div className="stack-lg">
          <div className="h2">{window.t(lang, "expense")}</div>
          {fExp}{fGross}{fWht}
          <div className="btn-row">
            {onDelete && <Button variant="danger" onClick={onDelete} icon="trash">{window.t(lang, "remove")}</Button>}
            <Button onClick={finish} disabled={!complete} icon="check">{window.t(lang, "done")}</Button>
          </div>
        </div>
      )}
    </Sheet>
  );
}

function OPEXForm({ data, session, lang, inputMode, onLang, nav, onReview }) {
  const company = data.companies.find((c) => c.id === session.companyId);
  const [lines, setLines] = useState([]);
  const [editing, setEditing] = useState(null);
  const [evidenceMode, setEvidenceMode] = useState("supplier"); // supplier | selfservice
  const [sellerId, setSellerId] = useState(null);
  const [workPhoto, setWorkPhoto] = useState(null);
  const [sellerSign, setSellerSign] = useState(null);
  const docNo = window.nextDocNo(company, "OPX").no;
  const isSupplier = evidenceMode === "supplier";

  const total = lines.reduce((s, x) => s + (parseFloat(x.gross) || 0), 0);
  const whtTotal = lines.reduce((s, x) => s + (x.wht && x.wht.deduct ? x.wht.amount : 0), 0);
  const netTotal = total - whtTotal;
  const overBound = total > company.opexUpperBound;
  const evidenceOk = isSupplier ? (sellerId && workPhoto && sellerSign) : !!workPhoto;
  const canSend = lines.length > 0 && !overBound && evidenceOk;

  // switching to self-service clears any WHT (can't withhold from an unidentified payee) + seller data
  function chooseMode(mode) {
    setEvidenceMode(mode);
    if (mode === "selfservice") {
      setLines((p) => p.map((l) => ({ ...l, wht: null })));
      setSellerId(null); setSellerSign(null);
    }
  }

  function saveLine(line) {
    setLines((p) => {
      if (editing === "new") return [...p, line];
      const n = p.slice(); n[editing.idx] = line; return n;
    });
    setEditing(null);
  }

  return (
    <div className="app">
      <TopBar title={window.t(lang, "opexTitle")} sub={window.t(lang, isSupplier ? "opexHeader" : "opClaimHeader")}
        onBack={() => nav("home")} lang={lang} onLang={onLang} />
      <div className="scroll stack-lg">
        <div className="card">
          <div className="between">
            <div className="eyebrow">{window.t(lang, "docNo")}</div>
            <span className="mono" style={{ fontSize: 13, fontWeight: 600, color: "var(--accent)" }}>{docNo}</span>
          </div>
          <hr className="hr" />
          <div style={{ fontWeight: 600, fontSize: 14 }}>{company.name.split("·")[0].trim()}</div>
          <div className="hint mono" style={{ marginTop: 4 }}>TAX {company.taxId} · {company.branch}</div>
          <div className="pill" style={{ marginTop: 12 }}>
            <Icon name="shield" size={15} style={{ color: "var(--muted)" }} />
            {window.t(lang, "upperBound")}: <span className="num" style={{ color: "var(--text)" }}>฿{window.fmtMoney(company.opexUpperBound)}</span>
          </div>
        </div>

        {/* lines */}
        <div className="stack">
          <div className="eyebrow">{window.t(lang, "expense")} ({lines.length}/3)</div>
          {lines.length === 0 && <div className="card center muted" style={{ padding: 26, textWrap: "pretty" }}>{window.t(lang, "emptyItems")}</div>}
          {lines.map((ln, i) => (
            <button key={i} className="row" style={{ textAlign: "left" }} onClick={() => setEditing({ idx: i })}>
              <span className="ix">{i + 1}</span>
              <div className="grow">
                <div style={{ fontWeight: 600 }}>{ln.desc}</div>
                <div className="hint mono" style={{ marginTop: 2 }}>
                  ฿{window.fmtMoney(ln.gross)}
                  {ln.wht && ln.wht.deduct && <span style={{ color: "var(--warn)" }}> · WHT {ln.wht.rate}% −฿{window.fmtMoney(ln.wht.amount)}</span>}
                </div>
              </div>
              <Icon name="edit" size={16} style={{ color: "var(--muted)" }} />
            </button>
          ))}
          {lines.length < 3 && (
            <button className="btn btn-ghost" onClick={() => setEditing("new")} style={{ borderStyle: "dashed" }}>
              <Icon name="plus" size={18} />{window.t(lang, "addExpense")}
            </button>
          )}
        </div>

        {overBound && (
          <div className="card" style={{ borderColor: "rgba(248,113,113,0.4)", background: "rgba(248,113,113,0.08)", display: "flex", gap: 10, alignItems: "flex-start" }}>
            <Icon name="warn" size={20} style={{ color: "var(--danger)", flex: "0 0 auto", marginTop: 1 }} />
            <div>
              <div style={{ fontWeight: 600, fontSize: 14, color: "var(--danger)" }}>{window.t(lang, "upperBoundError", { max: window.fmtMoney(company.opexUpperBound) })}</div>
            </div>
          </div>
        )}

        {/* evidence */}
        {lines.length > 0 && (
          <div className="stack-lg">
            <div>
              <div className="eyebrow" style={{ marginBottom: 10 }}>{window.t(lang, "evidenceType")}</div>
              <div className="stack">
                <button className={`tap-card ${isSupplier ? "" : ""}`} onClick={() => chooseMode("supplier")}
                  style={{ padding: 14, borderColor: isSupplier ? "var(--accent-line)" : "var(--line-soft)", background: isSupplier ? "var(--accent-soft)" : "var(--surface)" }}>
                  <div className="tile-icon" style={{ width: 40, height: 40, borderRadius: 11, flex: "0 0 auto" }}><Icon name="user" size={19} /></div>
                  <div className="grow" style={{ flex: 1 }}>
                    <div style={{ fontWeight: 600, fontSize: 15 }}>{window.t(lang, "supplierMode")}</div>
                    <div className="hint" style={{ marginTop: 2, textWrap: "pretty" }}>{window.t(lang, "supplierModeDesc")}</div>
                  </div>
                  <span className={isSupplier ? "" : ""} style={{ flex: "0 0 auto", color: isSupplier ? "var(--accent)" : "var(--faint)" }}>
                    <Icon name={isSupplier ? "check" : "chevDown"} size={isSupplier ? 20 : 0} /></span>
                </button>
                <button className="tap-card" onClick={() => chooseMode("selfservice")}
                  style={{ padding: 14, borderColor: !isSupplier ? "var(--accent-line)" : "var(--line-soft)", background: !isSupplier ? "var(--accent-soft)" : "var(--surface)" }}>
                  <div className="tile-icon" style={{ width: 40, height: 40, borderRadius: 11, flex: "0 0 auto" }}><Icon name="basket" size={19} /></div>
                  <div className="grow" style={{ flex: 1 }}>
                    <div style={{ fontWeight: 600, fontSize: 15 }}>{window.t(lang, "selfServiceMode")}</div>
                    <div className="hint" style={{ marginTop: 2, textWrap: "pretty" }}>{window.t(lang, "selfServiceModeDesc")}</div>
                  </div>
                  <span style={{ flex: "0 0 auto", color: !isSupplier ? "var(--accent)" : "var(--faint)" }}>
                    {!isSupplier && <Icon name="check" size={20} />}</span>
                </button>
              </div>
            </div>

            <div>
              <div className="eyebrow" style={{ marginBottom: 10 }}>{window.t(lang, "photoEvidence")}</div>
              {isSupplier ? (
                <div className="stack-lg">
                  <div className="photo-grid">
                    <PhotoCapture lang={lang} label={window.t(lang, "sellerIdPhoto")} value={sellerId} onChange={setSellerId} />
                    <PhotoCapture lang={lang} label={window.t(lang, "workPhoto")} value={workPhoto} onChange={setWorkPhoto} />
                  </div>
                  <Field label={window.t(lang, "sellerSign")} required hint={window.t(lang, "drawSign")}>
                    <SignPad value={sellerSign} onChange={setSellerSign} />
                  </Field>
                </div>
              ) : (
                <PhotoCapture lang={lang} label={window.t(lang, "workPhoto")} value={workPhoto} onChange={setWorkPhoto} />
              )}
            </div>
          </div>
        )}
      </div>

      <div className="action-bar">
        <div className="between" style={{ padding: "0 4px" }}>
          <span className="muted">{whtTotal > 0 ? window.t(lang, "netPay") : window.t(lang, "total")}</span>
          <span className="num" style={{ fontSize: 22, fontWeight: 700 }}>฿{window.fmtMoney(netTotal)}</span>
        </div>
        <Button onClick={() => onReview({
          type: "OPX", companyId: company.id, docNo, lines, total, whtTotal, netTotal,
          evidenceMode, workPhoto,
          sellerId: isSupplier ? sellerId : null, sellerSign: isSupplier ? sellerSign : null,
        })} disabled={!canSend} icon="fwd">{window.t(lang, "next")}</Button>
      </div>

      {editing && (
        <OPEXLineSheet company={company} lang={lang} inputMode={inputMode} whtEnabled={isSupplier}
          initial={editing === "new" ? null : lines[editing.idx]}
          onSave={saveLine} onClose={() => setEditing(null)}
          onDelete={editing !== "new" ? () => { setLines((p) => p.filter((_, i) => i !== editing.idx)); setEditing(null); } : null} />
      )}
    </div>
  );
}

Object.assign(window, { OPEXForm });
