// bin.jsx — recycle-bin view for soft-deleted tasks.
//
// Shows every task the current user can see whose deleted_at is set.
// Each row exposes:
//   • the task name + project pill
//   • who deleted it + when (relative time)
//   • a countdown to auto-purge ("Auto-deletes in N days")
//   • a Restore button — moves the task back into the live tables
//   • a Delete forever button — hard-deletes immediately, skipping the
//     30-day waiting period (with a confirm prompt)
//
// The list refreshes automatically when the SSE stream reports a task
// event, so a teammate restoring a task in another tab is reflected
// here within a second.

function BinView({ onAfterChange }) {
  const [rows, setRows]       = React.useState(null);
  const [busyId, setBusyId]   = React.useState(null);
  const [error, setError]     = React.useState("");
  const [filter, setFilter]   = React.useState("");

  async function load() {
    setError("");
    try {
      const data = await api.bin.listTasks();
      setRows(Array.isArray(data) ? data : []);
    } catch (e) {
      setError((e && e.message) || "Couldn't load the bin.");
    }
  }

  React.useEffect(() => { load(); }, []);

  // Live updates — when SSE fires any task event, the bin list may have
  // gained or lost a row, so re-pull. Cheap (<1s) and only fires on
  // actual changes.
  React.useEffect(() => {
    let pending = null;
    function onTaskEvent() {
      if (pending) return;
      pending = setTimeout(() => { pending = null; load(); }, 250);
    }
    window.addEventListener("flowboard:rt:tasks.deleted", onTaskEvent);
    window.addEventListener("flowboard:rt:tasks.created", onTaskEvent);
    window.addEventListener("flowboard:rt:tasks.updated", onTaskEvent);
    return () => {
      if (pending) clearTimeout(pending);
      window.removeEventListener("flowboard:rt:tasks.deleted", onTaskEvent);
      window.removeEventListener("flowboard:rt:tasks.created", onTaskEvent);
      window.removeEventListener("flowboard:rt:tasks.updated", onTaskEvent);
    };
  }, []);

  async function restore(t) {
    if (busyId) return;
    setBusyId(t.id); setError("");
    try {
      await api.bin.restoreTask(t.id);
      await load();
      onAfterChange && onAfterChange();
    } catch (e) {
      setError("Couldn't restore: " + ((e && e.message) || "network error"));
    } finally {
      setBusyId(null);
    }
  }

  async function purge(t) {
    if (busyId) return;
    if (!confirm(`Permanently delete "${t.name}"?\nThis can't be undone.`)) return;
    setBusyId(t.id); setError("");
    try {
      await api.bin.purgeTask(t.id);
      await load();
      onAfterChange && onAfterChange();
    } catch (e) {
      setError("Couldn't purge: " + ((e && e.message) || "network error"));
    } finally {
      setBusyId(null);
    }
  }

  const q = filter.trim().toLowerCase();
  const visible = (rows || []).filter(r => {
    if (!q) return true;
    return (
      (r.name || "").toLowerCase().includes(q) ||
      (r.project_name || "").toLowerCase().includes(q) ||
      (r.deleted_by_name || "").toLowerCase().includes(q)
    );
  });

  return (
    <div className="bin-root">
      <div className="bin-header">
        <div className="bin-title-row">
          <h1 className="bin-title">
            <span className="bin-title-icon">🗑️</span> Bin
          </h1>
          <div className="bin-meta">
            Items here are kept for <b>30 days</b>, then auto-deleted forever.
          </div>
        </div>
        <div className="bin-toolbar">
          <input className="bin-search"
                 type="text"
                 placeholder="Search by task, project, or who deleted it"
                 value={filter}
                 onChange={(e) => setFilter(e.target.value)}/>
          <button type="button" className="btn" onClick={load}>Refresh</button>
        </div>
      </div>

      {error && <div className="bin-error">{error}</div>}

      {rows === null ? (
        <div className="bin-empty">Loading…</div>
      ) : visible.length === 0 ? (
        <div className="bin-empty">
          {q
            ? "No deleted tasks match your search."
            : "Nothing in the bin. Deleted tasks land here for 30 days before they're removed forever."}
        </div>
      ) : (
        <div className="bin-table">
          <div className="bin-table-head">
            <div>Task</div>
            <div>Project</div>
            <div>Deleted by</div>
            <div>Deleted</div>
            <div>Auto-deletes in</div>
            <div className="bin-col-actions">Actions</div>
          </div>
          {visible.map(t => (
            <BinRow key={t.id} t={t}
                    busy={busyId === t.id}
                    onRestore={() => restore(t)}
                    onPurge={() => purge(t)}/>
          ))}
        </div>
      )}
    </div>
  );
}

function BinRow({ t, busy, onRestore, onPurge }) {
  const deletedAgo = fmtRelative ? fmtRelative(t.deleted_at) : t.deleted_at;
  const purgeAt = t.purge_at ? new Date(t.purge_at) : null;
  const daysLeft = purgeAt
    ? Math.max(0, Math.ceil((purgeAt - new Date()) / (24 * 60 * 60 * 1000)))
    : null;
  const urgent = daysLeft != null && daysLeft <= 3;

  return (
    <div className={`bin-row ${busy ? "is-busy" : ""}`}>
      <div className="bin-cell-task">
        <div className="bin-name">{t.name}</div>
        <div className="bin-id">#{t.id}</div>
      </div>
      <div className="bin-cell-project">
        {t.project_color && <span className="bin-project-dot" style={{ background: t.project_color }}/>}
        <span>{t.project_name || "—"}</span>
      </div>
      <div className="bin-cell-actor">
        {t.deleted_by_name ? (
          <>
            <span className="bin-actor-dot" style={{ background: t.deleted_by_color || "#a3a8b6" }}/>
            <span>{t.deleted_by_name}</span>
          </>
        ) : <span className="bin-faint">—</span>}
      </div>
      <div className="bin-cell-when">{deletedAgo}</div>
      <div className={`bin-cell-purge ${urgent ? "is-urgent" : ""}`}>
        {daysLeft == null
          ? "—"
          : daysLeft === 0
            ? "Today"
            : `${daysLeft} day${daysLeft === 1 ? "" : "s"}`}
      </div>
      <div className="bin-cell-actions">
        <button type="button" className="btn"
                onClick={onRestore} disabled={busy}>
          {busy ? "…" : "Restore"}
        </button>
        <button type="button" className="btn bin-btn-danger"
                onClick={onPurge} disabled={busy}>
          Delete forever
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { BinView });
