// Audit log — system event log, grouped by date

const ACTION_META = {
  // 用戶管理
  "永久封鎖":    { tone: "danger",  icon: "ban" },
  "暫時封鎖":    { tone: "danger",  icon: "ban" },
  "解除封鎖":    { tone: "success", icon: "check" },
  "發送警告":    { tone: "warn",    icon: "alert" },
  "累計違規點數": { tone: "warn",   icon: "alert" },
  "鎖定功能":    { tone: "warn",    icon: "lock" },
  "更新功能鎖定": { tone: "warn",   icon: "lock" },
  "強制登出":    { tone: "default", icon: "logout" },
  // 創作者申請
  "通過創作者申請": { tone: "success", icon: "check" },
  "拒絕創作者申請": { tone: "danger",  icon: "x" },
  // 內容管理
  "隱藏內容":    { tone: "warn",    icon: "eye-off" },
  "下架內容":    { tone: "warn",    icon: "ban" },
  "刪除內容":    { tone: "danger",  icon: "trash" },
  "復原內容":    { tone: "success", icon: "check" },
  // 調解與檢舉
  "調解裁定":   { tone: "warn",    icon: "alert" },
  "處置檢舉":   { tone: "danger",  icon: "ban" },
  "駁回檢舉":   { tone: "default", icon: "x" },
  // 系統
  "新增管理員":  { tone: "success", icon: "shield" },
};

const TONE_COLORS = {
  danger:  { bg: "var(--danger-soft)",  fg: "var(--danger)",  dot: "#ef4444" },
  warn:    { bg: "var(--warn-soft)",    fg: "var(--warn)",    dot: "#f59e0b" },
  success: { bg: "var(--success-soft)", fg: "var(--success)", dot: "#22c55e" },
  default: { bg: "var(--surface-2)",    fg: "var(--ink-3)",   dot: "#94a3b8" },
};

const fmtDate = (iso) => {
  const d = new Date(iso);
  const today = new Date();
  const yesterday = new Date(today); yesterday.setDate(today.getDate() - 1);
  const isoDate = iso.slice(0, 10);
  if (isoDate === today.toISOString().slice(0, 10)) return "今天";
  if (isoDate === yesterday.toISOString().slice(0, 10)) return "昨天";
  return d.toLocaleDateString("zh-TW", { year: "numeric", month: "long", day: "numeric", weekday: "short" });
};

const fmtExactTime = (iso) => new Date(iso).toLocaleTimeString("zh-TW", {
  hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false,
});

const fmtFullDateTime = (iso) => new Date(iso).toLocaleString("zh-TW", {
  year: "numeric", month: "2-digit", day: "2-digit",
  hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false,
});

// Build human-readable summary for a log entry
const buildSummary = (l) => {
  const admin = l.adminEmail?.split("@")[0] || "未知管理員";
  const target = l.targetUserName ? `「${l.targetUserName}」` : "用戶";
  switch (l.action) {
    case "永久封鎖":    return `${admin} 將 ${target} 永久封鎖`;
    case "暫時封鎖":    return `${admin} 將 ${target} 暫時封鎖${l.details?.duration ? `（${l.details.duration}）` : ""}`;
    case "解除封鎖":    return `${admin} 解除了 ${target} 的封鎖`;
    case "發送警告":    return `${admin} 向 ${target} 發送警告`;
    case "累計違規點數": return `${admin} 對 ${target} 累計違規點數`;
    case "鎖定功能":    return `${admin} 鎖定了 ${target} 的功能${l.details?.features?.length ? `：${l.details.features.join("、")}` : ""}`;
    case "更新功能鎖定": return `${admin} 更新了 ${target} 的功能鎖定`;
    case "強制登出":    return `${admin} 強制 ${target} 登出`;
    case "通過創作者申請": return `${admin} 通過了 ${target} 的創作者申請`;
    case "拒絕創作者申請": return `${admin} 拒絕了 ${target} 的創作者申請${l.details?.reason ? `（${l.details.reason}）` : ""}`;
    case "隱藏內容":    return `${admin} 將${l.details?.contentType ? `「${({ products:"商品",posts:"動態",solicits:"徵稿" })[l.details.contentType] || l.details.contentType}」` : "內容"} ${l.targetUserName || ""} 設為隱藏`;
    case "下架內容":    return `${admin} 將${l.details?.contentType ? `「${({ products:"商品",posts:"動態",solicits:"徵稿" })[l.details.contentType] || l.details.contentType}」` : "內容"} ${l.targetUserName || ""} 下架`;
    case "刪除內容":    return `${admin} 永久刪除了${l.details?.contentType ? `「${({ products:"商品",posts:"動態",solicits:"徵稿" })[l.details.contentType] || l.details.contentType}」` : "內容"} ${l.targetUserName || ""}`;
    case "復原內容":    return `${admin} 將 ${l.targetUserName || "內容"} 復原為公開`;
    case "新增管理員":  return `${admin} 邀請了 ${l.targetUserName || target} 成為管理員`;
    case "調解裁定":   return `${admin} 對訂單 ${target} 做出調解裁定：${l.details?.outcome ?? ""}`;
    case "處置檢舉":   return `${admin} 處置了對 ${target} 的檢舉（${l.details?.reason ?? ""}）`;
    case "駁回檢舉":   return `${admin} 駁回了對 ${target} 的檢舉（${l.details?.reason ?? ""}）`;
    default:           return `${admin} 執行了「${l.action}」`;
  }
};

