// Admin · Customer Win-Back
// Finds customers who've gone quiet and lets Joy mail them a Thanks.io postcard
// with a unique discount code. Manual, one click per customer. Sending spends
// real Thanks.io credit unless the server is in dry-run mode (shown clearly).

function fmtDate(ms) {
  if (!ms) return "\u2014";
  try { return new Date(ms).toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" }); }
  catch (e) { return "\u2014"; }
}
function monthsAgo(ms) {
  if (!ms) return "";
  const m = Math.floor((Date.now() - ms) / (30 * 24 * 60 * 60 * 1000));
  return m <= 0 ? "this month" : m + (m === 1 ? " month ago" : " months ago");
}

function WinBack() {
  const app = useApp();
  const live = app.mode === "api";

  const [config, setConfig] = useState(null);
  const [months, setMonths] = useState(6);
  const [discountPct, setDiscountPct] = useState(15);
  const [rows, setRows] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [note, setNote] = useState("");
  const [sendingId, setSendingId] = useState("");
  const [view, setView] = useState("targets"); // 'targets' | 'mailable' | 'history'
  const [history, setHistory] = useState([]);
  const [mailable, setMailable] = useState([]);

  useEffect(() => {
    if (!live) return;
    api.winbackConfig().then((c) => {
      setConfig(c);
      setMonths(c.defaults.months);
      setDiscountPct(c.defaults.discountPct);
      loadDormant(c.defaults.months);
    }).catch((e) => setError(e.message));
  }, []);

  const loadDormant = (m) => {
    setLoading(true); setError("");
    api.winbackDormant(m == null ? months : m)
      .then((r) => setRows(r.customers || []))
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
  };
  const loadHistory = () => {
    api.winbackHistory().then(setHistory).catch((e) => setError(e.message));
  };
  const loadMailable = () => {
    setLoading(true); setError("");
    api.winbackMailable()
      .then((r) => setMailable(r.customers || []))
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
  };

  const send = async (row) => {
    const spend = config && !config.dryRun;
    const msg = spend
      ? "Mail a postcard to " + (row.name || row.email) + " at " + discountPct + "% off?\n\nThis spends Thanks.io credit (~$0.45\u2013$0.60)."
      : "Dry run: simulate a postcard to " + (row.name || row.email) + "? No card is mailed and no credit is spent.";
    if (!window.confirm(msg)) return;
    setSendingId(row.id); setError(""); setNote("");
    try {
      const res = await api.winbackSend({ customerId: row.id, discountPct });
      setNote(
        (res.dryRun ? "Dry run logged" : "Postcard sent") +
        " to " + (row.name || row.email) + " \u2014 code " + res.code + "."
      );
      if (view === "mailable") loadMailable(); else loadDormant();
    } catch (e) {
      setError(e.message);
    } finally {
      setSendingId("");
    }
  };

  if (!live) {
    return (
      <div className="stitched" style={{ padding: 18 }}>
        <h2 style={{ marginTop: 0 }}>Customer Win-Back</h2>
        <p style={{ color: "var(--ink-3)" }}>
          This tool talks to the live backend (dormant-customer data and Thanks.io).
          It's available on the deployed site, not in the local design preview.
        </p>
      </div>
    );
  }

  const eligible = rows.filter((r) => r.mailable && !r.mailedRecently).length;

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <h2 style={{ margin: 0 }}>Customer Win-Back</h2>
        <div style={{ color: "var(--ink-3)", fontSize: 14, marginTop: 4 }}>
          Reach customers who haven't ordered in a while with a personalized postcard and a one-time discount code.
        </div>
      </div>

      {/* Status banner */}
      {config && (
        <div className={"stitched " + (config.dryRun ? "stitched-sage" : "")}
             style={{ padding: "10px 14px", marginBottom: 14, fontSize: 13 }}>
          {config.dryRun
            ? "Dry-run mode is ON \u2014 sends are simulated and logged, no cards mailed, no credit spent. Flip WINBACK_DRY_RUN off to mail for real."
            : (config.configured
                ? "Live mode \u2014 sending mails a real postcard and spends Thanks.io credit."
                : "Thanks.io isn't configured yet (set THANKSIO_API_KEY). You can still review dormant customers below.")}
        </div>
      )}

      {error && <div style={{ color: "var(--rose-deep)", fontSize: 14, marginBottom: 10 }}>{error}</div>}
      {note &&  <div style={{ color: "var(--sage-deep)", fontSize: 14, marginBottom: 10 }}>{note}</div>}

      {/* Tabs */}
      <div style={{ display: "flex", gap: 8, marginBottom: 14 }}>
        <button className={"btn btn-small " + (view === "targets" ? "" : "btn-ghost")}
                onClick={() => setView("targets")}>Dormant customers</button>
        <button className={"btn btn-small " + (view === "mailable" ? "" : "btn-ghost")}
                onClick={() => { setView("mailable"); loadMailable(); }}>All mailable</button>
        <button className={"btn btn-small " + (view === "history" ? "" : "btn-ghost")}
                onClick={() => { setView("history"); loadHistory(); }}>History</button>
      </div>

      {view === "targets" && (
        <div>
          <div className="stitched" style={{ padding: 14, marginBottom: 14, display: "flex", gap: 18, flexWrap: "wrap", alignItems: "flex-end" }}>
            <div className="field" style={{ margin: 0 }}>
              <label>Quiet for at least</label>
              <select value={months} onChange={(e) => setMonths(Number(e.target.value))}>
                {[3, 4, 6, 9, 12, 18, 24].map((m) => <option key={m} value={m}>{m} months</option>)}
              </select>
            </div>
            <div className="field" style={{ margin: 0 }}>
              <label>Discount on the card</label>
              <select value={discountPct} onChange={(e) => setDiscountPct(Number(e.target.value))}>
                {[10, 15, 20, 25].map((p) => <option key={p} value={p}>{p}% off</option>)}
              </select>
            </div>
            <button className="btn" onClick={() => loadDormant()} disabled={loading}>
              {loading ? "Loading\u2026" : "Refresh list"}
            </button>
            <div style={{ flex: 1 }} />
            <div style={{ color: "var(--ink-3)", fontSize: 13, alignSelf: "center" }}>
              {rows.length} dormant · {eligible} ready to mail
            </div>
          </div>

          {rows.length === 0 && !loading && (
            <div className="stitched" style={{ padding: 24, textAlign: "center", color: "var(--ink-3)" }}>
              No customers have been quiet that long. Try a shorter window.
            </div>
          )}

          {rows.length > 0 && (
            <div className="stitched" style={{ padding: 0, overflow: "hidden" }}>
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 14 }}>
                <thead>
                  <tr style={{ textAlign: "left", color: "var(--ink-3)", borderBottom: "1px solid var(--line)" }}>
                    <th style={{ padding: "10px 14px" }}>Customer</th>
                    <th style={{ padding: "10px 14px" }}>Last order</th>
                    <th style={{ padding: "10px 14px" }}>Address</th>
                    <th style={{ padding: "10px 14px" }}>Last mailed</th>
                    <th style={{ padding: "10px 14px" }}></th>
                  </tr>
                </thead>
                <tbody>
                  {rows.map((r) => (
                    <tr key={r.id} style={{ borderBottom: "1px solid var(--line)" }}>
                      <td style={{ padding: "10px 14px" }}>
                        <div style={{ fontWeight: 600 }}>{r.name || "\u2014"}</div>
                        <div style={{ color: "var(--ink-3)", fontSize: 12 }}>{r.email}</div>
                      </td>
                      <td style={{ padding: "10px 14px" }}>
                        {fmtDate(r.lastOrderAt)}
                        <div style={{ color: "var(--ink-3)", fontSize: 12 }}>{monthsAgo(r.lastOrderAt)}</div>
                      </td>
                      <td style={{ padding: "10px 14px" }}>
                        {r.mailable
                          ? <span style={{ color: "var(--sage-deep)" }}>{r.city}{r.city && r.state ? ", " : ""}{r.state}</span>
                          : <span style={{ color: "var(--rose-deep)" }}>No address</span>}
                      </td>
                      <td style={{ padding: "10px 14px", color: "var(--ink-3)" }}>
                        {fmtDate(r.lastMailedAt)}
                      </td>
                      <td style={{ padding: "10px 14px", textAlign: "right" }}>
                        <button className="btn btn-small"
                          disabled={!r.mailable || r.mailedRecently || sendingId === r.id}
                          title={!r.mailable ? "No mailing address on file"
                               : r.mailedRecently ? "Mailed recently (within cooldown)" : ""}
                          onClick={() => send(r)}>
                          {sendingId === r.id ? "Sending\u2026"
                            : r.mailedRecently ? "Mailed"
                            : (config && config.dryRun ? "Simulate" : "Send postcard")}
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {view === "mailable" && (
        <div>
          <div className="stitched" style={{ padding: 14, marginBottom: 14, display: "flex", gap: 18, flexWrap: "wrap", alignItems: "flex-end" }}>
            <div className="field" style={{ margin: 0 }}>
              <label>Discount on the card</label>
              <select value={discountPct} onChange={(e) => setDiscountPct(Number(e.target.value))}>
                {[10, 15, 20, 25].map((p) => <option key={p} value={p}>{p}% off</option>)}
              </select>
            </div>
            <button className="btn" onClick={loadMailable} disabled={loading}>
              {loading ? "Loading\u2026" : "Refresh list"}
            </button>
            <div style={{ flex: 1 }} />
            <div style={{ color: "var(--ink-3)", fontSize: 13, alignSelf: "center" }}>
              {mailable.length} with a mailing address · {mailable.filter((r) => !r.mailedRecently).length} ready to mail
            </div>
          </div>

          <div className="stitched stitched-sage" style={{ padding: "10px 14px", marginBottom: 14, fontSize: 13 }}>
            Everyone with a complete mailing address, including customers imported from QuickBooks (who won't show under
            "Dormant" because that list is built from on-site orders only). The same discount code and cooldown rules apply.
          </div>

          {mailable.length === 0 && !loading && (
            <div className="stitched" style={{ padding: 24, textAlign: "center", color: "var(--ink-3)" }}>
              No customers with a complete mailing address yet. Import your customer list from the Customers tab.
            </div>
          )}

          {mailable.length > 0 && (
            <div className="stitched" style={{ padding: 0, overflow: "hidden" }}>
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 14 }}>
                <thead>
                  <tr style={{ textAlign: "left", color: "var(--ink-3)", borderBottom: "1px solid var(--line)" }}>
                    <th style={{ padding: "10px 14px" }}>Customer</th>
                    <th style={{ padding: "10px 14px" }}>Address</th>
                    <th style={{ padding: "10px 14px" }}>Last mailed</th>
                    <th style={{ padding: "10px 14px" }}></th>
                  </tr>
                </thead>
                <tbody>
                  {mailable.map((r) => (
                    <tr key={r.id} style={{ borderBottom: "1px solid var(--line)" }}>
                      <td style={{ padding: "10px 14px" }}>
                        <div style={{ fontWeight: 600 }}>{r.name || "\u2014"}</div>
                        <div style={{ color: "var(--ink-3)", fontSize: 12 }}>{r.email || "no email"}</div>
                      </td>
                      <td style={{ padding: "10px 14px" }}>
                        <span style={{ color: "var(--sage-deep)" }}>{r.city}{r.city && r.state ? ", " : ""}{r.state}</span>
                      </td>
                      <td style={{ padding: "10px 14px", color: "var(--ink-3)" }}>{fmtDate(r.lastMailedAt)}</td>
                      <td style={{ padding: "10px 14px", textAlign: "right" }}>
                        <button className="btn btn-small"
                          disabled={r.mailedRecently || sendingId === r.id}
                          title={r.mailedRecently ? "Mailed recently (within cooldown)" : ""}
                          onClick={() => send(r)}>
                          {sendingId === r.id ? "Sending\u2026"
                            : r.mailedRecently ? "Mailed"
                            : (config && config.dryRun ? "Simulate" : "Send postcard")}
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {view === "history" && (
        <div className="stitched" style={{ padding: 0, overflow: "hidden" }}>
          {history.length === 0 && (
            <div style={{ padding: 24, textAlign: "center", color: "var(--ink-3)" }}>No postcards sent yet.</div>
          )}
          {history.length > 0 && (
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 14 }}>
              <thead>
                <tr style={{ textAlign: "left", color: "var(--ink-3)", borderBottom: "1px solid var(--line)" }}>
                  <th style={{ padding: "10px 14px" }}>Sent</th>
                  <th style={{ padding: "10px 14px" }}>Customer</th>
                  <th style={{ padding: "10px 14px" }}>Code</th>
                  <th style={{ padding: "10px 14px" }}>Status</th>
                  <th style={{ padding: "10px 14px" }}>Redeemed</th>
                </tr>
              </thead>
              <tbody>
                {history.map((h) => (
                  <tr key={h.id} style={{ borderBottom: "1px solid var(--line)" }}>
                    <td style={{ padding: "10px 14px" }}>{fmtDate(h.createdAt)}{h.mode === "dryrun" ? " (dry)" : ""}</td>
                    <td style={{ padding: "10px 14px" }}>{h.name || h.email}</td>
                    <td style={{ padding: "10px 14px", fontFamily: "monospace" }}>{h.code} · {h.discountPct}%</td>
                    <td style={{ padding: "10px 14px", color: h.status === "sent" ? "var(--sage-deep)" : "var(--rose-deep)" }}>
                      {h.status}
                    </td>
                    <td style={{ padding: "10px 14px" }}>
                      <label style={{ display: "flex", gap: 6, alignItems: "center", cursor: "pointer", color: "var(--ink-3)" }}>
                        <input type="checkbox" checked={!!h.redeemedAt}
                          onChange={(e) => api.winbackRedeemed(h.id, e.target.checked)
                            .then(() => loadHistory()).catch((err) => setError(err.message))} />
                        {h.redeemedAt ? fmtDate(h.redeemedAt) : "mark used"}
                      </label>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { WinBack });
