import { useEffect, useState } from 'react'
import { ScrollText, Search } from 'lucide-react'
import { getAuditLogs } from '../api/client'

interface Log { id: number; action: string; actor: string; target?: string; detail?: string; createdAt: string | null }

export default function AuditLog() {
  const [list, setList] = useState<Log[]>([])
  const [action, setAction] = useState('')
  const [actor, setActor] = useState('')
  const [err, setErr] = useState('')

  const load = () =>
    getAuditLogs(action, actor, 200)
      .then(r => { setList(r.data?.data || []); setErr('') })
      .catch(e => setErr(e?.response?.status === 403 ? '권한이 없습니다 (Manager+).' : '감사 로그를 불러오지 못했습니다.'))
  useEffect(() => { load() }, [])

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-xl font-bold flex items-center gap-2"><ScrollText className="text-brand" size={20} /> 감사 로그</h1>
      </div>

      <div className="flex items-center gap-2 mb-4">
        <input placeholder="action 필터" value={action} onChange={e => setAction(e.target.value)} onKeyDown={e => e.key === 'Enter' && load()} className="inp w-44" />
        <input placeholder="actor 필터" value={actor} onChange={e => setActor(e.target.value)} onKeyDown={e => e.key === 'Enter' && load()} className="inp w-44" />
        <button onClick={load} className="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-card border border-edge text-sm hover:border-brand"><Search size={15} /> 검색</button>
      </div>

      {err && <div className="bg-rose-500/10 border border-rose-500/40 text-rose-300 text-sm rounded-lg px-4 py-2.5 mb-4">{err}</div>}

      <div className="bg-card border border-edge rounded-xl overflow-hidden">
        <table className="w-full text-sm">
          <thead className="text-slate-500 text-xs bg-panel">
            <tr><th className="text-left py-3 px-4">시각</th><th className="text-left">행위자</th><th className="text-left">액션</th><th className="text-left">대상</th><th className="text-left">상세</th></tr>
          </thead>
          <tbody>
            {list.map(l => (
              <tr key={l.id} className="border-t border-edge/50">
                <td className="py-3 px-4 text-slate-500 text-xs whitespace-nowrap">{l.createdAt ? new Date(l.createdAt).toLocaleString('ko-KR') : '-'}</td>
                <td className="text-slate-300">{l.actor}</td>
                <td><span className="px-2 py-0.5 rounded bg-brand/15 text-brand text-xs border border-brand/30">{l.action}</span></td>
                <td className="text-slate-400 font-mono text-xs">{l.target || '-'}</td>
                <td className="text-slate-400 text-xs truncate max-w-[360px]">{l.detail || '-'}</td>
              </tr>
            ))}
            {list.length === 0 && <tr><td colSpan={5} className="py-6 text-center text-slate-500">감사 로그가 없습니다.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  )
}
