import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { ScrollText, Search } from 'lucide-react'
import { getAuditLogs } from '../api/client'

export default function AuditLog() {
  const [action, setAction] = useState('')
  const [actor, setActor] = useState('')
  const { data: logs } = useQuery({ queryKey: ['audit', action, actor], queryFn: () => getAuditLogs(action, actor, 200) })

  return (
    <div>
      <div className="flex items-center justify-between mb-5">
        <div className="flex items-center gap-2"><ScrollText className="text-brand" size={22} /><h1 className="text-xl font-bold">Audit Log</h1></div>
        <div className="flex items-center gap-2">
          <div className="flex items-center gap-2 bg-card border border-edge rounded-lg px-3 py-2"><Search size={14} className="text-slate-500" /><input value={actor} onChange={e => setActor(e.target.value)} placeholder="Actor" className="bg-transparent text-sm outline-none w-28" /></div>
          <input value={action} onChange={e => setAction(e.target.value)} placeholder="Filter action" className="bg-card border border-edge rounded-lg px-3 py-2 text-sm w-32" />
        </div>
      </div>
      <div className="bg-card border border-edge rounded-xl overflow-hidden">
        <table className="w-full text-sm">
          <thead><tr className="text-slate-400 text-xs border-b border-edge bg-panel">
            <th className="text-left p-3">Time</th><th className="text-left">Actor</th><th className="text-left">Action</th><th className="text-left">Target</th><th className="text-left">Details</th>
          </tr></thead>
          <tbody>
            {(logs || []).map((l: any, i: number) => (
              <tr key={l.id || i} className="border-b border-edge/50 hover:bg-panel/50">
                <td className="p-3 text-slate-400 text-xs whitespace-nowrap">{(l.createdAt || l.timestamp || '').slice(0, 19).replace('T', ' ')}</td>
                <td className="text-slate-300">{l.actor || l.username || '-'}</td>
                <td><span className="text-brand text-xs font-mono">{l.action}</span></td>
                <td className="text-slate-400 text-xs">{l.target || l.resource || '-'}</td>
                <td className="text-slate-500 text-xs max-w-md truncate">{l.detail || l.details || ''}</td>
              </tr>
            ))}
            {!(logs || []).length && <tr><td colSpan={5} className="text-center text-slate-500 py-8">No audit logs found.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  )
}
