"use client";

import { useEffect, useState } from "react";
import { format } from "date-fns";

interface AuditLog {
  source: "user_activity" | "project_audit";
  id: number;
  actor_uid: string;
  action: string;
  resource: string | null;
  ip_address: string | null;
  user_agent: string | null;
  created_at: string;
}

const ACTION_LABELS: Record<string, string> = {
  login: "登录", logout: "登出", register: "注册",
  create: "创建", update: "更新", delete: "删除",
  password_change: "改密", password_reset: "密码重置",
  transfer: "转移", rename: "重命名", settings_change: "设置变更",
};

const SOURCE_LABELS: Record<string, string> = {
  user_activity: "用户活动",
  project_audit: "项目审计",
};

export default function PlatformAuditPage() {
  const [logs, setLogs] = useState<AuditLog[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [source, setSource] = useState("");
  const [action, setAction] = useState("");
  const [loading, setLoading] = useState(true);
  const pageSize = 30;

  useEffect(() => { loadLogs(); }, [page, source, action]);

  function loadLogs() {
    setLoading(true);
    const params = new URLSearchParams({ page: String(page), pageSize: String(pageSize) });
    if (source) params.set("source", source);
    if (action) params.set("action", action);
    fetch(`/api/platform/audit-logs?${params}`)
      .then((r) => r.json())
      .then((data) => {
        setLogs(data.logs || []);
        setTotal(data.total || 0);
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }

  const totalPages = Math.ceil(total / pageSize);

  return (
    <div className="admin-content">
      <div className="page-header">
        <h1 className="page-title">平台审计日志</h1>
        <p className="page-subtitle">平台用户活动 + 项目操作记录（来源：user_activity_log + project_audit_log）</p>
      </div>
      <div className="toolbar">
        <select className="form-input" style={{ maxWidth: "160px" }}
          value={source} onChange={(e) => { setSource(e.target.value); setPage(1); }}>
          <option value="">全部来源</option>
          <option value="user">用户活动</option>
          <option value="project">项目审计</option>
        </select>
        <input type="text" className="form-input search-input" placeholder="搜索操作类型..."
          value={action} onChange={(e) => { setAction(e.target.value); setPage(1); }} />
      </div>
      <div className="card">
        {loading ? <div className="loading">加载中...</div> : logs.length === 0 ? (
          <div className="empty-state">
            <div className="empty-state-icon">📋</div>
            <p>暂无审计记录</p>
          </div>
        ) : (
          <div className="table-container">
            <table className="data-table">
              <thead>
                <tr>
                  <th>时间</th>
                  <th>来源</th>
                  <th>操作</th>
                  <th>用户 UID</th>
                  <th>资源</th>
                  <th>IP</th>
                </tr>
              </thead>
              <tbody>
                {logs.map((log) => (
                  <tr key={`${log.source}-${log.id}`}>
                    <td style={{ fontSize: "12px" }}>{format(new Date(log.created_at), "yyyy-MM-dd HH:mm:ss")}</td>
                    <td>
                      <span className={`badge ${log.source === "user_activity" ? "badge-success" : "badge-neutral"}`}>
                        {SOURCE_LABELS[log.source] || log.source}
                      </span>
                    </td>
                    <td><span className="badge badge-neutral">{ACTION_LABELS[log.action] || log.action}</span></td>
                    <td style={{ fontSize: "12px", fontFamily: "monospace" }}>{log.actor_uid || "—"}</td>
                    <td style={{ fontSize: "11px", maxWidth: "160px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}
                      title={log.resource || ""}>
                      {log.resource || "—"}
                    </td>
                    <td style={{ fontSize: "11px" }}>{log.ip_address || "—"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
      {totalPages > 1 && (
        <div className="pagination">
          <span className="pagination-info">第 {page} / {totalPages} 页，共 {total} 条</span>
          <button className="btn btn-secondary btn-sm" disabled={page <= 1} onClick={() => setPage(p => p - 1)}>上一页</button>
          <button className="btn btn-secondary btn-sm" disabled={page >= totalPages} onClick={() => setPage(p => p + 1)}>下一页</button>
        </div>
      )}
    </div>
  );
}
