/* Admin dashboard — access code management */
const { useState, useMemo, useEffect } = React;
const { Eyebrow, Icon, DataRow } = window;

const DURATIONS = [7, 30, 60, 90, 180, 365];
const CODE_CHARS = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // no I, O, 0, 1

function makeCode() {
  let c = "";
  for (let i = 0; i < 8; i++) c += CODE_CHARS[Math.floor(Math.random() * CODE_CHARS.length)];
  return c;
}
function uniqueCode(existing) {
  let c;
  let tries = 0;
  do { c = makeCode(); tries++; } while (existing[c] && tries < 100);
  return c;
}
function fmtDate(iso) {
  if (!iso) return "—";
  const d = new Date(iso + "T12:00:00");
  return d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
}

function AdminDashboard() {
  const [codes,    setCodes]    = useState({});
  const [loading,  setLoading]  = useState(true);
  const [duration, setDuration] = useState(30);
  const [qty,      setQty]      = useState(1);
  const [newCodes, setNewCodes] = useState([]);
  const [filter,   setFilter]   = useState("all");
  const [copied,   setCopied]   = useState(null);
  const [editId,   setEditId]   = useState(null);
  const [editDays, setEditDays] = useState(30);

  // Load codes from Supabase on mount
  useEffect(() => {
    window.dbGetCodes().then(c => { setCodes(c); setLoading(false); }).catch(() => setLoading(false));
  }, []);

  async function generate() {
    const now = new Date().toISOString().slice(0, 10);
    const created = [];
    const newEntries = {};
    for (let i = 0; i < qty; i++) {
      const c = uniqueCode({ ...codes, ...newEntries });
      const data = { days: duration, label: duration + "-day pass", status: "active", createdAt: now };
      newEntries[c] = data;
      created.push(c);
    }
    await Promise.all(Object.entries(newEntries).map(([code, data]) => window.dbInsertCode(code, data)));
    setCodes(prev => ({ ...prev, ...newEntries }));
    setNewCodes(created);
  }

  async function deleteCode(code) {
    if (!window.confirm("Delete code " + code + "?")) return;
    await window.dbDeleteCode(code);
    setCodes(prev => { const u = { ...prev }; delete u[code]; return u; });
    setNewCodes(prev => prev.filter(c => c !== code));
  }

  function startEdit(code) {
    setEditId(code);
    setEditDays(codes[code].days);
  }

  async function saveEdit() {
    await window.dbUpdateCode(editId, editDays);
    setCodes(prev => ({
      ...prev,
      [editId]: { ...prev[editId], days: editDays, label: editDays + "-day pass" },
    }));
    setEditId(null);
  }

  function copy(text) {
    navigator.clipboard.writeText(text).catch(() => {});
    setCopied(text);
    setTimeout(() => setCopied(c => c === text ? null : c), 1800);
  }

  function copyAll() {
    if (!newCodes.length) return;
    copy(newCodes.join("\n"));
  }

  const codeList = useMemo(() => {
    return Object.entries(codes)
      .filter(([, v]) => filter === "all" || v.status === filter)
      .sort(([, a], [, b]) => (b.createdAt || "").localeCompare(a.createdAt || ""));
  }, [codes, filter]);

  const stats = useMemo(() => {
    const all = Object.values(codes);
    return { total: all.length, active: all.filter(c => c.status === "active").length, used: all.filter(c => c.status === "used").length };
  }, [codes]);

  if (loading) return (
    <div style={{ padding: 48, textAlign: "center", color: "var(--fg-muted)", fontSize: 14 }}>
      Loading codes…
    </div>
  );

  return (
    <div className="col fade-in" style={{ gap: 28 }}>

      {/* ── Header ───────────────────────────────────────── */}
      <div>
        <Eyebrow>Admin</Eyebrow>
        <h1 className="h-hero" style={{ marginTop: 12, fontSize: 56 }}>Code manager.</h1>
      </div>

      {/* ── Stats ────────────────────────────────────────── */}
      <div className="grid-3" style={{ gap: 16 }}>
        {[
          ["Total generated", stats.total, "var(--fg)"],
          ["Active",          stats.active, "var(--accent-ink)"],
          ["Redeemed",        stats.used,   "var(--fg-muted)"],
        ].map(([label, val, color]) => (
          <div key={label} className="card" style={{ padding: 24 }}>
            <Eyebrow>{label}</Eyebrow>
            <div className="h-data" style={{ fontSize: 52, marginTop: 8, color }}>{val}</div>
          </div>
        ))}
      </div>

      {/* ── Generate ─────────────────────────────────────── */}
      <div className="card" style={{ padding: 28 }}>
        <Eyebrow style={{ marginBottom: 20, display: "block" }}>Generate new codes</Eyebrow>

        <div className="row" style={{ gap: 20, flexWrap: "wrap", alignItems: "flex-end" }}>
          {/* Duration */}
          <div className="field" style={{ flex: "0 0 auto" }}>
            <label className="field-label">Duration</label>
            <div className="seg" style={{ marginTop: 6 }}>
              {DURATIONS.map(d => (
                <button key={d} className={duration === d ? "on" : ""} onClick={() => setDuration(d)}>
                  {d}d
                </button>
              ))}
            </div>
          </div>

          {/* Quantity */}
          <div className="field" style={{ flex: "0 0 120px" }}>
            <label className="field-label">Quantity</label>
            <div className="seg" style={{ marginTop: 6 }}>
              {[1, 5, 10].map(n => (
                <button key={n} className={qty === n ? "on" : ""} onClick={() => setQty(n)}>{n}</button>
              ))}
            </div>
          </div>

          <button className="btn btn-primary" style={{ marginBottom: 2 }} onClick={generate}>
            <Icon name="plus" size={14} /> Generate {qty > 1 ? qty + " codes" : "code"}
          </button>
        </div>

        {/* Newly generated codes */}
        {newCodes.length > 0 && (
          <div style={{ marginTop: 20 }}>
            <div className="between" style={{ marginBottom: 10 }}>
              <Eyebrow>Just generated</Eyebrow>
              <button className="btn btn-ghost btn-sm" onClick={copyAll}>
                Copy all
              </button>
            </div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
              {newCodes.map(c => (
                <button key={c} onClick={() => copy(c)} style={{
                  padding: "12px 18px",
                  background: copied === c ? "var(--accent)" : "var(--bg-soft)",
                  border: "1px solid " + (copied === c ? "var(--accent)" : "var(--line)"),
                  borderRadius: 10, cursor: "pointer",
                  transition: "all .15s",
                }}>
                  <span className="mono" style={{
                    fontSize: 17, fontWeight: 800, letterSpacing: "0.1em",
                    color: copied === c ? "var(--accent-ink)" : "var(--fg)",
                  }}>
                    {c}
                  </span>
                  <div className="muted mono" style={{ fontSize: 11, marginTop: 3 }}>
                    {copied === c ? "✓ Copied" : duration + "d · click to copy"}
                  </div>
                </button>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* ── Code table ───────────────────────────────────── */}
      <div className="card flush">
        <div className="between" style={{ padding: "20px 24px", borderBottom: "1px solid var(--line)" }}>
          <div>
            <Eyebrow>All codes</Eyebrow>
            <div className="muted mono" style={{ fontSize: 12, marginTop: 4 }}>
              {stats.total} total · {stats.active} active · {stats.used} redeemed
            </div>
          </div>
          <div className="seg">
            {["all", "active", "used"].map(f => (
              <button key={f} className={filter === f ? "on" : ""} onClick={() => setFilter(f)}>
                {f.charAt(0).toUpperCase() + f.slice(1)}
              </button>
            ))}
          </div>
        </div>

        {codeList.length === 0 ? (
          <div style={{ padding: 48, textAlign: "center", color: "var(--fg-muted)", fontSize: 14 }}>
            {filter === "all" ? "No codes yet. Generate some above." : "No " + filter + " codes."}
          </div>
        ) : (
          <div>
            {/* Column headers */}
            <div style={{
              display: "grid",
              gridTemplateColumns: "140px 90px 110px 90px 1fr auto",
              gap: 0, padding: "10px 24px",
              borderBottom: "1px solid var(--line-soft)",
              background: "var(--bg-soft)",
            }}>
              {["Code", "Days", "Created", "Status", "Used by", "Actions"].map(h => (
                <div key={h} className="eyebrow" style={{ fontSize: 10 }}>{h}</div>
              ))}
            </div>

            {codeList.map(([code, data], i) => (
              editId === code ? (
                /* Editing row */
                <div key={code} style={{
                  display: "flex", alignItems: "center", gap: 12,
                  padding: "14px 24px",
                  borderBottom: i < codeList.length - 1 ? "1px solid var(--line-soft)" : "none",
                  background: "var(--accent-soft)",
                }}>
                  <span className="mono" style={{ fontWeight: 800, fontSize: 15, letterSpacing: "0.08em", flex: "0 0 140px" }}>{code}</span>
                  <div className="seg" style={{ flex: "0 0 auto" }}>
                    {DURATIONS.map(d => (
                      <button key={d} className={editDays === d ? "on" : ""} onClick={() => setEditDays(d)} style={{ fontSize: 12 }}>{d}d</button>
                    ))}
                  </div>
                  <button className="btn btn-primary btn-sm" onClick={saveEdit}>Save</button>
                  <button className="btn btn-ghost btn-sm" onClick={() => setEditId(null)}>Cancel</button>
                </div>
              ) : (
                /* Normal row */
                <div key={code} style={{
                  display: "grid",
                  gridTemplateColumns: "140px 90px 110px 90px 1fr auto",
                  gap: 0, alignItems: "center",
                  padding: "14px 24px",
                  borderBottom: i < codeList.length - 1 ? "1px solid var(--line-soft)" : "none",
                }}>
                  {/* Code */}
                  <span className="mono" style={{ fontWeight: 800, fontSize: 14, letterSpacing: "0.08em" }}>
                    {code}
                  </span>

                  {/* Days */}
                  <span className="chip mono" style={{ alignSelf: "center", width: "fit-content" }}>{data.days}d</span>

                  {/* Created */}
                  <span className="muted mono" style={{ fontSize: 12 }}>{fmtDate(data.createdAt)}</span>

                  {/* Status */}
                  <span style={{
                    fontSize: 11, fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase",
                    color: data.status === "active" ? "var(--accent-ink)" : "var(--fg-muted)",
                  }}>
                    {data.status === "active" ? "● Active" : "○ Used"}
                  </span>

                  {/* Used by */}
                  <span className="muted mono" style={{ fontSize: 12 }}>
                    {data.usedBy ? data.usedBy + (data.usedAt ? " · " + fmtDate(data.usedAt) : "") : "—"}
                  </span>

                  {/* Actions */}
                  <div className="row" style={{ gap: 6, justifyContent: "flex-end" }}>
                    <button className="btn btn-ghost btn-sm" style={{ fontSize: 12 }} onClick={() => copy(code)}
                      title="Copy code">
                      {copied === code ? "✓" : "Copy"}
                    </button>
                    {data.status === "active" && (
                      <button className="btn btn-ghost btn-sm" style={{ fontSize: 12 }} onClick={() => startEdit(code)}
                        title="Edit duration">
                        Edit
                      </button>
                    )}
                    <button className="btn btn-ghost btn-sm"
                      style={{ fontSize: 12, color: "var(--m-protein)" }}
                      onClick={() => deleteCode(code)}
                      title="Delete">
                      Delete
                    </button>
                  </div>
                </div>
              )
            ))}
          </div>
        )}
      </div>

    </div>
  );
}

Object.assign(window, { AdminDashboard });
