// SAR drafts view — review, comment, close, or file SARs.

const { useState: useSARState, useEffect: useSAREffect, useMemo: useSARMemo } = React;

function formatAmount(n, cur) {
  const sym = { USD: "$", EUR: "€", GBP: "£", MXN: "MX$" }[cur] || "";
  return sym + Number(n || 0).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function formatDate(iso) {
  if (!iso) return "—";
  return new Date(iso).toLocaleString(undefined, { month: "short", day: "numeric", year: "numeric", hour: "2-digit", minute: "2-digit" });
}

function SARStatusPill({ status }) {
  const map = {
    draft: { cls: "pill med", label: "Draft" },
    under_review: { cls: "pill high", label: "Under review" },
    pending_review: { cls: "pill high", label: "Pending review" },
    filed: { cls: "pill ok", label: "Filed" },
    acknowledged: { cls: "pill low", label: "Acknowledged" },
    closed: { cls: "pill low", label: "Closed" },
    dismissed: { cls: "pill low", label: "Dismissed" },
  };
  const m = map[status] || { cls: "pill", label: status };
  return <span className={m.cls}>{m.label}</span>;
}

function SARDetail({ sar, onBack, onRefresh }) {
  const [note, setNote] = useSARState("");
  const [posting, setPosting] = useSARState(false);
  const [acting, setActing] = useSARState(false);
  const [message, setMessage] = useSARState(null);

  const postNote = async () => {
    if (!note.trim()) return;
    setPosting(true);
    try {
      await window.mossadApi.addSARNote(sar.id, note.trim());
      setNote("");
      setMessage({ type: "ok", text: "Note added" });
      await onRefresh();
    } catch (err) {
      setMessage({ type: "error", text: "Failed to add note: " + err.message });
    } finally {
      setPosting(false);
    }
  };

  const updateStatus = async (status) => {
    setActing(true);
    setMessage(null);
    try {
      await window.mossadApi.updateSAR(sar.id, { status });
      setMessage({ type: "ok", text: `SAR ${status.replace("_", " ")}` });
      await onRefresh();
    } catch (err) {
      setMessage({ type: "error", text: "Failed to update SAR: " + err.message });
    } finally {
      setActing(false);
    }
  };

  const fileSAR = async () => {
    setActing(true);
    setMessage(null);
    try {
      const result = await window.mossadApi.fileSAR(sar.id);
      setMessage({ type: "ok", text: `SAR filed: ${result.filing_reference || result.external_id}` });
      await onRefresh();
    } catch (err) {
      setMessage({ type: "error", text: "Failed to file SAR: " + err.message });
    } finally {
      setActing(false);
    }
  };

  const notes = sar.notes || [];
  const isFinal = sar.status === "filed" || sar.status === "acknowledged" || sar.status === "closed" || sar.status === "dismissed";

  return (
    <div style={{ padding: 18, overflow: "auto", flex: 1 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16 }}>
        <button className="btn ghost sm" onClick={onBack}>
          <Icon.Chevron size={11} style={{ transform: "rotate(180deg)" }} /> Back to SAR drafts
        </button>
        <span className="mono" style={{ fontSize: 12, color: "var(--fg-3)" }}>{sar.external_id}</span>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 14 }}>
        <div className="card">
          <div className="card-hd"><h3>SAR overview</h3></div>
          <div className="card-body">
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
              <SARStatusPill status={sar.status} />
              <span className="mono muted" style={{ fontSize: 12 }}>{formatDate(sar.created_at)}</span>
            </div>
            <div style={{ fontSize: 13, color: "var(--fg-2)", lineHeight: 1.6, marginBottom: 16 }}>
              {sar.suspicious_activity_description || "No description."}
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "160px 1fr", gap: "8px 12px", fontSize: 12.5 }}>
              <div className="muted">Linked case</div>
              <div className="mono">{sar.case_id}</div>
              <div className="muted">Total suspicious amount</div>
              <div className="mono">{formatAmount(sar.total_suspicious_amount, "USD")}</div>
              <div className="muted">Regulator</div>
              <div>{sar.regulator}</div>
              <div className="muted">Jurisdiction</div>
              <div>{sar.jurisdiction}</div>
              {sar.filing_reference && (
                <>
                  <div className="muted">Filing reference</div>
                  <div className="mono">{sar.filing_reference}</div>
                </>
              )}
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-hd"><h3>Actions</h3></div>
          <div className="card-body">
            {message && (
              <div style={{
                fontSize: 12, marginBottom: 10,
                color: message.type === "ok" ? "var(--risk-low)" : "var(--risk-high)",
                background: message.type === "ok" ? "var(--risk-low-bg)" : "var(--risk-high-bg)",
                padding: "6px 8px", borderRadius: 4,
              }}>{message.text}</div>
            )}
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              <button className="btn primary" onClick={fileSAR} disabled={acting || isFinal}>
                <Icon.Flag size={12} /> {acting ? "Working…" : isFinal ? "SAR final" : "File SAR"}
              </button>
              <button className="btn" onClick={() => updateStatus("closed")} disabled={acting || isFinal}>
                <Icon.X size={12} /> Close without filing
              </button>
              <button className="btn" onClick={() => updateStatus("dismissed")} disabled={acting || isFinal}>
                <Icon.X size={12} /> Dismiss
              </button>
            </div>
          </div>
        </div>
      </div>

      <div className="card" style={{ marginTop: 14 }}>
        <div className="card-hd"><h3>Review notes</h3></div>
        <div className="card-body">
          {!isFinal && (
            <div style={{ marginBottom: 14 }}>
              <textarea
                value={note}
                onChange={e => setNote(e.target.value)}
                placeholder="Add a review note…"
                style={{
                  width: "100%", minHeight: 80,
                  border: "1px solid var(--border)", background: "var(--bg-2)", color: "var(--fg)",
                  borderRadius: 6, padding: 8, font: "inherit", fontSize: 12.5, resize: "vertical", outline: "none",
                }}
              />
              <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 8 }}>
                <button className="btn sm primary" onClick={postNote} disabled={posting || !note.trim()}>
                  {posting ? "Adding…" : "Add note"}
                </button>
              </div>
            </div>
          )}
          {notes.length === 0 && <div className="muted" style={{ fontSize: 12 }}>No notes yet.</div>}
          {notes.length > 0 && (
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {notes.slice().reverse().map((n, i) => (
                <div key={i} style={{ padding: 10, background: "var(--bg-2)", border: "1px solid var(--border)", borderRadius: 6 }}>
                  <div style={{ fontSize: 12, color: "var(--fg-2)", lineHeight: 1.5, wordBreak: "break-word" }}>{n.content}</div>
                  <div className="mono" style={{ fontSize: 10, color: "var(--fg-3)", marginTop: 4 }}>
                    {n.created_by_name || "Unknown"} · {formatDate(n.created_at)}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function SARsView({ data, initialId }) {
  const sars = data?.sars || window.SARS_API || [];
  const [selectedSAR, setSelectedSAR] = useSARState(null);
  const [filter, setFilter] = useSARState("draft");

  useSAREffect(() => {
    if (!initialId) return;
    const found = sars.find(s => s.id === initialId);
    if (found) setSelectedSAR(found);
  }, [initialId, sars]);

  const filtered = useSARMemo(() => {
    if (filter === "all") return sars;
    return sars.filter(s => s.status === filter);
  }, [sars, filter]);

  if (selectedSAR) {
    return (
      <SARDetail
        sar={selectedSAR}
        onBack={() => setSelectedSAR(null)}
        onRefresh={async () => {
          if (data?.refresh) await data.refresh();
          const fresh = await window.mossadApi.fetchSAR(selectedSAR.id);
          setSelectedSAR(fresh);
        }}
      />
    );
  }

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
      <div style={{ padding: 18, borderBottom: "1px solid var(--border)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
          <h1 style={{ margin: 0, fontSize: 22, fontWeight: 600 }}>SAR drafts</h1>
          <span className="pill outline">{filtered.length.toLocaleString()}</span>
          <div style={{ flex: 1 }} />
          <button className="btn sm" onClick={data?.refresh} title="Refresh">
            <Icon.Refresh size={12} />
          </button>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          {["all", "draft", "under_review", "filed", "closed", "dismissed"].map(f => (
            <button
              key={f}
              className={`btn sm ${filter === f ? "primary" : ""}`}
              onClick={() => setFilter(f)}
              style={{ textTransform: "capitalize" }}
            >
              {f.replace("_", " ")}
            </button>
          ))}
        </div>
      </div>

      <div style={{ flex: 1, overflow: "auto" }}>
        <table className="tbl">
          <thead>
            <tr>
              <th>SAR ID</th>
              <th>Status</th>
              <th>Linked case</th>
              <th className="right">Amount</th>
              <th>Created</th>
              <th>Notes</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(s => (
              <tr key={s.id} onClick={() => setSelectedSAR(s)} style={{ cursor: "pointer" }}>
                <td><span className="mono" style={{ fontSize: 12 }}>{s.external_id}</span></td>
                <td><SARStatusPill status={s.status} /></td>
                <td><span className="mono" style={{ fontSize: 11.5, color: "var(--fg-3)" }}>{s.case_id}</span></td>
                <td className="right mono">{formatAmount(s.total_suspicious_amount, "USD")}</td>
                <td style={{ fontSize: 11.5, color: "var(--fg-3)" }}>{formatDate(s.created_at)}</td>
                <td>{(s.notes || []).length}</td>
              </tr>
            ))}
          </tbody>
        </table>
        {filtered.length === 0 && (
          <div style={{ padding: 40, textAlign: "center", color: "var(--fg-3)" }}>
            No SARs match the selected filter.
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { SARsView });
