// Case detail view — drill into a real case and see attached alerts.

const { useState: useCaseState, useEffect: useCaseEffect } = 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 CaseStatusPill({ status }) {
  const map = {
    open:       { cls: "pill info",  label: "Open" },
    in_review:  { cls: "pill med",   label: "In review" },
    escalated:  { cls: "pill high",  label: "Escalated" },
    closed:     { cls: "pill low",   label: "Closed" },
    sar_filed:  { cls: "pill high",  label: "SAR filed" },
  };
  const m = map[status] || { cls: "pill", label: status };
  return <span className={m.cls}>{m.label}</span>;
}

function SeverityDot({ s }) {
  const cls = s === "high" || s === "critical" ? "dot-high" : s === "med" || s === "medium" ? "dot-med" : "dot-low";
  return <span className={`dot ${cls}`} />;
}

function AlertNotesPanel({ alert, onOpenAlert }) {
  const notes = alert._raw?.notes || alert.notes || [];

  return (
    <div style={{ padding: "14px 16px", background: "var(--bg-2)", borderTop: "1px dashed var(--border)" }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <div>
          <div className="kpi-label" style={{ marginBottom: 6 }}>Details</div>
          <div style={{ fontSize: 12, color: "var(--fg-2)", lineHeight: 1.5 }}>
            {alert._raw?.description || alert.title || "No description."}
          </div>
          <div style={{ marginTop: 8, display: "flex", gap: 6, flexWrap: "wrap" }}>
            <span className="pill outline" style={{ fontSize: 11 }}>{alert.typology}</span>
            <span className="pill outline" style={{ fontSize: 11 }}>{alert.rule}</span>
            <span className="pill outline" style={{ fontSize: 11 }}>risk {alert.risk}</span>
          </div>
          {onOpenAlert && (
            <div style={{ marginTop: 10 }}>
              <span style={{ fontSize: 12, color: "var(--accent)", cursor: "pointer" }}
                    onClick={(e) => { e.stopPropagation(); onOpenAlert(alert); }}>
                Open alert page →
              </span>
            </div>
          )}
        </div>
        <div>
          <div className="kpi-label" style={{ marginBottom: 6 }}>Notes</div>
          {notes.length === 0 && (
            <div style={{ fontSize: 12, color: "var(--fg-3)", fontStyle: "italic" }}>No notes on this alert.</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)", 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 CaseDetailPage({ caseItem, onClose, onOpenAlert, data }) {
  const [alerts, setAlerts] = useCaseState([]);
  const [loading, setLoading] = useCaseState(false);
  const [error, setError] = useCaseState(null);
  const [comment, setComment] = useCaseState("");
  const [posting, setPosting] = useCaseState(false);
  const [message, setMessage] = useCaseState(null);
  const [expandedAlertId, setExpandedAlertId] = useCaseState(null);
  const [escalating, setEscalating] = useCaseState(false);
  const [escalateMessage, setEscalateMessage] = useCaseState(null);

  const caseId = caseItem._raw?.id || caseItem.id;

  const loadAlerts = async () => {
    setLoading(true);
    setError(null);
    try {
      const result = await window.mossadApi.fetchCaseAlerts(caseId);
      setAlerts(Array.isArray(result) ? result.map(window.mossadApi.mapAlert) : []);
    } catch (err) {
      setError("Failed to load alerts: " + err.message);
    } finally {
      setLoading(false);
    }
  };

  useCaseEffect(() => {
    loadAlerts();
  }, [caseId]);

  const postComment = async () => {
    if (!comment.trim()) return;
    setPosting(true);
    setMessage(null);
    try {
      await window.mossadApi.addCaseComment(caseId, comment.trim());
      setComment("");
      setMessage({ type: "ok", text: "Comment added" });
      if (data?.refresh) await data.refresh();
    } catch (err) {
      setMessage({ type: "error", text: "Failed to add comment: " + err.message });
    } finally {
      setPosting(false);
    }
  };

  const toggleAlert = (id) => {
    setExpandedAlertId(expanded => expanded === id ? null : id);
  };

  const escalateToSAR = async () => {
    if (!window.confirm(`Escalate case ${caseItem.external_id || caseItem.id} to SAR review?`)) return;
    setEscalating(true);
    setEscalateMessage(null);
    try {
      const result = await window.mossadApi.createSAR({
        case_id: caseId,
        suspicious_activity_description: `Escalated from case ${caseItem.external_id || caseItem.id}: ${caseItem.title}`,
      });
      setEscalateMessage({ type: "ok", text: `SAR draft created: ${result.external_id}` });
      if (data?.refresh) await data.refresh();
    } catch (err) {
      setEscalateMessage({ type: "error", text: "Failed to escalate to SAR: " + err.message });
    } finally {
      setEscalating(false);
    }
  };

  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={onClose}>
          <Icon.Chevron size={11} style={{ transform: "rotate(180deg)" }} /> Back to cases
        </button>
        <span className="muted">·</span>
        <span className="mono" style={{ fontSize: 12, color: "var(--fg-3)" }}>{caseItem.id}</span>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 14, marginBottom: 16 }}>
        <div className="card">
          <div className="card-hd"><h3>Case overview</h3></div>
          <div className="card-body">
            <h1 style={{ margin: "0 0 8px", fontSize: 20, fontWeight: 600 }}>{caseItem.title}</h1>
            <div style={{ display: "flex", gap: 8, marginBottom: 12 }}>
              <CaseStatusPill status={caseItem.status} />
              <span className={`pill ${caseItem.priority === "medium" ? "med" : caseItem.priority === "critical" ? "high" : caseItem.priority}`}>{caseItem.priority}</span>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "120px 1fr", gap: "8px 12px", fontSize: 12.5 }}>
              <div className="muted">Entity</div>
              <div>{caseItem.entity}</div>
              <div className="muted">Risk score</div>
              <div className="mono">{caseItem.risk}</div>
              <div className="muted">Alerts</div>
              <div className="mono">{caseItem.alerts}</div>
              <div className="muted">Amount</div>
              <div className="mono">{formatAmount(caseItem.amount, "USD")}</div>
              <div className="muted">Assignee</div>
              <div>{caseItem.assignee}</div>
              <div className="muted">Opened</div>
              <div>{formatDate(caseItem.opened)}</div>
            </div>
            <div style={{ marginTop: 14, paddingTop: 14, borderTop: "1px solid var(--border)" }}>
              {escalateMessage && (
                <div style={{
                  fontSize: 12, marginBottom: 8,
                  color: escalateMessage.type === "ok" ? "var(--risk-low)" : "var(--risk-high)",
                  background: escalateMessage.type === "ok" ? "var(--risk-low-bg)" : "var(--risk-high-bg)",
                  padding: "6px 8px", borderRadius: 4,
                }}>{escalateMessage.text}</div>
              )}
              <button
                className="btn danger"
                style={{ width: "100%", justifyContent: "center" }}
                onClick={escalateToSAR}
                disabled={escalating || caseItem.status === "escalated" || caseItem.status === "sar_filed"}
              >
                <Icon.Flag size={12} />
                {escalating ? "Escalating…" : caseItem.status === "escalated" ? "Already escalated to SAR" : caseItem.status === "sar_filed" ? "SAR filed" : "Escalate to SAR review"}
              </button>
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-hd"><h3>Add comment</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>
            )}
            <textarea
              value={comment}
              onChange={e => setComment(e.target.value)}
              placeholder="Add a comment…"
              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={postComment} disabled={posting || !comment.trim()}>
                {posting ? "Adding…" : "Add comment"}
              </button>
            </div>
          </div>
        </div>
      </div>

      <div className="card">
        <div className="card-hd">
          <h3>Attached alerts ({caseItem.alerts})</h3>
          <span style={{ flex: 1 }} />
          {loading && <span className="muted" style={{ fontSize: 12 }}>Loading…</span>}
        </div>
        <div className="card-body" style={{ padding: 0 }}>
          {error && <div style={{ padding: 16, color: "var(--risk-high)" }}>{error}</div>}
          {!loading && alerts.length === 0 && <div style={{ padding: 24, textAlign: "center", color: "var(--fg-3)" }}>No alerts attached.</div>}
          {alerts.length > 0 && (
            <table className="tbl">
              <thead>
                <tr>
                  <th style={{ width: 28 }}></th>
                  <th>Alert</th>
                  <th>Severity</th>
                  <th>Subject</th>
                  <th className="right">Amount</th>
                  <th>Status</th>
                  <th>Opened</th>
                </tr>
              </thead>
              <tbody>
                {alerts.map(a => {
                  const expanded = expandedAlertId === a.id;
                  return (
                    <React.Fragment key={a.id}>
                      <tr onClick={() => toggleAlert(a.id)} style={{ cursor: "pointer" }} className={expanded ? "expanded" : ""}>
                        <td style={{ textAlign: "center" }}>
                          <span style={{ display: "inline-block", transition: "transform 0.15s", transform: expanded ? "rotate(90deg)" : "rotate(0deg)", color: "var(--fg-3)" }}>
                            <Icon.Chevron size={12} />
                          </span>
                        </td>
                        <td><span className="mono" style={{ fontSize: 12 }}>{a.external_id}</span></td>
                        <td><span className={`pill ${a.severity === "medium" ? "med" : a.severity}`}><SeverityDot s={a.severity} /> {a.severity}</span></td>
                        <td>{a.subject}</td>
                        <td className="right mono">{formatAmount(a.amount, a.currency)}</td>
                        <td><span className="pill outline">{a.status}</span></td>
                        <td className="mono" style={{ fontSize: 11.5, color: "var(--fg-3)" }}>{formatDate(a.opened)}</td>
                      </tr>
                      {expanded && (
                        <tr>
                          <td colSpan={7} style={{ padding: 0 }}>
                            <AlertNotesPanel alert={a} onOpenAlert={onOpenAlert} />
                          </td>
                        </tr>
                      )}
                    </React.Fragment>
                  );
                })}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CaseDetailPage });
