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

const actionColor: Record<string, string> = {
  FIRMWARE_DEPLOY:    'bg-purple-500/20 text-purple-300',
  FIRMWARE_UPDATE:    'bg-purple-500/20 text-purple-300',
  FIRMWARE_DELETE:    'bg-red-500/20 text-red-400',
  POS_PRICE_CHANGE:   'bg-amber-500/20 text-amber-300',
  USER_CREATE:        'bg-green-500/20 text-green-400',
  USER_UPDATE:        'bg-blue-500/20 text-blue-400',
  USER_DELETE:        'bg-red-500/20 text-red-400',
  USER_PASSWORD_RESET:'bg-blue-500/20 text-blue-400',
  USER_ACTIVE_TOGGLE: 'bg-blue-500/20 text-blue-400',
  TENANT_CREATE:      'bg-green-500/20 text-green-400',
  TENANT_UPDATE:      'bg-blue-500/20 text-blue-400',
  TENANT_DELETE:      'bg-red-500/20 text-red-400',
  SETTING_CHANGE:     'bg-cyan-500/20 text-cyan-300',
}

const ACTIONS = [
  '', 'FIRMWARE_DEPLOY', 'FIRMWARE_UPDATE', 'FIRMWARE_DELETE',
  'POS_PRICE_CHANGE', 'USER_CREATE', 'USER_UPDATE', 'USER_DELETE',
  'USER_PASSWORD_RESET', 'USER_ACTIVE_TOGGLE',
  'TENANT_CREATE', 'TENANT_UPDATE', 'TENANT_DELETE', 'SETTING_CHANGE',
]

export default function AuditLog() {
  const [action, setAction] = useState('')
  const [username, setUsername] = useState('')
  const [tenantCode, setTenantCode] = useState('')
  const [from, setFrom] = useState('')
  const [to, setTo] = useState('')
  const [applied, setApplied] = useState<Record<string, any>>({ limit: 200 })

  const { data: logs = [], isLoading, refetch, isFetching } = useQuery({
    queryKey: ['audit', applied],
    queryFn:  () => getAuditLogs(applied),
  })

  const search = () => {
    const p: Record<string, any> = { limit: 200 }
    if (action) p.action = action
    if (username.trim()) p.username = username.trim()
    if (tenantCode.trim()) p.tenantCode = tenantCode.trim()
    if (from) p.from = from + ':00'
    if (to) p.to = to + ':59'
    setApplied(p)
  }

  const reset = () => {
    setAction(''); setUsername(''); setTenantCode(''); setFrom(''); setTo('')
    setApplied({ limit: 200 })
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-semibold text-white">감사 로그</h1>
        <button
          onClick={() => refetch()}
          className="text-xs px-3 py-1.5 rounded bg-edge/60 text-gray-300 hover:bg-edge">
          {isFetching ? '조회 중...' : '새로고침'}
        </button>
      </div>

      {/* 필터 */}
      <div className="bg-card border border-edge rounded-lg p-4 grid grid-cols-1 md:grid-cols-6 gap-3 items-end">
        <div className="flex flex-col gap-1">
          <label className="text-xs text-gray-500">액션</label>
          <select value={action} onChange={e => setAction(e.target.value)}
            className="bg-panel border border-edge rounded px-2 py-1.5 text-sm text-gray-200">
            {ACTIONS.map(a => <option key={a} value={a}>{a || '전체'}</option>)}
          </select>
        </div>
        <div className="flex flex-col gap-1">
          <label className="text-xs text-gray-500">수행자</label>
          <input value={username} onChange={e => setUsername(e.target.value)} placeholder="username"
            className="bg-panel border border-edge rounded px-2 py-1.5 text-sm text-gray-200" />
        </div>
        <div className="flex flex-col gap-1">
          <label className="text-xs text-gray-500">테넌트</label>
          <input value={tenantCode} onChange={e => setTenantCode(e.target.value)} placeholder="EMART"
            className="bg-panel border border-edge rounded px-2 py-1.5 text-sm text-gray-200" />
        </div>
        <div className="flex flex-col gap-1">
          <label className="text-xs text-gray-500">시작 일시</label>
          <input type="datetime-local" value={from} onChange={e => setFrom(e.target.value)}
            className="bg-panel border border-edge rounded px-2 py-1.5 text-sm text-gray-200" />
        </div>
        <div className="flex flex-col gap-1">
          <label className="text-xs text-gray-500">종료 일시</label>
          <input type="datetime-local" value={to} onChange={e => setTo(e.target.value)}
            className="bg-panel border border-edge rounded px-2 py-1.5 text-sm text-gray-200" />
        </div>
        <div className="flex gap-2">
          <button onClick={search}
            className="flex-1 px-3 py-1.5 rounded bg-brand/80 text-white text-sm hover:bg-brand">조회</button>
          <button onClick={reset}
            className="px-3 py-1.5 rounded bg-edge/60 text-gray-300 text-sm hover:bg-edge">초기화</button>
        </div>
      </div>

      {isLoading ? (
        <div className="text-gray-400 p-8">로딩 중...</div>
      ) : (
        <div className="bg-card border border-edge rounded-lg overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-panel border-b border-edge">
              <tr>
                {['일시','수행자','테넌트','액션','리소스','대상','상세','IP','결과'].map(h => (
                  <th key={h} className="px-4 py-3 text-left text-xs text-gray-400 font-medium">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {(logs as any[]).map((l: any) => (
                <tr key={l.id} className="border-b border-edge hover:bg-edge/30">
                  <td className="px-4 py-3 text-gray-500 text-xs whitespace-nowrap">
                    {l.createdAt ? new Date(l.createdAt).toLocaleString('ko-KR') : '-'}
                  </td>
                  <td className="px-4 py-3 text-gray-300">{l.username || '-'}</td>
                  <td className="px-4 py-3 text-brand text-xs">{l.tenantCode || '-'}</td>
                  <td className="px-4 py-3">
                    <span className={`px-2 py-0.5 rounded text-xs ${actionColor[l.action] || 'bg-gray-500/20 text-gray-400'}`}>
                      {l.action}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-gray-400 text-xs">{l.resource || '-'}</td>
                  <td className="px-4 py-3 text-gray-400 text-xs">{l.resourceId || '-'}</td>
                  <td className="px-4 py-3 text-gray-400 text-xs max-w-xs truncate" title={l.detail}>{l.detail || '-'}</td>
                  <td className="px-4 py-3 text-gray-500 text-xs">{l.ipAddress || '-'}</td>
                  <td className="px-4 py-3">
                    <span className={`px-2 py-0.5 rounded text-xs ${l.success === false ? 'bg-red-500/20 text-red-400' : 'bg-green-500/20 text-green-400'}`}>
                      {l.success === false ? '실패' : '성공'}
                    </span>
                  </td>
                </tr>
              ))}
              {(logs as any[]).length === 0 && (
                <tr><td colSpan={9} className="px-4 py-8 text-center text-gray-500">감사 로그가 없습니다</td></tr>
              )}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}
