import { useEffect, useMemo, useState } from 'react'
import { listAuditLogs } from '../services/api.js'

// 操作日志运营 Tab：聚合 cf-worker /api/audit 数据，方便运营查 谁/什么时候/做了什么
const ACTION_LABELS = {
  'skill.create': { label: '创建 Skill',  color: 'bg-emerald-100 text-emerald-700' },
  'skill.update': { label: '更新 Skill',  color: 'bg-blue-100 text-blue-700'       },
  'skill.delete': { label: '删除 Skill',  color: 'bg-rose-100 text-rose-700'       },
  'skill.upload': { label: '上传文件',    color: 'bg-amber-100 text-amber-700'     },
}

function fmtTime(sec) {
  if (!sec) return '-'
  const d = new Date(Number(sec) * 1000)
  if (isNaN(d.getTime())) return '-'
  const pad = (n) => String(n).padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}

function parseMeta(s) {
  if (!s) return null
  try { return typeof s === 'string' ? JSON.parse(s) : s } catch { return s }
}

export default function AuditLog() {
  const [list, setList] = useState([])
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [size] = useState(50)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [action, setAction] = useState('')
  const [actorPhone, setActorPhone] = useState('')

  const fetchData = async (p = page) => {
    setLoading(true)
    setError('')
    try {
      const r = await listAuditLogs({ action, actor_phone: actorPhone.trim(), page: p, size })
      setList(Array.isArray(r?.data) ? r.data : [])
      setTotal(Number(r?.total) || 0)
      setPage(Number(r?.page) || p)
    } catch (e) {
      const detail = e?.response?.data?.message || e?.response?.data?.error || e?.message || String(e)
      setError('加载失败：' + detail)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchData(1)
    // 仅初次进入 + 筛选改变后由按钮触发
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const totalPages = useMemo(() => Math.max(1, Math.ceil(total / size)), [total, size])

  return (
    <div className="flex-1 overflow-auto p-8 max-w-6xl mx-auto w-full">
      <div className="flex items-center justify-between mb-4">
        <div>
          <h1 className="text-[18px] font-semibold text-gray-900">操作日志</h1>
          <div className="text-[12px] text-gray-500 mt-1">运营 Tab：所有 Skill / 文件 / 节点的写操作均自动留痕，可按操作类型 / 手机号筛选</div>
        </div>
        <button
          onClick={() => fetchData(1)}
          className="px-3 py-1.5 text-[13px] rounded-md text-white bg-brand-600 hover:bg-brand-700"
        >刷新</button>
      </div>

      {/* 筛选区 */}
      <div className="bg-white border border-gray-200 rounded-xl p-4 mb-4 flex items-end gap-3 flex-wrap">
        <div>
          <label className="block text-[12px] text-gray-500 mb-1">操作类型</label>
          <select
            value={action}
            onChange={(e) => setAction(e.target.value)}
            className="px-3 py-1.5 text-[13px] border border-gray-200 rounded-md focus:outline-none focus:border-brand-400 min-w-[160px]"
          >
            <option value="">全部</option>
            <option value="skill.create">创建 Skill</option>
            <option value="skill.update">更新 Skill</option>
            <option value="skill.delete">删除 Skill</option>
            <option value="skill.upload">上传文件</option>
          </select>
        </div>
        <div>
          <label className="block text-[12px] text-gray-500 mb-1">操作人手机号</label>
          <input
            value={actorPhone}
            onChange={(e) => setActorPhone(e.target.value)}
            placeholder="按手机号精确匹配"
            className="px-3 py-1.5 text-[13px] border border-gray-200 rounded-md focus:outline-none focus:border-brand-400 min-w-[200px]"
          />
        </div>
        <button
          onClick={() => fetchData(1)}
          className="px-3 py-1.5 text-[13px] rounded-md text-gray-700 border border-gray-200 hover:bg-gray-50"
        >筛选</button>
        <button
          onClick={() => { setAction(''); setActorPhone(''); setTimeout(() => fetchData(1), 0) }}
          className="px-3 py-1.5 text-[13px] rounded-md text-gray-500 hover:text-gray-700"
        >重置</button>
        <div className="ml-auto text-[12px] text-gray-400">共 {total} 条</div>
      </div>

      {error && (
        <div className="mb-3 text-[12px] text-rose-600 bg-rose-50 border border-rose-200 rounded-md px-3 py-2">
          {error}
        </div>
      )}

      {/* 列表 */}
      <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
        <table className="w-full text-[13px]">
          <thead className="bg-gray-50 text-gray-500 text-[12px]">
            <tr>
              <th className="text-left px-3 py-2 font-normal w-[160px]">时间</th>
              <th className="text-left px-3 py-2 font-normal w-[120px]">操作</th>
              <th className="text-left px-3 py-2 font-normal">操作人</th>
              <th className="text-left px-3 py-2 font-normal">目标</th>
              <th className="text-left px-3 py-2 font-normal">附加信息</th>
            </tr>
          </thead>
          <tbody>
            {loading && (
              <tr><td colSpan={5} className="px-3 py-8 text-center text-gray-400">加载中…</td></tr>
            )}
            {!loading && list.length === 0 && (
              <tr><td colSpan={5} className="px-3 py-8 text-center text-gray-400">暂无日志</td></tr>
            )}
            {!loading && list.map(row => {
              const meta = parseMeta(row.meta)
              const tag = ACTION_LABELS[row.action] || { label: row.action, color: 'bg-gray-100 text-gray-600' }
              return (
                <tr key={row.id} className="border-t border-gray-100 hover:bg-gray-50/60">
                  <td className="px-3 py-2 text-gray-600 whitespace-nowrap">{fmtTime(row.ts)}</td>
                  <td className="px-3 py-2">
                    <span className={`inline-block px-1.5 py-0.5 rounded text-[11px] ${tag.color}`}>{tag.label}</span>
                  </td>
                  <td className="px-3 py-2 text-gray-700">
                    <div className="font-medium text-gray-800">{row.actor_name || '-'}</div>
                    <div className="text-[11px] text-gray-400">{row.actor_phone || row.actor_email || ''}</div>
                  </td>
                  <td className="px-3 py-2 text-gray-700">
                    <div className="text-gray-800 truncate max-w-[260px]" title={row.target_name}>{row.target_name || '-'}</div>
                    <div className="text-[11px] text-gray-400">{row.target_type}{row.target_id ? ` · ${row.target_id}` : ''}</div>
                  </td>
                  <td className="px-3 py-2 text-[11px] text-gray-500 align-top max-w-[360px]">
                    {meta ? (
                      <pre className="whitespace-pre-wrap break-words font-mono leading-tight bg-gray-50 px-2 py-1 rounded border border-gray-100">
                        {typeof meta === 'string' ? meta : JSON.stringify(meta, null, 0)}
                      </pre>
                    ) : '—'}
                  </td>
                </tr>
              )
            })}
          </tbody>
        </table>
      </div>

      {/* 分页 */}
      {total > size && (
        <div className="mt-4 flex items-center justify-end gap-2 text-[13px]">
          <button
            disabled={page <= 1 || loading}
            onClick={() => fetchData(page - 1)}
            className="px-3 py-1 rounded-md border border-gray-200 text-gray-600 hover:bg-gray-50 disabled:opacity-40"
          >上一页</button>
          <span className="text-gray-500 px-2">第 {page} / {totalPages} 页</span>
          <button
            disabled={page >= totalPages || loading}
            onClick={() => fetchData(page + 1)}
            className="px-3 py-1 rounded-md border border-gray-200 text-gray-600 hover:bg-gray-50 disabled:opacity-40"
          >下一页</button>
        </div>
      )}
    </div>
  )
}
