import { useEffect, useState } from 'react';
import api from '../../api/client';

const ACTION_COLORS = {
  REGISTER: 'var(--success)', LOGIN: 'var(--success)', LOGIN_FAIL: 'var(--danger)',
  LOGOUT: 'var(--text2)', PROJECT_CREATE: 'var(--accent2)', PROJECT_SUBMIT: 'var(--warn)',
  PROJECT_DELETE: 'var(--danger)', ADMIN_APPROVE: 'var(--success)', ADMIN_REJECT: 'var(--danger)',
  ADMIN_USER_DEACTIVATE: 'var(--danger)', ORDER_CREATE: 'var(--accent2)', PAYMENT_CONFIRM: 'var(--success)',
};

export default function AdminLogs() {
  const [data, setData]   = useState({ logs: [], total: 0, pages: 1 });
  const [page, setPage]   = useState(1);
  const [filter, setFilter] = useState({ action: '', userId: '' });
  const [loading, setLoading] = useState(true);

  function load() {
    setLoading(true);
    const params = new URLSearchParams({ page, limit: 50 });
    if (filter.action) params.set('action', filter.action);
    if (filter.userId) params.set('userId', filter.userId);
    api.get(`/admin/logs?${params}`)
      .then(r => setData(r.data))
      .catch(() => {})
      .finally(() => setLoading(false));
  }

  useEffect(() => { load(); }, [page]);

  return (
    <div className="container page">
      <div className="flex items-center justify-between" style={{ marginBottom: 20 }}>
        <h2>감사 로그</h2>
        <span className="text-muted" style={{ fontSize: 13 }}>총 {data.total.toLocaleString()}건</span>
      </div>

      <div style={{ display: 'flex', gap: 8, marginBottom: 20 }}>
        <input placeholder="Action 필터 (예: LOGIN)" value={filter.action}
          onChange={e => setFilter(f => ({ ...f, action: e.target.value }))} style={{ maxWidth: 200 }} />
        <input placeholder="User ID" value={filter.userId}
          onChange={e => setFilter(f => ({ ...f, userId: e.target.value }))} style={{ maxWidth: 200 }} />
        <button className="btn btn-outline" onClick={() => { setPage(1); load(); }}>검색</button>
      </div>

      {loading ? <div className="spinner" /> : (
        <>
          <div className="table-wrap">
            <table>
              <thead>
                <tr><th>시간</th><th>Action</th><th>사용자</th><th>대상</th><th>IP</th><th>상태</th></tr>
              </thead>
              <tbody>
                {data.logs.map(log => (
                  <tr key={log.id}>
                    <td style={{ fontSize: 12, color: 'var(--text2)', whiteSpace: 'nowrap' }}>
                      {new Date(log.createdAt).toLocaleString('ko-KR')}
                    </td>
                    <td>
                      <code style={{ fontSize: 12, color: ACTION_COLORS[log.action] || 'var(--text)', background: 'var(--bg3)', padding: '2px 6px', borderRadius: 4 }}>
                        {log.action}
                      </code>
                    </td>
                    <td style={{ fontSize: 12 }}>
                      {log.user ? `${log.user.nickname} (${log.user.email})` : '-'}
                    </td>
                    <td style={{ fontSize: 12, color: 'var(--text2)' }}>
                      {log.targetType ? `${log.targetType} ${log.targetId?.slice(0, 8)}...` : '-'}
                    </td>
                    <td style={{ fontSize: 12, color: 'var(--text2)' }}>{log.ipAddress}</td>
                    <td>
                      {log.responseStatus && (
                        <span style={{ fontSize: 12, color: log.responseStatus < 400 ? 'var(--success)' : 'var(--danger)' }}>
                          {log.responseStatus}
                        </span>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          {data.pages > 1 && (
            <div className="pagination">
              <button disabled={page <= 1} onClick={() => setPage(p => p - 1)}>이전</button>
              {Array.from({ length: Math.min(data.pages, 10) }, (_, i) => (
                <button key={i + 1} className={page === i + 1 ? 'active' : ''} onClick={() => setPage(i + 1)}>{i + 1}</button>
              ))}
              <button disabled={page >= data.pages} onClick={() => setPage(p => p + 1)}>다음</button>
            </div>
          )}
        </>
      )}
    </div>
  );
}
