"use client";

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

interface AuditLog {
  id: number; user_id: number; username: string; action: string;
  resource: string; resource_id: string | null; request_params: Record<string, unknown> | null;
  ip_address: string | null; result: string; error_message: string | null; created_at: string;
}

const ACTION_LABELS: Record<string, string> = {
  create: "创建", read: "查看", update: "更新", delete: "删除",
  login: "登录", logout: "登出",
};

export default function LogsPage() {
  const [logs, setLogs] = useState<AuditLog[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [action, setAction] = useState("");
  const [resource, setResource] = useState("");
  const [loading, setLoading] = useState(true);
  const [detailLog, setDetailLog] = useState<AuditLog | null>(null);
  const pageSize = 20;

  useEffect(() => { loadLogs(); }, [page, action, resource]);
  async function loadLogs() {
    setLoading(true);
    const params = new URLSearchParams({ page: String(page), pageSize: String(pageSize) });
    if (action) params.set("action", action);
    if (resource) params.set("resource", resource);
    const res = await fetch(`/api/logs?${params}`);
    const data = await res.json();
    setLogs(data.logs || []);
    setTotal(data.total || 0);
    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">共 {total} 条记录</p>
      </div>
      <div className="toolbar">
        <select className="form-input" style={{ maxWidth: "160px" }} value={action}
          onChange={(e) => { setAction(e.target.value); setPage(1); }}>
          <option value="">全部操作</option>
          {Object.entries(ACTION_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
        </select>
        <input type="text" className="form-input search-input" placeholder="搜索资源..."
          value={resource} onChange={(e) => { setResource(e.target.value); setPage(1); }} />
        <button
          className="btn btn-secondary"
          onClick={() => {
            const params = new URLSearchParams({ format: "csv" });
            if (action) params.set("action", action);
            if (resource) params.set("resource", resource);
            window.location.href = `/api/logs?${params}`;
          }}
        >
          导出 CSV
        </button>
      </div>
      <div className="card">
        {loading ? <div className="loading">加载中...</div> : (
          <div className="table-container">
            <table className="data-table">
              <thead><tr><th>时间</th><th>用户</th><th>操作</th><th>资源</th><th>结果</th><th>IP</th><th>详情</th></tr></thead>
              <tbody>
                {logs.map((log) => (
                  <tr key={log.id}>
                    <td>{format(new Date(log.created_at), "yyyy-MM-dd HH:mm:ss")}</td>
                    <td>{log.username}</td>
                    <td><span className="badge badge-neutral">{ACTION_LABELS[log.action] || log.action}</span></td>
                    <td>
                      <span style={{ fontSize: "12px", color: "#737373" }}>{log.resource}</span>
                      {log.resource_id && <span style={{ fontSize: "11px", color: "#a3a3a3", marginLeft: "4px" }}>#{log.resource_id}</span>}
                    </td>
                    <td><span className={`badge ${log.result === "success" ? "badge-success" : "badge-danger"}`}>{log.result === "success" ? "成功" : "失败"}</span></td>
                    <td style={{ fontSize: "12px" }}>{log.ip_address || "-"}</td>
                    <td><button className="btn btn-secondary btn-sm" onClick={() => setDetailLog(log)}>查看</button></td>
                  </tr>
                ))}
                {logs.length === 0 && <tr><td colSpan={7} style={{ textAlign: "center", padding: "24px", color: "#737373" }}>暂无数据</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>
      )}
      {detailLog && (
        <div className="modal-overlay" onClick={() => setDetailLog(null)}>
          <div className="modal" onClick={(e) => e.stopPropagation()} style={{ maxWidth: "600px" }}>
            <h2 className="modal-title">日志详情</h2>
            <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: "8px 16px", fontSize: "14px" }}>
              <span style={{ color: "#737373" }}>ID</span><span>{detailLog.id}</span>
              <span style={{ color: "#737373" }}>用户</span><span>{detailLog.username}</span>
              <span style={{ color: "#737373" }}>操作</span><span>{detailLog.action}</span>
              <span style={{ color: "#737373" }}>资源</span><span>{detailLog.resource}</span>
              <span style={{ color: "#737373" }}>资源ID</span><span>{detailLog.resource_id || "-"}</span>
              <span style={{ color: "#737373" }}>结果</span><span>{detailLog.result}</span>
              <span style={{ color: "#737373" }}>IP</span><span>{detailLog.ip_address || "-"}</span>
              <span style={{ color: "#737373" }}>时间</span><span>{format(new Date(detailLog.created_at), "yyyy-MM-dd HH:mm:ss")}</span>
              <span style={{ color: "#737373" }}>请求参数</span>
              <pre style={{ background: "#f4f4f5", padding: "8px", borderRadius: "4px", fontSize: "12px", overflow: "auto" }}>
                {detailLog.request_params ? JSON.stringify(detailLog.request_params, null, 2) : "-"}
              </pre>
              {detailLog.error_message && (<><span style={{ color: "#737373" }}>错误</span><span style={{ color: "#dc2626" }}>{detailLog.error_message}</span></>)}
            </div>
            <div className="modal-footer"><button className="btn btn-secondary" onClick={() => setDetailLog(null)}>关闭</button></div>
          </div>
        </div>
      )}
    </div>
  );
}