const LogEntry = ({ log, onClick }) => {
  const meta = ACTION_META[log.action] || { tone: "default", icon: "scroll" };
  const colors = TONE_COLORS[meta.tone];

  return (
    <div onClick={() => onClick(log)} style={{
      display: "flex", gap: 14, padding: "12px 20px",
      cursor: "pointer", transition: "background .1s",
      borderBottom: "1px solid var(--border)",
    }}
      onMouseEnter={e => e.currentTarget.style.background = "var(--surface-2)"}
      onMouseLeave={e => e.currentTarget.style.background = "transparent"}
    >
      {/* Time column */}
      <div style={{ width: 72, flexShrink: 0, paddingTop: 2 }}>
        <div className="mono" style={{ fontSize: 12, color: "var(--ink-3)", lineHeight: 1.4 }}>
          {fmtExactTime(log.createdAt)}
        </div>
      </div>

      {/* Dot + line */}
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", flexShrink: 0 }}>
        <div style={{
          width: 9, height: 9, borderRadius: "50%",
          background: colors.dot, marginTop: 4, flexShrink: 0,
          boxShadow: `0 0 0 3px ${colors.bg}`,
        }}/>
      </div>

      {/* Content */}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 3 }}>
          {/* Action badge */}
          <span style={{
            display: "inline-flex", alignItems: "center", gap: 4,
            padding: "2px 8px", borderRadius: 6, fontSize: 11.5, fontWeight: 600,
            background: colors.bg, color: colors.fg,
          }}>
            <Icon name={meta.icon} size={11}/>
            {log.action}
          </span>
          {/* Admin */}
          <span style={{
            display: "inline-flex", alignItems: "center", gap: 5,
            fontSize: 12, color: "var(--ink-3)",
          }}>
            <div style={{
              width: 18, height: 18, borderRadius: "50%",
              background: "var(--accent-soft)", color: "var(--accent-ink)",
              display: "flex", alignItems: "center", justifyContent: "center",
              fontSize: 9, fontWeight: 700, flexShrink: 0,
            }}>
              {(log.adminEmail?.split("@")[0] || "?")[0].toUpperCase()}
            </div>
            {log.adminEmail?.split("@")[0] || "—"}
          </span>
        </div>

        {/* Summary sentence */}
        <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5 }}>
          {buildSummary(log)}
        </div>

        {/* Reason / extra detail */}
        {log.details?.reason && (
          <div style={{
            marginTop: 5, fontSize: 12, color: "var(--ink-3)",
            background: "var(--surface-2)", borderRadius: 6,
            padding: "4px 10px", display: "inline-block",
          }}>
            原因：{log.details.reason}
          </div>
        )}
      </div>

      {/* Arrow */}
      <div style={{ color: "var(--ink-4)", paddingTop: 3, flexShrink: 0 }}>
        <Icon name="arrow-right" size={14}/>
      </div>
    </div>
  );
};

