// automations-view.jsx — workspace-wide task automations admin page.
//
// Owner / workspace-admin only (server enforces; the sidebar entry is
// gated client-side by canSeeAll). Shows:
//   • Workspace-wide rules — full CRUD (Add / Remove). These apply to
//     every project in the workspace.
//   • Per-project rules — read-only summary so admins can see what's
//     already configured per project without leaving the page. Click a
//     project name to jump to that project's settings → Automations
//     tab for editing.
//
// Conflict policy (documented for users): when a workspace-wide rule
// AND a project rule both match the same status change, the project
// rule wins. The backend enforces this in tasks.routes.js by sorting
// project rules first and skipping later rules whose target user is
// already an assignee.

(function () {
  const R = window.React;

  function AutomationsView() {
    const [wsId, setWsId]       = R.useState(null);
    const [wsRules, setWsRules] = R.useState([]);
    const [projRules, setProjRules] = R.useState([]); // [{project_id, project_name, rules:[]}]
    const [loading, setLoading] = R.useState(true);
    const [err, setErr]         = R.useState("");
    const [addOpen, setAddOpen] = R.useState(false);

    // Resolve workspace + projects.
    React.useEffect(() => {
      (async () => {
        try {
          const ws = (typeof window.WORKSPACE !== "undefined") ? window.WORKSPACE : null;
          const id = ws && ws.id;
          if (!id) { setErr("Could not determine workspace."); setLoading(false); return; }
          setWsId(id);
          await reload(id);
        } catch (e) {
          setErr((e && e.body && (e.body.message || e.body.error)) || "Could not load automations");
          setLoading(false);
        }
      })();
    }, []);

    async function reload(id) {
      setLoading(true); setErr("");
      try {
        const wsRes = await window.api.workspaces.automationRules.list(id || wsId);
        const all   = wsRes.rules || [];
        const wsR   = all.filter(r => !r.project_id);
        const proj  = all.filter(r => !!r.project_id);
        // Group project rules by project_id.
        const byProj = new Map();
        for (const r of proj) {
          if (!byProj.has(r.project_id)) byProj.set(r.project_id, []);
          byProj.get(r.project_id).push(r);
        }
        const PROJECTS = (typeof window.PROJECTS !== "undefined" && Array.isArray(window.PROJECTS)) ? window.PROJECTS : [];
        const out = [];
        for (const [pid, rules] of byProj) {
          const p = PROJECTS.find(x => x.id === pid);
          out.push({ project_id: pid, project_name: p ? p.name : pid, project_color: p && p.color, rules });
        }
        out.sort((a, b) => a.project_name.localeCompare(b.project_name));
        setWsRules(wsR);
        setProjRules(out);
      } catch (e) {
        setErr((e && e.body && (e.body.message || e.body.error)) || "Could not load automations");
      } finally { setLoading(false); }
    }

    async function removeWsRule(id) {
      if (!window.confirm("Remove this workspace-wide rule?")) return;
      try { await window.api.workspaces.automationRules.remove(wsId, id); await reload(wsId); }
      catch (e) { setErr((e && e.body && (e.body.message || e.body.error)) || "Could not delete"); }
    }

    function strategyLabel(r) {
      const PEOPLE = (typeof window.PEOPLE !== "undefined" && Array.isArray(window.PEOPLE)) ? window.PEOPLE : [];
      if (r.strategy === "user") {
        const u = PEOPLE.find(p => p.id === r.assignee_user_id);
        return u ? u.name : (r.assignee_user_id || "—");
      }
      if (r.strategy === "project_owner") return "Project owner";
      if (r.strategy === "reporter")      return "Reporter";
      if (r.strategy === "round_robin_team") return "Round-robin (team)";
      return r.strategy;
    }
    function statusLabel(s) {
      const STATUSES = (typeof window.STATUSES !== "undefined" && Array.isArray(window.STATUSES)) ? window.STATUSES : [];
      const m = STATUSES.find(x => x.id === s);
      return m ? m.label : s;
    }

    return (
      <div className="home-root" style={{ padding: 18, maxWidth: 980, margin: "0 auto" }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginBottom: 4 }}>
          <h1 style={{ margin: 0, fontSize: 20, fontWeight: 700, color: "var(--ink-strong, #0f1729)" }}>
            Automations
          </h1>
          <span style={{ fontSize: 12, color: "var(--ink-muted)" }}>
            Workspace-wide task rules. Project-specific rules override these.
          </span>
        </div>

        {err && <div style={{ color: "#c0223a", fontSize: 13, padding: "8px 0" }}>{err}</div>}

        {/* Workspace-wide rules */}
        <div style={{ border: "1px solid var(--border-row, #eaecf1)", borderRadius: 10, background: "var(--bg-card, #fff)", marginTop: 14 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 16px", borderBottom: "1px solid var(--border-row, #eaecf1)" }}>
            <div>
              <div style={{ fontSize: 14, fontWeight: 700, color: "var(--ink-strong, #0f1729)" }}>Workspace-wide rules</div>
              <div style={{ fontSize: 12, color: "var(--ink-muted)", marginTop: 1 }}>Applies to every project unless a project rule overrides.</div>
            </div>
            <button className="btn btn-primary" style={{ padding: "5px 12px", fontSize: 12 }} onClick={() => setAddOpen(true)}>+ Add rule</button>
          </div>
          {loading ? (
            <div style={{ padding: 24, color: "var(--ink-muted)", textAlign: "center" }}>Loading…</div>
          ) : wsRules.length === 0 ? (
            <div style={{ padding: 22, color: "var(--ink-muted)", fontSize: 13 }}>No workspace-wide rules yet.</div>
          ) : (
            <div>
              {wsRules.map(r => (
                <div key={r.id} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 16px", borderBottom: "1px solid var(--border-row, #f1f2f5)" }}>
                  <div style={{ fontSize: 12.5, color: "var(--ink-muted)", width: 50 }}>When</div>
                  <span style={{ padding: "2px 9px", borderRadius: 99, fontSize: 11.5, fontWeight: 700, background: "#eef1f6", color: "#5f6675" }}>
                    {statusLabel(r.status)}
                  </span>
                  <div style={{ fontSize: 12.5, color: "var(--ink-muted)" }}>→ assign to</div>
                  <span style={{ fontSize: 13, fontWeight: 600, color: "var(--ink-strong, #0f1729)" }}>{strategyLabel(r)}</span>
                  <div style={{ flex: 1 }}/>
                  <button className="btn" style={{ padding: "3px 9px", fontSize: 11.5 }} onClick={() => removeWsRule(r.id)}>Remove</button>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Per-project rules (read-only summary) */}
        <div style={{ marginTop: 18, border: "1px solid var(--border-row, #eaecf1)", borderRadius: 10, background: "var(--bg-card, #fff)" }}>
          <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--border-row, #eaecf1)" }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: "var(--ink-strong, #0f1729)" }}>Per-project rules</div>
            <div style={{ fontSize: 12, color: "var(--ink-muted)", marginTop: 1 }}>Configure these from each project's settings → Automations tab.</div>
          </div>
          {projRules.length === 0 ? (
            <div style={{ padding: 22, color: "var(--ink-muted)", fontSize: 13 }}>No project rules configured.</div>
          ) : (
            <div>
              {projRules.map(grp => (
                <div key={grp.project_id} style={{ padding: "10px 16px", borderBottom: "1px solid var(--border-row, #f1f2f5)" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
                    <span style={{ width: 8, height: 8, borderRadius: 99, background: grp.project_color || "#0073ea" }}/>
                    <span style={{ fontSize: 13, fontWeight: 700, color: "var(--ink-strong, #0f1729)" }}>{grp.project_name}</span>
                    <span style={{ fontSize: 11, color: "var(--ink-muted)" }}>· {grp.rules.length} rule{grp.rules.length === 1 ? "" : "s"}</span>
                  </div>
                  {grp.rules.map(r => (
                    <div key={r.id} style={{ display: "flex", alignItems: "center", gap: 10, padding: "4px 0", fontSize: 12.5, color: "var(--ink-muted)" }}>
                      <span>When</span>
                      <span style={{ padding: "1px 7px", borderRadius: 99, fontSize: 11, fontWeight: 700, background: "#eef1f6", color: "#5f6675" }}>
                        {statusLabel(r.status)}
                      </span>
                      <span>→</span>
                      <span style={{ color: "var(--ink-strong, #0f1729)", fontWeight: 600 }}>{strategyLabel(r)}</span>
                    </div>
                  ))}
                </div>
              ))}
            </div>
          )}
        </div>

        {addOpen && wsId && (
          <AddWsRuleModal wsId={wsId}
                          onClose={() => setAddOpen(false)}
                          onSaved={() => { setAddOpen(false); reload(wsId); }}/>
        )}
      </div>
    );
  }

  function AddWsRuleModal({ wsId, onClose, onSaved }) {
    const STATUSES = (typeof window.STATUSES !== "undefined" && Array.isArray(window.STATUSES)) ? window.STATUSES : [];
    const PEOPLE   = (typeof window.PEOPLE   !== "undefined" && Array.isArray(window.PEOPLE))   ? window.PEOPLE   : [];
    const [status, setStatus] = R.useState(STATUSES[0] ? STATUSES[0].id : "");
    const [strategy, setStrat] = R.useState("user");
    const [userId, setUserId] = R.useState(PEOPLE[0] ? PEOPLE[0].id : "");
    const [busy, setBusy] = R.useState(false);
    const [err, setErr]   = R.useState("");
    async function save() {
      if (!status) return;
      if (strategy === "user" && !userId) { setErr("Pick a user"); return; }
      setBusy(true); setErr("");
      try {
        await window.api.workspaces.automationRules.add(wsId, {
          status, strategy,
          assignee_user_id: strategy === "user" ? userId : null,
        });
        onSaved();
      } catch (e) {
        setErr((e && e.body && (e.body.message || e.body.error)) || "Could not save");
        setBusy(false);
      }
    }
    return window.ReactDOM.createPortal(
      <div className="modal-backdrop" onMouseDown={onClose}>
        <div className="modal" onMouseDown={e => e.stopPropagation()} style={{ width: 440 }}>
          <div className="modal-header"><div style={{ fontWeight: 700 }}>New workspace-wide rule</div>
            <button className="modal-close" onClick={onClose}>×</button>
          </div>
          <div className="modal-body" style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <label style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              <span style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".04em", color: "var(--ink-muted)" }}>When status becomes</span>
              <select value={status} onChange={e => setStatus(e.target.value)} style={{ padding: "7px 10px", borderRadius: 7, border: "1px solid var(--bd, #d8dce4)", fontSize: 13 }}>
                {STATUSES.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
              </select>
            </label>
            <label style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              <span style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".04em", color: "var(--ink-muted)" }}>Assign to</span>
              <select value={strategy} onChange={e => setStrat(e.target.value)} style={{ padding: "7px 10px", borderRadius: 7, border: "1px solid var(--bd, #d8dce4)", fontSize: 13 }}>
                <option value="user">A specific user</option>
                <option value="project_owner">The project owner</option>
                <option value="reporter">The reporter (whoever created the task)</option>
              </select>
            </label>
            {strategy === "user" && (
              <label style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                <span style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".04em", color: "var(--ink-muted)" }}>User</span>
                <select value={userId} onChange={e => setUserId(e.target.value)} style={{ padding: "7px 10px", borderRadius: 7, border: "1px solid var(--bd, #d8dce4)", fontSize: 13 }}>
                  {PEOPLE.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                </select>
              </label>
            )}
            <div style={{ fontSize: 11.5, color: "var(--ink-muted)", padding: "6px 8px", background: "#f6f8fc", borderRadius: 6 }}>
              This rule applies to every project in the workspace. Project-specific rules with the same status will override it.
            </div>
            {err && <div style={{ color: "#c0223a", fontSize: 12 }}>{err}</div>}
          </div>
          <div className="modal-footer">
            <button className="btn" onClick={onClose} disabled={busy}>Cancel</button>
            <button className="btn btn-primary" onClick={save} disabled={busy}>{busy ? "Saving…" : "Add rule"}</button>
          </div>
        </div>
      </div>,
      document.body
    );
  }

  Object.assign(window, { AutomationsView });
})();
