import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { PageHeader, Toolbar, Table, Badge, TextInput, Button } from '../components/ui'
import { getAuditLogs } from '../api/client'

// 감사 로그 — 사용자·펌웨어배포·설정변경 등 작업 추적. 민감정보(비밀번호/키) 미기록.
export default function AuditLog() {
  const [action, setAction] = useState('')
  const [username, setUsername] = useState('')
  const [q, setQ] = useState<{ action?: string; username?: string }>({})

  const { data: logs = [], isLoading } = useQuery({
    queryKey: ['audit', q],
    queryFn: () => getAuditLogs({ ...(q.action && { action: q.action }), ...(q.username && { username: q.username }), limit: 200 }),
  })

  return (
    <div>
      <PageHeader title="감사 로그" subtitle="사용자·배포·설정 변경 등 관리 작업 추적 (민감정보 미기록)" />
      <Toolbar>
        <TextInput value={action} onChange={setAction} placeholder="action (예: FIRMWARE_DEPLOY)" className="w-56" />
        <TextInput value={username} onChange={setUsername} placeholder="사용자" className="w-40" />
        <Button icon="search" onClick={() => setQ({ action: action || undefined, username: username || undefined })}>검색</Button>
      </Toolbar>

      {isLoading ? <div className="p-8 text-center text-gray-400 text-sm">로딩 중...</div> : (
        <Table
          rowKey={(r: any) => r.id}
          rows={logs as any[]}
          columns={[
            { key: 'createdAt', header: '시각', render: r => <span className="text-xs text-gray-400">{(r.createdAt || '').replace('T', ' ').slice(0, 19)}</span> },
            { key: 'username', header: '사용자', render: r => <span className="text-white text-xs">{r.username}</span> },
            { key: 'action', header: '작업', render: r => <Badge tone="blue">{r.action}</Badge> },
            { key: 'resource', header: '리소스', render: r => <span className="text-xs text-gray-400">{r.resource}{r.resourceId ? ` #${r.resourceId}` : ''}</span> },
            { key: 'detail', header: '상세', render: r => <span className="text-xs text-gray-300">{r.detail}</span> },
            { key: 'success', header: '결과', render: r => <Badge tone={r.success ? 'green' : 'red'}>{r.success ? '성공' : '실패'}</Badge> },
          ]}
        />
      )}
    </div>
  )
}
