import { useState } from 'react'
import { useApi } from '../hooks/useApi'
import { guardiaApi } from '../api/clients'
import { DataTable } from '../components/common/DataTable'
import type { AuditEntry } from '../api/types'

export default function AuditLog() {
  const [page, setPage] = useState(0)
  const { data, loading } = useApi<{ items: AuditEntry[]; total: number }>(
    guardiaApi, `/api/audit?page=${page}&size=20`, { deps: [page] }
  )
  const entries = data?.items ?? []
  const total   = data?.total ?? 0

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <DataTable<AuditEntry>
        cols={[
          { key: 'id',          header: 'ID',   width: 60 },
          { key: 'created_at',  header: '시각', width: 155, render: r => r.created_at?.slice(0, 16) },
          { key: 'username',    header: '사용자' },
          { key: 'action',      header: '액션' },
          { key: 'entity_type', header: '대상 유형' },
          { key: 'entity_id',   header: '대상 ID' },
          { key: 'ip_hash',     header: 'IP (해시)', render: r =>
            <span style={{ fontFamily: 'monospace', fontSize: 11, color: '#94a3b8' }}>
              {r.ip_hash?.slice(0, 12)}...
            </span> },
        ]}
        rows={entries}
        loading={loading}
        empty="감사 로그가 없습니다."
        toolbar={<span style={{ fontSize: 12, color: '#64748b' }}>전체 {total}건</span>}
      />

      {/* 페이지네이션 */}
      {total > 20 && (
        <div style={{ display: 'flex', justifyContent: 'center', gap: 6 }}>
          <button disabled={page === 0} onClick={() => setPage(0)}
            style={{ padding: '5px 10px', border: '1px solid #e2e8f0', borderRadius: 5,
              cursor: page === 0 ? 'not-allowed' : 'pointer', opacity: page === 0 ? .4 : 1 }}>
            «
          </button>
          <button disabled={page === 0} onClick={() => setPage(p => p - 1)}
            style={{ padding: '5px 10px', border: '1px solid #e2e8f0', borderRadius: 5,
              cursor: page === 0 ? 'not-allowed' : 'pointer', opacity: page === 0 ? .4 : 1 }}>
            ‹
          </button>
          <span style={{ padding: '5px 12px', fontSize: 13, color: '#64748b' }}>
            {page + 1} / {Math.ceil(total / 20)}
          </span>
          <button disabled={page >= Math.ceil(total / 20) - 1}
            onClick={() => setPage(p => p + 1)}
            style={{ padding: '5px 10px', border: '1px solid #e2e8f0', borderRadius: 5,
              cursor: 'pointer' }}>
            ›
          </button>
        </div>
      )}
    </div>
  )
}