const AuditPage = () => {
  const [logs, setLogs] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [query, setQuery] = React.useState("");
  const [filterAction, setFilterAction] = React.useState("all");
  const [filterAdmin, setFilterAdmin] = React.useState("all");
  const [detail, setDetail] = React.useState(null);

  React.useEffect(() => {
    fetch("/api/admin/audit?limit=500")
      .then(r => r.ok ? r.json() : [])
      .then(d => { setLogs(Array.isArray(d) ? d : []); setLoading(false); })
      .catch(() => setLoading(false));
  }, []);

  const adminEmails = [...new Set(logs.map(l => l.adminEmail))];
  const actionTypes = [...new Set(logs.map(l => l.action))];

  const filtered = logs.filter(l => {
    if (filterAction !== "all" && l.action !== filterAction) return false;
    if (filterAdmin !== "all" && l.adminEmail !== filterAdmin) return false;
    if (query) {
      const q = query.toLowerCase();
      if (
        !l.action?.toLowerCase().includes(q) &&
        !l.adminEmail?.toLowerCase().includes(q) &&
        !l.targetUserName?.toLowerCase().includes(q) &&
        !l.details?.reason?.toLowerCase().includes(q)
      ) return false;
    }
    return true;
  });

  // Group filtered logs by date
  const grouped = [];
  const seenDates = {};
  filtered.forEach(l => {
    const date = l.createdAt?.slice(0, 10) || "";
    if (!seenDates[date]) {
      seenDates[date] = true;
      grouped.push({ type: "date", date, label: fmtDate(l.createdAt) });
    }
    grouped.push({ type: "log", log: l });
  });

  return (
    <div className="fade-in">
      <PageHeader
        title="審計日誌"
        subtitle={`所有管理員操作的不可篡改紀錄${logs.length > 0 ? ` · 共 ${logs.length} 筆` : ""}`}
        actions={<Button variant="secondary" icon="download" onClick={() => {
          csvDownload(`audit_${Date.now()}.csv`,
            ["時間","管理員","操作","對象","原因"],
            filtered.map(l => [fmtFullDateTime(l.createdAt), l.adminEmail, l.action, l.targetUserName ?? "", l.details?.reason ?? ""])
          );
        }}>匯出日誌</Button>}
      />

      {/* Filter bar */}
      <div style={{ display: "flex", gap: 10, marginBottom: 16, flexWrap: "wrap" }}>
        <div style={{ flex: 1, minWidth: 260, maxWidth: 400 }}>
          <Input icon="search" placeholder="搜尋操作類型、管理員、對象用戶、原因…" value={query} onChange={e => setQuery(e.target.value)}/>
        </div>
        <Select value={filterAction} onChange={setFilterAction} options={[
          { value: "all", label: "所有操作類型" },
          ...actionTypes.map(a => ({ value: a, label: a })),
        ]}/>
        <Select value={filterAdmin} onChange={setFilterAdmin} options={[
          { value: "all", label: "所有管理員" },
          ...adminEmails.map(e => ({ value: e, label: e.split("@")[0] })),
        ]}/>
      </div>

      {/* Log list */}
      {loading ? (
        <div style={{ padding: "80px 0", textAlign: "center", color: "var(--ink-4)", fontSize: 13 }}>
          <Icon name="scroll" size={24} style={{ marginBottom: 10, display: "block", margin: "0 auto 10px" }}/>
          載入中…
        </div>
      ) : filtered.length === 0 ? (
        <Card padding={60}>
          <div style={{ textAlign: "center", color: "var(--ink-4)" }}>
            <Icon name="scroll" size={30} style={{ marginBottom: 12 }}/>
            <div style={{ fontSize: 14, marginTop: 10 }}>
              {logs.length === 0 ? "尚無任何操作紀錄" : "無符合條件的紀錄"}
            </div>
            {logs.length > 0 && (
              <div style={{ fontSize: 12.5, marginTop: 6 }}>請嘗試調整篩選條件</div>
            )}
          </div>
        </Card>
      ) : (
        <Card padding={0} style={{ overflow: "hidden" }}>
          {/* Log header */}
          <div style={{
            padding: "12px 20px",
            borderBottom: "1px solid var(--border)",
            display: "flex", alignItems: "center", gap: 16,
            background: "var(--surface-2)",
          }}>
            <span style={{ fontSize: 11.5, fontWeight: 600, letterSpacing: 0.5, color: "var(--ink-3)", textTransform: "uppercase" }}>
              時間
            </span>
            <span style={{ fontSize: 11.5, fontWeight: 600, letterSpacing: 0.5, color: "var(--ink-3)", textTransform: "uppercase", marginLeft: 20 }}>
              操作紀錄
            </span>
            <span style={{ marginLeft: "auto", fontSize: 12, color: "var(--ink-4)" }}>
              顯示 {Math.min(filtered.length, 200)} / {filtered.length} 筆
            </span>
          </div>

          {grouped.slice(0, 600).map((item, i) => {
            if (item.type === "date") {
              return (
                <div key={`d-${item.date}`} style={{
                  padding: "8px 20px",
                  background: "var(--surface)",
                  borderBottom: "1px solid var(--border)",
                  display: "flex", alignItems: "center", gap: 12,
                }}>
                  <div style={{
                    fontSize: 11, fontWeight: 700, letterSpacing: 0.8,
                    color: "var(--ink-3)", textTransform: "uppercase",
                  }}>{item.label}</div>
                  <div style={{ flex: 1, height: 1, background: "var(--border)" }}/>
                  <div style={{ fontSize: 11, color: "var(--ink-4)" }}>
                    {filtered.filter(l => l.createdAt?.slice(0, 10) === item.date).length} 筆操作
                  </div>
                </div>
              );
            }
            return <LogEntry key={item.log.id} log={item.log} onClick={setDetail}/>;
          })}

          {filtered.length > 200 && (
            <div style={{
              padding: "14px 20px", textAlign: "center",
              fontSize: 12.5, color: "var(--ink-4)",
              borderTop: "1px solid var(--border)",
            }}>
              僅顯示最近 200 筆，共 {filtered.length} 筆符合條件
            </div>
          )}
        </Card>
      )}

      {/* Detail modal */}
      <Modal open={!!detail} onClose={() => setDetail(null)} width={500}>
        {detail && (() => {
          const meta = ACTION_META[detail.action] || { tone: "default", icon: "scroll" };
          const colors = TONE_COLORS[meta.tone];
          return (
            <div style={{ padding: 24 }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 20 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <div style={{
                    width: 36, height: 36, borderRadius: 10,
                    background: colors.bg, color: colors.fg,
                    display: "flex", alignItems: "center", justifyContent: "center",
                  }}>
                    <Icon name={meta.icon} size={18}/>
                  </div>
                  <div>
                    <div style={{ fontSize: 16, fontWeight: 700 }}>{detail.action}</div>
                    <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 1 }}>操作詳細紀錄</div>
                  </div>
                </div>
                <button onClick={() => setDetail(null)} style={{ color: "var(--ink-3)" }}><Icon name="x" size={18}/></button>
              </div>

              {/* Summary */}
              <div style={{
                padding: "12px 16px", borderRadius: 10,
                background: colors.bg, marginBottom: 16,
                fontSize: 13.5, color: colors.fg, fontWeight: 500,
              }}>
                {buildSummary(detail)}
              </div>

              {/* Fields */}
              <div style={{ display: "flex", flexDirection: "column", gap: 1, background: "var(--border)", borderRadius: 10, overflow: "hidden" }}>
                {[
                  ["操作時間", fmtFullDateTime(detail.createdAt)],
                  ["執行管理員", detail.adminEmail || "—"],
                  ["對象用戶", detail.targetUserName || "—"],
                  ["對象 ID", detail.targetUserId || "—", true],
                  ...(detail.details?.reason ? [["原因", detail.details.reason]] : []),
                  ...(detail.details?.duration ? [["封鎖期限", detail.details.duration]] : []),
                  ...(detail.details?.points ? [["累計點數", String(detail.details.points)]] : []),
                  ...(detail.details?.features?.length ? [["鎖定功能", detail.details.features.join("、")]] : []),
                  ["紀錄編號", detail.id, true],
                ].map(([k, v, mono], i) => (
                  <div key={i} style={{ display: "flex", padding: "10px 14px", background: "var(--surface)", gap: 12 }}>
                    <div style={{ fontSize: 12, color: "var(--ink-3)", width: 80, flexShrink: 0, paddingTop: 1 }}>{k}</div>
                    <div style={{
                      fontSize: 12.5,
                      fontFamily: mono ? "var(--font-mono)" : "inherit",
                      wordBreak: "break-all", color: "var(--ink)",
                    }}>{v}</div>
                  </div>
                ))}
              </div>
            </div>
          );
        })()}
      </Modal>
    </div>
  );
};

window.AuditPage = AuditPage;
